forked from parseablehq/parseable
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream_schema_provider.rs
More file actions
1283 lines (1141 loc) · 42.6 KB
/
Copy pathstream_schema_provider.rs
File metadata and controls
1283 lines (1141 loc) · 42.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Parseable Server (C) 2022 - 2025 Parseable, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
use std::{any::Any, collections::HashMap, ops::Bound, sync::Arc};
use arrow_array::RecordBatch;
use arrow_schema::{Schema, SchemaRef, SortOptions};
use chrono::{DateTime, NaiveDateTime, TimeDelta, Timelike, Utc};
use datafusion::{
catalog::{SchemaProvider, Session},
common::{
Constraints, ToDFSchema,
stats::Precision,
tree_node::{TreeNode, TreeNodeRecursion},
},
datasource::{
MemTable, TableProvider,
file_format::{FileFormat, parquet::ParquetFormat},
listing::PartitionedFile,
physical_plan::{FileGroup, FileScanConfigBuilder, ParquetSource},
},
error::{DataFusionError, Result as DataFusionResult},
execution::object_store::ObjectStoreUrl,
logical_expr::{
BinaryExpr, Operator, TableProviderFilterPushDown, TableType, utils::conjunction,
},
physical_expr::{LexOrdering, PhysicalSortExpr, create_physical_expr, expressions::col},
physical_plan::{ExecutionPlan, Statistics, empty::EmptyExec, union::UnionExec},
prelude::Expr,
scalar::ScalarValue,
};
use futures_util::TryFutureExt;
use itertools::Itertools;
use crate::{
catalog::{
ManifestFile, Snapshot as CatalogSnapshot,
column::{Column, TypedStatistics},
manifest::File,
snapshot::{ManifestItem, Snapshot},
},
event::DEFAULT_TIMESTAMP_KEY,
hottier::HotTierManager,
metrics::{QUERY_CACHE_HIT, increment_files_scanned_in_query_by_date},
option::Mode,
parseable::{DEFAULT_TENANT, PARSEABLE, STREAM_EXISTS},
storage::{ObjectStorage, ObjectStoreFormat},
};
use super::listing_table_builder::ListingTableBuilder;
// schema provider for stream based on global data
#[derive(Debug)]
pub struct GlobalSchemaProvider {
pub storage: Arc<dyn ObjectStorage>,
pub tenant_id: Option<String>,
}
#[async_trait::async_trait]
impl SchemaProvider for GlobalSchemaProvider {
fn as_any(&self) -> &dyn Any {
self
}
fn table_names(&self) -> Vec<String> {
PARSEABLE.streams.list(&self.tenant_id)
}
async fn table(&self, name: &str) -> DataFusionResult<Option<Arc<dyn TableProvider>>> {
if self.table_exist(name) {
Ok(Some(Arc::new(StandardTableProvider {
schema: PARSEABLE
.get_stream(name, &self.tenant_id)
.expect(STREAM_EXISTS)
.get_schema(),
stream: name.to_owned(),
tenant_id: self.tenant_id.clone(),
})))
} else {
Ok(None)
}
}
fn table_exist(&self, name: &str) -> bool {
PARSEABLE.get_stream(name, &self.tenant_id).is_ok()
}
}
#[derive(Debug)]
struct StandardTableProvider {
schema: SchemaRef,
// prefix under which to find snapshot
stream: String,
tenant_id: Option<String>,
}
impl StandardTableProvider {
#[allow(clippy::too_many_arguments)]
async fn create_parquet_physical_plan(
&self,
execution_plans: &mut Vec<Arc<dyn ExecutionPlan>>,
object_store_url: ObjectStoreUrl,
partitions: Vec<Vec<PartitionedFile>>,
statistics: Statistics,
projection: Option<&Vec<usize>>,
filters: &[Expr],
limit: Option<usize>,
state: &dyn Session,
time_partition: Option<String>,
) -> Result<(), DataFusionError> {
let filters = if let Some(expr) = conjunction(filters.to_vec()) {
let table_df_schema = self.schema.as_ref().clone().to_dfschema()?;
let filters = create_physical_expr(&expr, &table_df_schema, state.execution_props())?;
Some(filters)
} else {
None
};
let sort_expr = PhysicalSortExpr {
expr: if let Some(time_partition) = time_partition {
col(&time_partition, &self.schema)?
} else {
col(DEFAULT_TIMESTAMP_KEY, &self.schema)?
},
options: SortOptions {
descending: true,
nulls_first: true,
},
};
let file_format = ParquetFormat::default().with_enable_pruning(true);
// create file groups from vec file partitions
let file_groups = partitions.into_iter().map(FileGroup::new).collect_vec();
// parquet file source, default table parquet options
let file_source = if let Some(phyiscal_expr) = filters {
ParquetSource::default().with_predicate(phyiscal_expr)
} else {
ParquetSource::default()
};
let mut conf_builder =
FileScanConfigBuilder::new(object_store_url, self.schema.clone(), file_source.into())
.with_statistics(statistics)
.with_batch_size(Some(20000))
.with_constraints(Constraints::default())
.with_file_groups(file_groups)
.with_output_ordering(vec![LexOrdering::new([sort_expr]).unwrap()]);
// Set projection if provided
if let Some(proj_indices) = projection {
conf_builder = conf_builder.with_projection_indices(Some(proj_indices.clone()));
}
// Set limit if provided
if let Some(lim) = limit {
conf_builder = conf_builder.with_limit(Some(lim));
}
let conf = conf_builder.build();
// create the execution plan
let plan = file_format
.create_physical_plan(
state,
// .as_any().downcast_ref::<SessionState>().unwrap(), // Remove this when ParquetFormat catches up
conf,
)
.await?;
execution_plans.push(plan);
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn get_hottier_exectuion_plan(
&self,
execution_plans: &mut Vec<Arc<dyn ExecutionPlan>>,
hot_tier_manager: &HotTierManager,
manifest_files: &mut Vec<File>,
projection: Option<&Vec<usize>>,
filters: &[Expr],
limit: Option<usize>,
state: &dyn Session,
time_partition: Option<String>,
) -> Result<(), DataFusionError> {
let hot_tier_files = hot_tier_manager
.get_hot_tier_manifest_files(manifest_files)
.await
.map_err(|err| DataFusionError::External(Box::new(err)))?;
let hot_tier_files: Vec<File> = hot_tier_files
.into_iter()
.map(|mut file| {
let path = PARSEABLE
.options
.hot_tier_storage_path
.as_ref()
.unwrap()
.join(&file.file_path);
file.file_path = path.to_str().unwrap().to_string();
file
})
.collect();
let (partitioned_files, statistics) = self.partitioned_files(hot_tier_files);
let object_store_url = "file:///";
self.create_parquet_physical_plan(
execution_plans,
ObjectStoreUrl::parse(object_store_url).unwrap(),
partitioned_files,
statistics,
projection,
filters,
limit,
state,
time_partition.clone(),
)
.await?;
Ok(())
}
/// Create an execution plan over the records in arrows and parquet that are still in staging, awaiting push to object storage
async fn get_staging_execution_plan(
&self,
execution_plans: &mut Vec<Arc<dyn ExecutionPlan>>,
projection: Option<&Vec<usize>>,
filters: &[Expr],
limit: Option<usize>,
state: &dyn Session,
time_partition: Option<&String>,
) -> Result<(), DataFusionError> {
let Ok(staging) = PARSEABLE.get_stream(&self.stream, &self.tenant_id) else {
return Ok(());
};
// Staging arrow exection plan
let records = staging.recordbatches_cloned(&self.schema);
let arrow_exec = reversed_mem_table(records, self.schema.clone())?
.scan(state, projection, filters, limit)
.await?;
execution_plans.push(arrow_exec);
// Get a list of parquet files still in staging, order by filename
let mut parquet_files = staging.parquet_files();
parquet_files.sort_by(|a, b| a.cmp(b).reverse());
// NOTE: We don't partition among CPUs to ensure consistent results.
// i.e. We were seeing in-consistent ordering when querying over parquets in staging.
let mut partitioned_files = Vec::with_capacity(parquet_files.len());
for file_path in parquet_files {
let Ok(file_meta) = file_path.metadata() else {
continue;
};
let file = PartitionedFile::new(file_path.display().to_string(), file_meta.len());
partitioned_files.push(file)
}
// // NOTE: There is the possibility of a parquet file being pushed to object store
// // and deleted from staging in the time it takes for datafusion to get to it.
// // Staging parquet execution plan
// let object_store_url = if let Some(tenant_id) = self.tenant_id.as_ref() {
// &format!("file://{tenant_id}/")
// } else {
// "file:///"
// };
let object_store_url = "file:///";
self.create_parquet_physical_plan(
execution_plans,
ObjectStoreUrl::parse(object_store_url).unwrap(),
vec![partitioned_files],
Statistics::new_unknown(&self.schema),
projection,
filters,
limit,
state,
time_partition.cloned(),
)
.await
}
#[allow(clippy::too_many_arguments)]
async fn legacy_listing_table(
&self,
execution_plans: &mut Vec<Arc<dyn ExecutionPlan>>,
glob_storage: Arc<dyn ObjectStorage>,
time_filters: &[PartialTimeFilter],
state: &dyn Session,
projection: Option<&Vec<usize>>,
filters: &[Expr],
limit: Option<usize>,
time_partition: Option<String>,
) -> Result<(), DataFusionError> {
ListingTableBuilder::new(self.stream.to_owned())
.populate_via_listing(glob_storage.clone(), time_filters)
.and_then(|builder| async {
let table = builder.build(
self.schema.clone(),
|x| glob_storage.query_prefixes(x),
time_partition,
)?;
if let Some(table) = table {
let plan = table.scan(state, projection, filters, limit).await?;
execution_plans.push(plan);
}
Ok(())
})
.await?;
Ok(())
}
fn final_plan(
&self,
mut execution_plans: Vec<Arc<dyn ExecutionPlan>>,
projection: Option<&Vec<usize>>,
) -> Result<Arc<dyn ExecutionPlan>, DataFusionError> {
let exec: Arc<dyn ExecutionPlan> = if execution_plans.is_empty() {
let schema = match projection {
Some(projection) => Arc::new(self.schema.project(projection)?),
None => self.schema.to_owned(),
};
Arc::new(EmptyExec::new(schema))
} else if execution_plans.len() == 1 {
execution_plans.pop().unwrap()
} else {
UnionExec::try_new(execution_plans)?
};
Ok(exec)
}
fn partitioned_files(
&self,
manifest_files: Vec<File>,
) -> (Vec<Vec<PartitionedFile>>, datafusion::common::Statistics) {
let target_partition: usize = num_cpus::get();
let mut partitioned_files = Vec::from_iter((0..target_partition).map(|_| Vec::new()));
let mut column_statistics = HashMap::<String, Option<TypedStatistics>>::new();
let mut count = 0;
let mut file_count = 0u64;
for (index, file) in manifest_files
.into_iter()
.enumerate()
.map(|(x, y)| (x % target_partition, y))
{
#[allow(unused_mut)]
let File {
mut file_path,
num_rows,
columns,
..
} = file;
// Track billing metrics for files scanned in query
file_count += 1;
// object_store::path::Path doesn't automatically deal with Windows path separators
// to do that, we are using from_absolute_path() which takes into consideration the underlying filesystem
// before sending the file path to PartitionedFile
// the github issue- https://github.com/parseablehq/parseable/issues/824
// For some reason, the `from_absolute_path()` doesn't work for macos, hence the ugly solution
// TODO: figure out an elegant solution to this
#[cfg(windows)]
{
if PARSEABLE.storage.name() == "drive" {
file_path = object_store::path::Path::from_absolute_path(file_path)
.unwrap()
.to_string();
}
}
let pf = PartitionedFile::new(file_path, file.file_size);
partitioned_files[index].push(pf);
columns.into_iter().for_each(|col| {
column_statistics
.entry(col.name)
.and_modify(|x| {
if let Some((stats, col_stats)) = x.as_ref().cloned().zip(col.stats.clone())
{
*x = Some(stats.update(col_stats));
}
})
.or_insert_with(|| col.stats.as_ref().cloned());
});
count += num_rows;
}
let statistics = self
.schema
.fields()
.iter()
.map(|field| {
column_statistics
.get(field.name())
.and_then(|stats| stats.as_ref())
.and_then(|stats| stats.clone().min_max_as_scalar(field.data_type()))
.map(|(min, max)| datafusion::common::ColumnStatistics {
null_count: Precision::Absent,
max_value: Precision::Exact(max),
min_value: Precision::Exact(min),
distinct_count: Precision::Absent,
sum_value: Precision::Absent,
})
.unwrap_or_default()
})
.collect();
let statistics = datafusion::common::Statistics {
num_rows: Precision::Exact(count as usize),
total_byte_size: Precision::Absent,
column_statistics: statistics,
};
// Track billing metrics for query scan
let current_date = chrono::Utc::now().date_naive().to_string();
increment_files_scanned_in_query_by_date(
file_count,
¤t_date,
self.tenant_id.as_deref().unwrap_or(DEFAULT_TENANT),
);
(partitioned_files, statistics)
}
}
async fn collect_from_snapshot(
snapshot: &Snapshot,
time_filters: &[PartialTimeFilter],
filters: &[Expr],
limit: Option<usize>,
stream_name: &str,
tenant_id: &Option<String>,
) -> Result<Vec<File>, DataFusionError> {
let mut manifest_files = Vec::new();
for manifest_item in snapshot.manifests(time_filters) {
let manifest_opt = PARSEABLE
.metastore
.get_manifest(
stream_name,
manifest_item.time_lower_bound,
manifest_item.time_upper_bound,
Some(manifest_item.manifest_path),
tenant_id,
)
.await
.map_err(|e| DataFusionError::Plan(e.to_string()))?;
if let Some(manifest) = manifest_opt {
manifest_files.push(manifest);
} else {
tracing::warn!(
"Manifest missing for stream={} [{:?} - {:?}]",
stream_name,
manifest_item.time_lower_bound,
manifest_item.time_upper_bound
);
}
}
let mut manifest_files: Vec<_> = manifest_files
.into_iter()
.flat_map(|file| file.files)
.rev()
.collect();
for filter in filters {
manifest_files.retain(|file| !file.can_be_pruned(filter))
}
if let Some(limit) = limit {
let limit = limit as u64;
let mut curr_limit = 0;
let mut pos = None;
for (index, file) in manifest_files.iter().enumerate() {
curr_limit += file.num_rows();
if curr_limit >= limit {
pos = Some(index);
break;
}
}
if let Some(pos) = pos {
manifest_files.truncate(pos + 1);
}
}
Ok(manifest_files)
}
#[async_trait::async_trait]
impl TableProvider for StandardTableProvider {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn schema(&self) -> SchemaRef {
self.schema.clone()
}
fn table_type(&self) -> TableType {
TableType::Base
}
async fn scan(
&self,
state: &dyn Session,
projection: Option<&Vec<usize>>,
filters: &[Expr],
limit: Option<usize>,
) -> Result<Arc<dyn ExecutionPlan>, DataFusionError> {
let mut execution_plans = vec![];
let glob_storage = PARSEABLE.storage.get_object_store();
let object_store_format: ObjectStoreFormat = serde_json::from_slice(
&PARSEABLE
.metastore
.get_stream_json(&self.stream, false, &self.tenant_id)
.await
.map_err(|e| DataFusionError::Plan(e.to_string()))?,
)
.map_err(|e| DataFusionError::Plan(e.to_string()))?;
let time_partition = object_store_format.time_partition;
let mut time_filters = extract_primary_filter(filters, &time_partition);
if is_within_staging_window(&time_filters) {
self.get_staging_execution_plan(
&mut execution_plans,
projection,
filters,
limit,
state,
time_partition.as_ref(),
)
.await?;
};
let mut merged_snapshot = Snapshot::default();
if PARSEABLE.options.mode == Mode::Query || PARSEABLE.options.mode == Mode::Prism {
let obs = PARSEABLE
.metastore
.get_all_stream_jsons(&self.stream, None, &self.tenant_id)
.await;
if let Ok(obs) = obs {
for ob in obs {
if let Ok(object_store_format) =
serde_json::from_slice::<ObjectStoreFormat>(&ob)
{
let snapshot = object_store_format.snapshot;
for manifest in snapshot.manifest_list {
merged_snapshot.manifest_list.push(manifest);
}
}
}
}
} else {
merged_snapshot = object_store_format.snapshot;
}
// Is query timerange is overlapping with older data.
// if true, then get listing table time filters and execution plan separately
if is_overlapping_query(&merged_snapshot.manifest_list, &time_filters) {
let listing_time_fiters =
return_listing_time_filters(&merged_snapshot.manifest_list, &mut time_filters);
if let Some(listing_time_filter) = listing_time_fiters {
self.legacy_listing_table(
&mut execution_plans,
glob_storage.clone(),
&listing_time_filter,
state,
projection,
filters,
limit,
time_partition.clone(),
)
.await?;
}
}
let mut manifest_files = collect_from_snapshot(
&merged_snapshot,
&time_filters,
filters,
limit,
&self.stream,
&self.tenant_id,
)
.await?;
if manifest_files.is_empty() {
return self.final_plan(execution_plans, projection);
}
// Hot tier data fetch
if let Some(hot_tier_manager) = HotTierManager::global()
&& hot_tier_manager.check_stream_hot_tier_exists(&self.stream, &self.tenant_id)
{
self.get_hottier_exectuion_plan(
&mut execution_plans,
hot_tier_manager,
&mut manifest_files,
projection,
filters,
limit,
state,
time_partition.clone(),
)
.await?;
}
if manifest_files.is_empty() {
QUERY_CACHE_HIT
.with_label_values(&[
&self.stream,
self.tenant_id.as_deref().unwrap_or(DEFAULT_TENANT),
])
.inc();
return self.final_plan(execution_plans, projection);
}
let (partitioned_files, statistics) = self.partitioned_files(manifest_files);
let object_store_url = glob_storage.store_url();
self.create_parquet_physical_plan(
&mut execution_plans,
ObjectStoreUrl::parse(object_store_url).unwrap(),
partitioned_files,
statistics,
projection,
filters,
limit,
state,
time_partition.clone(),
)
.await?;
Ok(self.final_plan(execution_plans, projection)?)
}
/*
Updated the function signature (and name)
Now it handles multiple filters
*/
fn supports_filters_pushdown(
&self,
filters: &[&Expr],
) -> Result<Vec<TableProviderFilterPushDown>, DataFusionError> {
let res_vec = filters
.iter()
.map(|filter| {
if expr_in_boundary(filter) {
// if filter can be handled by time partiton pruning, it is exact
TableProviderFilterPushDown::Exact
} else {
// otherwise, we still might be able to handle the filter with file
// level mechanisms such as Parquet row group pruning.
TableProviderFilterPushDown::Inexact
}
})
.collect_vec();
Ok(res_vec)
}
}
fn reversed_mem_table(
mut records: Vec<RecordBatch>,
schema: Arc<Schema>,
) -> Result<MemTable, DataFusionError> {
records[..].reverse();
records
.iter_mut()
.for_each(|batch| *batch = crate::utils::arrow::reverse(batch));
MemTable::try_new(schema, vec![records])
}
#[derive(Debug, Clone)]
pub enum PartialTimeFilter {
Low(Bound<NaiveDateTime>),
High(Bound<NaiveDateTime>),
Eq(NaiveDateTime),
}
impl PartialTimeFilter {
fn try_from_expr(expr: &Expr, time_partition: &Option<String>) -> Option<Self> {
let Expr::BinaryExpr(binexpr) = expr else {
return None;
};
let (op, time) = extract_timestamp_bound(binexpr, time_partition)?;
let value = match op {
Operator::Gt => PartialTimeFilter::Low(Bound::Excluded(time)),
Operator::GtEq => PartialTimeFilter::Low(Bound::Included(time)),
Operator::Lt => PartialTimeFilter::High(Bound::Excluded(time)),
Operator::LtEq => PartialTimeFilter::High(Bound::Included(time)),
Operator::Eq => PartialTimeFilter::Eq(time),
Operator::IsNotDistinctFrom => PartialTimeFilter::Eq(time),
_ => return None,
};
Some(value)
}
pub fn binary_expr(&self, left: Expr) -> Expr {
let (op, right) = match self {
PartialTimeFilter::Low(Bound::Excluded(time)) => {
(Operator::Gt, time.and_utc().timestamp_millis())
}
PartialTimeFilter::Low(Bound::Included(time)) => {
(Operator::GtEq, time.and_utc().timestamp_millis())
}
PartialTimeFilter::High(Bound::Excluded(time)) => {
(Operator::Lt, time.and_utc().timestamp_millis())
}
PartialTimeFilter::High(Bound::Included(time)) => {
(Operator::LtEq, time.and_utc().timestamp_millis())
}
PartialTimeFilter::Eq(time) => (Operator::Eq, time.and_utc().timestamp_millis()),
_ => unimplemented!(),
};
Expr::BinaryExpr(BinaryExpr::new(
Box::new(left),
op,
Box::new(Expr::Literal(
ScalarValue::TimestampMillisecond(Some(right), None),
None,
)),
))
}
}
fn is_overlapping_query(
manifest_list: &[ManifestItem],
time_filters: &[PartialTimeFilter],
) -> bool {
// This is for backwards compatiblity. Older table format relies on listing.
// if the start time is lower than lower bound of first file then we consider it overlapping
let Some(first_entry_lower_bound) =
manifest_list.iter().map(|file| file.time_lower_bound).min()
else {
return true;
};
for filter in time_filters {
match filter {
PartialTimeFilter::Low(Bound::Excluded(time))
| PartialTimeFilter::Low(Bound::Included(time)) => {
if time < &first_entry_lower_bound.naive_utc() {
return true;
}
}
_ => {}
}
}
false
}
/// This function will accept time filters provided to the query and will split them
/// into listing time filters and manifest time filters
/// This makes parseable backwards compatible for when it did not have manifests
/// Logic-
/// The control flow will only come to this function if there exists data without manifest files
/// Two new time filter vec![] are created
/// For listing table time filters, we will use OG time filter low bound and either OG time filter upper bound
/// or manifest lower bound
/// For manifest time filter, we will manifest lower bound and OG upper bound
fn return_listing_time_filters(
manifest_list: &[ManifestItem],
time_filters: &mut Vec<PartialTimeFilter>,
) -> Option<Vec<PartialTimeFilter>> {
if manifest_list.is_empty() {
return Some(time_filters.clone());
}
// vec to hold timestamps for listing
let mut vec_listing_timestamps = Vec::new();
let mut first_entry_lower_bound = manifest_list
.iter()
.map(|file| file.time_lower_bound.naive_utc())
.min()?;
let mut new_time_filters = vec![PartialTimeFilter::Low(Bound::Included(
first_entry_lower_bound,
))];
time_filters.iter_mut().for_each(|filter| {
match filter {
// since we've already determined that there is a need to list tables,
// we just need to check whether the filter's upper bound is < manifest lower bound
PartialTimeFilter::High(Bound::Included(upper))
| PartialTimeFilter::High(Bound::Excluded(upper)) => {
if upper.lt(&&mut first_entry_lower_bound) {
// filter upper bound is less than manifest lower bound, continue using filter upper bound
vec_listing_timestamps.push(filter.clone());
} else {
// use manifest lower bound as excluded
vec_listing_timestamps.push(PartialTimeFilter::High(Bound::Excluded(
first_entry_lower_bound,
)));
}
new_time_filters.push(filter.clone());
}
_ => {
vec_listing_timestamps.push(filter.clone());
}
}
});
// update time_filters
*time_filters = new_time_filters;
if vec_listing_timestamps.len().gt(&0) {
Some(vec_listing_timestamps)
} else {
None
}
}
/// We should consider data in staging for queries concerning a time period,
/// ending within 5 minutes from now. e.g. If current time is 5
pub fn is_within_staging_window(time_filters: &[PartialTimeFilter]) -> bool {
let five_minutes_back = (Utc::now() - TimeDelta::minutes(5))
.with_second(0)
.and_then(|x| x.with_nanosecond(0))
.expect("zeroed value is valid")
.naive_utc();
if time_filters.iter().any(|filter| match filter {
PartialTimeFilter::High(Bound::Excluded(time))
| PartialTimeFilter::High(Bound::Included(time))
| PartialTimeFilter::Eq(time) => time >= &five_minutes_back,
_ => false,
}) {
return true;
}
// does it even have a higher bound
let has_upper_bound = time_filters
.iter()
.any(|filter| matches!(filter, PartialTimeFilter::High(_)));
!has_upper_bound
}
fn expr_in_boundary(filter: &Expr) -> bool {
let Expr::BinaryExpr(binexpr) = filter else {
return false;
};
let Some((op, time)) = extract_timestamp_bound(binexpr, &None) else {
return false;
};
// this is due to knowlege of prefixes being minute long always.
// Without a consistent partition spec this cannot be guarenteed.
time.second() == 0
&& time.nanosecond() == 0
&& matches!(
op,
Operator::Gt | Operator::GtEq | Operator::Lt | Operator::LtEq
)
}
fn extract_timestamp_bound(
binexpr: &BinaryExpr,
time_partition: &Option<String>,
) -> Option<(Operator, NaiveDateTime)> {
let Expr::Literal(value, None) = binexpr.right.as_ref() else {
return None;
};
let is_time_partition = match (binexpr.left.as_ref(), time_partition) {
(Expr::Column(column), Some(time_partition)) => &column.name == time_partition,
_ => false,
};
match value {
ScalarValue::TimestampMillisecond(Some(value), _) => Some((
binexpr.op,
DateTime::from_timestamp_millis(*value).unwrap().naive_utc(),
)),
ScalarValue::TimestampNanosecond(Some(value), _) => Some((
binexpr.op,
DateTime::from_timestamp_nanos(*value).naive_utc(),
)),
ScalarValue::Utf8(Some(str_value)) if is_time_partition => {
match str_value.parse::<NaiveDateTime>() {
Ok(dt) => Some((binexpr.op, dt)),
Err(_) => None,
}
}
_ => None,
}
}
// Extract start time and end time from filter predicate
pub fn extract_primary_filter(
filters: &[Expr],
time_partition: &Option<String>,
) -> Vec<PartialTimeFilter> {
filters
.iter()
.filter_map(|expr| {
let mut time_filter = None;
let _ = expr.apply(&mut |expr| {
if let Some(time) = PartialTimeFilter::try_from_expr(expr, time_partition) {
time_filter = Some(time);
Ok(TreeNodeRecursion::Stop) // Stop further traversal
} else {
Ok(TreeNodeRecursion::Jump) // Skip this node
}
});
time_filter
})
.collect()
}
pub trait ManifestExt: ManifestFile {
fn find_matching_column(&self, partial_filter: &Expr) -> Option<&Column> {
let name = match partial_filter {
Expr::BinaryExpr(binary_expr) => {
let Expr::Column(col) = binary_expr.left.as_ref() else {
return None;
};
&col.name
}
_ => {
return None;
}
};
self.columns().iter().find(|col| &col.name == name)
}
fn can_be_pruned(&self, partial_filter: &Expr) -> bool {
fn extract_op_scalar(expr: &Expr) -> Option<(Operator, &ScalarValue)> {
let Expr::BinaryExpr(expr) = expr else {
return None;
};
let Expr::Literal(value, None) = &*expr.right else {
return None;
};
/* `BinaryExp` doesn't implement `Copy` */
Some((expr.op, value))
}
let Some(col) = self.find_matching_column(partial_filter) else {
return false;
};
let Some((op, value)) = extract_op_scalar(partial_filter) else {
return false;
};
let Some(value) = cast_or_none(value) else {
return false;
};
let Some(stats) = &col.stats else {
return false;
};
!satisfy_constraints(value, op, stats).unwrap_or(true)
}
}
impl<T: ManifestFile> ManifestExt for T {}
enum CastRes<'a> {
Bool(bool),
Int(i64),
Float(f64),
String(&'a str),
}
fn cast_or_none(scalar: &ScalarValue) -> Option<CastRes<'_>> {
match scalar {
ScalarValue::Null => None,
ScalarValue::Boolean(val) => val.map(CastRes::Bool),
ScalarValue::Float32(val) => val.map(|val| CastRes::Float(val as f64)),
ScalarValue::Float64(val) => val.map(CastRes::Float),
ScalarValue::Int8(val) => val.map(|val| CastRes::Int(val as i64)),
ScalarValue::Int16(val) => val.map(|val| CastRes::Int(val as i64)),
ScalarValue::Int32(val) => val.map(|val| CastRes::Int(val as i64)),