Repository navigation
Expand file tree
/
Copy pathfiltered_read.rs
More file actions
3656 lines (3317 loc) · 139 KB
/
Copy pathfiltered_read.rs
File metadata and controls
3656 lines (3317 loc) · 139 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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Lance Authors
use std::any::Any;
use std::collections::{BTreeMap, HashMap};
use std::pin::Pin;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::{ops::Range, sync::Arc};
use arrow::array::AsArray;
use arrow::datatypes::UInt32Type;
use arrow_array::RecordBatch;
use arrow_schema::SchemaRef;
use datafusion::common::runtime::SpawnedTask;
use datafusion::common::stats::Precision;
use datafusion::error::{DataFusionError, Result as DataFusionResult};
use datafusion::execution::{SendableRecordBatchStream, TaskContext};
use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
use datafusion::physical_plan::{
DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties,
execution_plan::{Boundedness, EmissionType},
};
use datafusion_expr::Expr;
use datafusion_physical_expr::{EquivalenceProperties, Partitioning, PhysicalExpr};
use datafusion_physical_plan::Statistics;
use datafusion_physical_plan::filter::FilterExec;
use datafusion_physical_plan::metrics::{BaselineMetrics, Count, MetricsSet, Time};
use futures::stream::BoxStream;
use futures::{FutureExt, Stream, StreamExt, TryFutureExt, TryStreamExt, future};
use lance_arrow::RecordBatchExt;
use lance_core::datatypes::OnMissing;
use lance_core::utils::deletion::DeletionVector;
use lance_core::utils::futures::FinallyStreamExt;
use lance_core::utils::mask::{
RowAddrMask, RowAddrSelection, RowAddrTreeMap, bitmap_to_ranges, ranges_to_bitmap,
};
use lance_core::utils::tokio::get_num_compute_intensive_cpus;
use lance_core::{Error, Result, datatypes::Projection};
use lance_datafusion::planner::Planner;
use lance_datafusion::utils::{
ExecutionPlanMetricsSetExt, FRAGMENTS_SCANNED_METRIC, RANGES_SCANNED_METRIC,
ROWS_SCANNED_METRIC, TASK_WAIT_TIME_METRIC,
};
use lance_index::scalar::expression::{FilterPlan, IndexExprResult};
use lance_io::scheduler::{ScanScheduler, SchedulerConfig};
use lance_table::format::Fragment;
use lance_table::rowids::RowIdSequence;
use lance_table::utils::stream::ReadBatchFut;
use roaring::RoaringBitmap;
use tokio::sync::{Mutex as AsyncMutex, OnceCell};
use tracing::{Instrument, instrument};
use crate::Dataset;
use crate::dataset::fragment::{FileFragment, FragReadConfig};
use crate::dataset::rowids::load_row_id_sequence;
use crate::dataset::scanner::{
BATCH_SIZE_FALLBACK, DEFAULT_FRAGMENT_READAHEAD, get_default_batch_size,
};
use super::utils::IoMetrics;
#[derive(Debug)]
pub struct EvaluatedIndex {
index_result: IndexExprResult,
applicable_fragments: RoaringBitmap,
}
impl EvaluatedIndex {
/// Get the row id mask representing which rows matched the index filter.
pub fn index_result(&self) -> &IndexExprResult {
&self.index_result
}
/// Get a reference to the applicable fragments bitmap, containing the set of fragment IDs
/// implicated by the filter.
pub fn applicable_fragments(&self) -> &RoaringBitmap {
&self.applicable_fragments
}
pub fn try_from_arrow(batch: &RecordBatch) -> Result<Self> {
if batch.num_rows() != 2 {
return Err(Error::invalid_input_source(
format!(
"Expected a batch with exactly 2 rows but there are {} rows",
batch.num_rows()
)
.into(),
));
}
if batch.num_columns() != 3 {
return Err(Error::invalid_input_source(
format!(
"Expected a batch with exactly two columns but there are {} columns",
batch.num_columns()
)
.into(),
));
}
let row_addr_mask = RowAddrMask::from_arrow(batch.column(0).as_binary())?;
let match_type = batch.column(1).as_primitive::<UInt32Type>().values()[0];
let index_result = IndexExprResult::from_parts(row_addr_mask, match_type)?;
let applicable_fragments = batch.column(2).as_binary::<i32>();
let applicable_fragments = RoaringBitmap::deserialize_from(applicable_fragments.value(0))?;
Ok(Self {
index_result,
applicable_fragments,
})
}
}
/// A fragment along with ranges of row offsets to read
struct ScopedFragmentRead {
fragment: Arc<FileFragment>,
ranges: Vec<Range<u64>>,
projection: Arc<Projection>,
with_deleted_rows: bool,
batch_size: u32,
// An in-memory filter to apply after reading the fragment (whatever couldn't be
// pushed down into the index query)
filter: Option<Expr>,
priority: u32,
scan_scheduler: Arc<ScanScheduler>,
}
impl ScopedFragmentRead {
fn frag_read_config(&self) -> FragReadConfig {
FragReadConfig::default()
.with_row_id(self.with_deleted_rows || self.projection.with_row_id)
.with_row_address(self.projection.with_row_addr)
.with_row_last_updated_at_version(self.projection.with_row_last_updated_at_version)
.with_row_created_at_version(self.projection.with_row_created_at_version)
.with_scan_scheduler(self.scan_scheduler.clone())
.with_reader_priority(self.priority)
}
}
/// A fragment with all of its metadata loaded
#[derive(Debug, Clone)]
struct LoadedFragment {
row_id_sequence: Arc<RowIdSequence>,
deletion_vector: Option<Arc<DeletionVector>>,
fragment: Arc<FileFragment>,
// The number of physical rows in the fragment
//
// This count includes deleted rows
num_physical_rows: u64,
// The number of logical rows in the fragment
//
// This count does not include deleted rows
num_logical_rows: u64,
}
/// Given a sorted iterator of deleted row offsets, return a sorted iterator of valid row ranges
///
/// For example, given a fragment with 100 rows, and a deletion vector of 10, 15, 16 this would
/// return 0..10, 11..15, 17..100
struct DvToValidRanges<I: Iterator<Item = u64> + Send> {
deleted_rows: I,
num_rows: u64,
position: u64,
}
impl<I: Iterator<Item = u64> + Send> DvToValidRanges<I> {
fn new(deleted_rows: I, num_rows: u64) -> Self {
Self {
deleted_rows,
num_rows,
position: 0,
}
}
}
impl<I: Iterator<Item = u64> + Send> Iterator for DvToValidRanges<I> {
type Item = Range<u64>;
fn next(&mut self) -> Option<Self::Item> {
if self.position >= self.num_rows {
return None;
}
for next_deleted_row in self.deleted_rows.by_ref() {
if next_deleted_row == self.position {
self.position += 1;
} else {
let position = self.position;
self.position = next_deleted_row + 1;
return Some(position..next_deleted_row);
}
}
let position = self.position;
self.position = self.num_rows;
if position == self.num_rows {
// Last deleted row was end of the fragment, return None
None
} else {
// Still some rows after the last deleted row, return them
Some(position..self.num_rows)
}
}
}
/// Global metrics for the FilteredReadExec node
///
/// These represent work that is not divisible by partition and this work is always
/// reported on partition 0
pub struct FilteredReadGlobalMetrics {
fragments_scanned: Count,
ranges_scanned: Count,
rows_scanned: Count,
io_metrics: IoMetrics,
}
impl FilteredReadGlobalMetrics {
pub fn new(metrics: &ExecutionPlanMetricsSet) -> Self {
Self {
fragments_scanned: metrics.new_count(FRAGMENTS_SCANNED_METRIC, 0),
ranges_scanned: metrics.new_count(RANGES_SCANNED_METRIC, 0),
rows_scanned: metrics.new_count(ROWS_SCANNED_METRIC, 0),
io_metrics: IoMetrics::new(metrics, 0),
}
}
}
/// Partition metrics for the FilteredReadExec node
///
/// These represent work that is divisible by partition and this work is reported on the
/// partition that it belongs to
pub struct FilteredReadPartitionMetrics {
// Records the amount of time spent waiting on the lock to grab the next task
//
// This should typically be fairly small relative to the overall execution time. If this
// value is large then it means we are bottlenecked on the read scheduler which is preventing
// this partition from being utilized.
task_wait_time: Time,
baseline_metrics: BaselineMetrics,
}
impl FilteredReadPartitionMetrics {
pub fn new(metrics: &ExecutionPlanMetricsSet, partition: usize) -> Self {
Self {
task_wait_time: metrics.new_time(TASK_WAIT_TIME_METRIC, partition),
baseline_metrics: BaselineMetrics::new(metrics, partition),
}
}
}
/// Tracks the number of ranges scanned based on the number of rows processed
struct RangeMetricsTracker {
ranges: Vec<Range<u64>>,
cumulative_rows: usize,
current_range_index: usize,
rows_processed_in_range: usize,
}
impl RangeMetricsTracker {
fn new(ranges: Vec<Range<u64>>) -> Self {
Self {
ranges,
cumulative_rows: 0,
current_range_index: 0,
rows_processed_in_range: 0,
}
}
// Counts ranges started scanning (not necessarily finished).
fn incremental_ranges_scanned(&mut self, num_rows: usize) -> usize {
self.cumulative_rows += num_rows;
let mut additional_ranges = 0;
while self.current_range_index < self.ranges.len() {
let current_range = &self.ranges[self.current_range_index];
let range_size = (current_range.end - current_range.start) as usize;
if self.cumulative_rows >= range_size {
// We've completed this range
if self.rows_processed_in_range == 0 {
// We are completing a range we never started
additional_ranges += 1;
}
self.cumulative_rows -= range_size;
self.current_range_index += 1;
self.rows_processed_in_range = 0;
} else {
// Still within the current range
if self.rows_processed_in_range == 0 {
additional_ranges += 1;
}
self.rows_processed_in_range += num_rows;
break;
}
}
additional_ranges
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilteredReadThreadingMode {
/// This mode allows for multi-threading to be used even if there is only a single
/// partition. In this mode, readahead will be added via the try_buffered method.
///
/// This mode is slightly less efficient as it is unlikely the decode will happen
/// on the same thread as any downstream logic. However, it is simple, and the reads
/// are sequential.
///
/// The number of threads is specified by the parameter
OnePartitionMultipleThreads(usize),
/// This mode will use a single thread per partition. This is more traditional for
/// DataFusion and should give better performance for complex queries that have a
/// lot of downstream processing. However, you will want to make sure to create the
/// node with enough partitions or else you will not get any parallelism.
///
/// The number of partitions is specified by the parameter.
MultiplePartitions(usize),
}
/// The stream of filtered rows that satisfies the FilteredReadExec node
///
/// This represents a scan of a Lance dataset. Upon creation of the stream we will
/// load the fragments, execute any scalar index query, and then plan out which portions
/// of the fragments we need to read.
///
/// For each fragment, we may read the entire fragment or we may read a portion of it. We
/// can use both the scan range and the index result to limit the amount of a fragment that
/// we read.
struct FilteredReadStream {
/// The schema of the output of the scan
output_schema: SchemaRef,
/// The stream of filtered rows, expressed as a stream of tasks (batch futures)
///
/// This stream can be shared by multiple partitions
task_stream: Arc<AsyncMutex<BoxStream<'static, Result<ReadBatchFut>>>>,
/// The scan scheduler for the scan
scan_scheduler: Arc<ScanScheduler>,
/// The global metrics for the scan
metrics: Arc<FilteredReadGlobalMetrics>,
/// The number of partitions currently running
///
/// We need to know when the final partition completes so that we can
/// gather the final I/O stats
active_partitions_counter: Arc<AtomicUsize>,
/// The threading mode for the scan
threading_mode: FilteredReadThreadingMode,
/// Range to apply to the result stream if not already pushed down in planning phase
scan_range_after_filter: Option<Range<u64>>,
}
impl std::fmt::Debug for FilteredReadStream {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FilteredReadStream").finish()
}
}
impl FilteredReadStream {
/// Create a new FilteredReadStream from a pre-computed internal plan
#[instrument(name = "init_filtered_read_stream", skip_all)]
async fn try_new(
dataset: Arc<Dataset>,
options: FilteredReadOptions,
metrics: &ExecutionPlanMetricsSet,
plan: FilteredReadInternalPlan,
) -> DataFusionResult<Self> {
let global_metrics = Arc::new(FilteredReadGlobalMetrics::new(metrics));
let threading_mode = options.threading_mode;
let io_parallelism = dataset.object_store.io_parallelism();
let fragment_readahead = options
.fragment_readahead
.unwrap_or_else(|| (*DEFAULT_FRAGMENT_READAHEAD).unwrap_or(io_parallelism * 2))
.max(1);
let fragments = options
.fragments
.clone()
.unwrap_or_else(|| dataset.fragments().clone());
log::debug!(
"Filtered read on {} fragments with frag_readahead={} and io_parallelism={}",
fragments.len(),
fragment_readahead,
io_parallelism
);
// Ideally we don't need to collect here but if we don't we get "implementation of FnOnce is
// not general enough" false positives from rustc
let frag_futs = fragments
.iter()
.map(|frag| {
Result::Ok(Self::load_fragment(
dataset.clone(),
frag.clone(),
options.with_deleted_rows,
))
})
.collect::<Vec<_>>();
let loaded_fragments = futures::stream::iter(frag_futs)
// Cannot use unordered because we need to populate logical_offset based on user-provided order
.try_buffered(io_parallelism)
.try_collect::<Vec<_>>()
.await?;
let output_schema = Arc::new(options.projection.to_arrow_schema());
let obj_store = dataset.object_store.clone();
let scheduler_config = if let Some(io_buffer_size_bytes) = options.io_buffer_size_bytes {
SchedulerConfig::new(io_buffer_size_bytes)
} else {
SchedulerConfig::max_bandwidth(obj_store.as_ref())
};
let scan_scheduler = ScanScheduler::new(obj_store, scheduler_config);
// Get scan_range_after_filter from the plan
let scan_range_after_filter = plan.scan_range_after_filter.clone();
// Convert plan to scoped fragments for I/O
let scoped_fragments = Self::plan_to_scoped_fragments(
&plan,
&loaded_fragments,
&dataset,
&options,
scan_scheduler.clone(),
);
let global_metrics_clone = global_metrics.clone();
let fragment_streams = futures::stream::iter(scoped_fragments)
.map({
let scan_range_after_filter = scan_range_after_filter.clone();
move |scoped_fragment| {
let metrics = global_metrics_clone.clone();
let limit = scan_range_after_filter.as_ref().map(|r| r.end);
SpawnedTask::spawn(
Self::read_fragment(scoped_fragment, metrics, limit).in_current_span(),
)
.map(|thread_result| thread_result.unwrap())
}
})
.buffered(fragment_readahead);
let task_stream = fragment_streams.try_flatten().boxed();
Ok(Self {
output_schema,
task_stream: Arc::new(AsyncMutex::new(task_stream)),
scan_scheduler,
metrics: global_metrics,
active_partitions_counter: Arc::new(AtomicUsize::new(0)),
threading_mode,
scan_range_after_filter,
})
}
async fn load_fragment(
dataset: Arc<Dataset>,
frag: Fragment,
include_deleted_rows: bool,
) -> Result<LoadedFragment> {
let file_fragment = FileFragment::new(dataset.clone(), frag.clone());
let deletion_vector = if include_deleted_rows {
None
} else {
file_fragment.get_deletion_vector().await?
};
let num_physical_rows = file_fragment.physical_rows().await? as u64;
let (row_id_sequence, num_logical_rows) = if dataset.manifest.uses_stable_row_ids() {
let row_id_sequence = load_row_id_sequence(dataset.as_ref(), &frag).await?;
let num_logical_rows = row_id_sequence.len();
(row_id_sequence, num_logical_rows)
} else {
let row_ids_start = frag.id << 32;
let row_ids_end = row_ids_start + num_physical_rows;
let num_logical_rows = file_fragment.count_rows(None).await? as u64;
let addrs_as_ids = Arc::new(RowIdSequence::from(row_ids_start..row_ids_end));
(addrs_as_ids, num_logical_rows)
};
Ok(LoadedFragment {
row_id_sequence,
fragment: Arc::new(file_fragment),
num_physical_rows,
num_logical_rows,
deletion_vector,
})
}
// This method is a bit complicated
//
// We start with a list of fragments, potentially a scalar index result, and a scan range.
//
// We need to figure out which ranges to read from each fragment.
//
// If the scan range is ignoring the filters we can push it down here.
// If the scan range is not ignoring the filters we can only push it down if:
// 1. The index result is an exact match (we know exactly which rows will be in the result)
// 2. The index result is AtLeast with guaranteed rows >= limit (we have enough guaranteed matches)
// Returns: FilteredReadInternalPlan
#[instrument(name = "plan_scan", skip_all)]
fn plan_scan(
fragments: &[LoadedFragment],
evaluated_index: &Option<Arc<EvaluatedIndex>>,
options: &FilteredReadOptions,
) -> FilteredReadInternalPlan {
// For pushing down scan_range_after_filter
let mut scan_planned_with_limit_pushed_down = false;
let mut to_skip = options
.scan_range_after_filter
.as_ref()
.map(|r| r.start)
.unwrap_or(0);
let mut to_take = options
.scan_range_after_filter
.as_ref()
.map(|r| r.end - r.start)
.unwrap_or(u64::MAX);
// Full fragment ranges to read before applying scan_range_after_filter
let mut fragments_to_read: BTreeMap<u32, Vec<Range<u64>>> = BTreeMap::new();
// Fragment ranges to read after applying scan_range_after_filter
// Adds an extra map because if scan_range_after_filter cannot be fulfilled we need to
// fall back to read the full fragment in fragments_to_read
// Used only when index guarantees enough rows to satisfy scan_range_after_filter
let mut scan_push_down_fragments_to_read: BTreeMap<u32, Vec<Range<u64>>> = BTreeMap::new();
// The current offset, includes filtered rows, but not deleted rows
let mut range_offset = 0;
for LoadedFragment {
row_id_sequence,
fragment,
num_logical_rows,
num_physical_rows,
deletion_vector,
} in fragments.iter()
{
if let Some(range_before_filter) = &options.scan_range_before_filter
&& range_offset >= range_before_filter.end
{
break;
}
let mut to_read: Vec<Range<u64>> =
Self::full_frag_range(*num_physical_rows, deletion_vector);
if let Some(range_before_filter) = &options.scan_range_before_filter {
let range_start = range_offset;
let range_end = if options.with_deleted_rows {
range_offset += num_physical_rows;
range_start + num_physical_rows
} else {
range_offset += num_logical_rows;
range_start + num_logical_rows
};
to_read = Self::trim_ranges(to_read, range_start..range_end, range_before_filter);
if to_read.is_empty() {
continue;
}
}
// Apply index and apply scan range after filter if applicable
Self::apply_index_to_fragment(
evaluated_index,
fragment,
row_id_sequence,
to_read,
&mut to_skip,
&mut to_take,
&mut fragments_to_read,
&mut scan_push_down_fragments_to_read,
);
if to_take == 0 {
scan_planned_with_limit_pushed_down = true;
fragments_to_read = scan_push_down_fragments_to_read;
break;
}
}
// Build filters for each fragment
let mut filters = HashMap::new();
for fragment in fragments.iter() {
let fragment_id = fragment.fragment.id() as u32;
if let Some(to_read) = fragments_to_read.get(&fragment_id) {
if !to_read.is_empty() {
// Resolve filter for this fragment
let filter = if let Some(evaluated_index) = evaluated_index {
if evaluated_index.applicable_fragments.contains(fragment_id) {
match &evaluated_index.index_result {
IndexExprResult::Exact(_) => options.refine_filter.clone(),
IndexExprResult::AtLeast(_)
if scan_planned_with_limit_pushed_down =>
{
options.refine_filter.clone()
}
_ => options.full_filter.clone(),
}
} else {
options.full_filter.clone()
}
} else {
options.full_filter.clone()
};
if let Some(f) = filter {
filters.insert(fragment_id, Arc::new(f));
}
log::trace!(
"Planning {} ranges ({} rows) from fragment {} with filter: {:?}",
to_read.len(),
to_read.iter().map(|r| r.end - r.start).sum::<u64>(),
fragment_id,
filters.get(&fragment_id)
);
} else {
log::trace!(
"Skipping fragment {} because it was outside the scan range",
fragment_id
);
}
}
}
// If scan_range_after_filter was pushed down, don't include it in the plan
let scan_range_after_filter = if scan_planned_with_limit_pushed_down {
None
} else {
options.scan_range_after_filter.clone()
};
FilteredReadInternalPlan {
rows: fragments_to_read,
filters,
scan_range_after_filter,
}
}
fn plan_to_scoped_fragments(
plan: &FilteredReadInternalPlan,
fragments: &[LoadedFragment],
dataset: &Dataset,
options: &FilteredReadOptions,
scan_scheduler: Arc<ScanScheduler>,
) -> Vec<ScopedFragmentRead> {
let default_batch_size = options.batch_size.unwrap_or_else(|| {
get_default_batch_size().unwrap_or_else(|| {
std::cmp::max(dataset.object_store().block_size() / 4, BATCH_SIZE_FALLBACK)
}) as u32
});
let projection = Arc::new(options.projection.clone());
let mut scoped_fragments = Vec::new();
for (priority, fragment) in fragments.iter().enumerate() {
let fragment_id = fragment.fragment.id() as u32;
// Check if this fragment is in the plan
if let Some(ranges) = plan.rows.get(&fragment_id) {
if ranges.is_empty() {
continue;
}
// Get filter for this fragment (convert Arc<Expr> back to Expr)
let filter = plan.filters.get(&fragment_id).map(|f| (**f).clone());
scoped_fragments.push(ScopedFragmentRead {
fragment: fragment.fragment.clone(),
ranges: ranges.clone(),
projection: projection.clone(),
with_deleted_rows: options.with_deleted_rows,
batch_size: default_batch_size,
filter,
priority: priority as u32,
scan_scheduler: scan_scheduler.clone(),
});
}
}
scoped_fragments
}
/// Apply index to a fragment and apply skip/take to matched ranges if possible
#[allow(clippy::too_many_arguments)]
fn apply_index_to_fragment(
evaluated_index: &Option<Arc<EvaluatedIndex>>,
fragment: &FileFragment,
row_id_sequence: &Arc<RowIdSequence>,
to_read: Vec<Range<u64>>,
to_skip: &mut u64,
to_take: &mut u64,
fragments_to_read: &mut BTreeMap<u32, Vec<Range<u64>>>,
scan_push_down_fragments_to_read: &mut BTreeMap<u32, Vec<Range<u64>>>,
) {
let fragment_id = fragment.id() as u32;
if let Some(evaluated_index) = evaluated_index {
if evaluated_index.applicable_fragments.contains(fragment_id) {
let _span = tracing::span!(tracing::Level::DEBUG, "apply_index_result").entered();
match &evaluated_index.index_result {
IndexExprResult::Exact(row_addr_mask) => {
let valid_ranges = row_id_sequence.mask_to_offset_ranges(row_addr_mask);
let mut matched_ranges = Self::intersect_ranges(&to_read, &valid_ranges);
fragments_to_read.insert(fragment_id, matched_ranges.clone());
Self::apply_skip_take_to_ranges(&mut matched_ranges, to_skip, to_take);
scan_push_down_fragments_to_read.insert(fragment_id, matched_ranges);
}
IndexExprResult::AtMost(row_addr_mask) => {
// Cannot push down skip/take for AtMost
let valid_ranges = row_id_sequence.mask_to_offset_ranges(row_addr_mask);
let matched_ranges = Self::intersect_ranges(&to_read, &valid_ranges);
fragments_to_read.insert(fragment_id, matched_ranges);
}
IndexExprResult::AtLeast(row_addr_mask) => {
let valid_ranges = row_id_sequence.mask_to_offset_ranges(row_addr_mask);
let mut guaranteed_ranges = Self::intersect_ranges(&to_read, &valid_ranges);
fragments_to_read.insert(fragment_id, guaranteed_ranges.clone());
Self::apply_skip_take_to_ranges(&mut guaranteed_ranges, to_skip, to_take);
scan_push_down_fragments_to_read.insert(fragment_id, guaranteed_ranges);
}
}
} else {
// Fragment not indexed - add full fragment to unindexed_ranges
fragments_to_read.insert(fragment_id, to_read);
}
} else {
// No index at all - add full fragment to unindexed_ranges
fragments_to_read.insert(fragment_id, to_read);
}
}
/// Trim physical ranges to skip `to_skip` rows and take at most `to_take` rows
fn trim_ranges_by_offset(physical_ranges: &mut Vec<Range<u64>>, to_skip: u64, to_take: u64) {
let mut skip_remaining = to_skip;
let mut take_remaining = to_take;
let mut write_idx = 0;
for read_idx in 0..physical_ranges.len() {
if take_remaining == 0 {
break;
}
let range = physical_ranges[read_idx].clone();
let range_size = range.end - range.start;
if range_size <= skip_remaining {
skip_remaining -= range_size;
continue;
}
if skip_remaining == 0 && take_remaining >= range_size {
physical_ranges[write_idx] = range;
write_idx += 1;
take_remaining -= range_size;
continue;
}
let skip_in_range = skip_remaining;
let available_in_range = range_size.saturating_sub(skip_in_range);
let take_from_range = available_in_range.min(take_remaining);
let new_start = range.start + skip_in_range;
let new_end = new_start + take_from_range;
physical_ranges[write_idx] = new_start..new_end;
write_idx += 1;
skip_remaining = 0;
take_remaining -= take_from_range;
}
physical_ranges.truncate(write_idx);
}
/// Intersect two sets of sorted ranges
fn intersect_ranges(ranges1: &[Range<u64>], ranges2: &[Range<u64>]) -> Vec<Range<u64>> {
let mut result = Vec::new();
let mut i = 0;
let mut j = 0;
while i < ranges1.len() && j < ranges2.len() {
let r1 = &ranges1[i];
let r2 = &ranges2[j];
// Check for intersection
let start = r1.start.max(r2.start);
let end = r1.end.min(r2.end);
if start < end {
result.push(start..end);
}
// Advance the range that ends first
if r1.end <= r2.end {
i += 1;
} else {
j += 1;
}
}
result
}
/// Apply skip and take to ranges and update the counters
fn apply_skip_take_to_ranges(
to_read: &mut Vec<Range<u64>>,
to_skip: &mut u64,
to_take: &mut u64,
) {
if *to_take == 0 {
to_read.clear();
*to_skip = 0;
return;
}
let original_rows: u64 = to_read.iter().map(|r| r.end - r.start).sum();
if *to_skip >= original_rows {
to_read.clear();
*to_skip -= original_rows;
return;
}
Self::trim_ranges_by_offset(to_read, *to_skip, *to_take);
let rows_taken: u64 = to_read.iter().map(|r| r.end - r.start).sum();
*to_skip = 0;
*to_take = to_take.saturating_sub(rows_taken);
}
#[instrument(level = "debug", skip_all)]
fn full_frag_range(
num_physical_rows: u64,
deletion_vector: &Option<Arc<DeletionVector>>,
) -> Vec<Range<u64>> {
if let Some(deletion_vector) = deletion_vector {
DvToValidRanges::new(
deletion_vector.to_sorted_iter().map(|pos| pos as u64),
num_physical_rows,
)
.collect()
} else {
vec![0..num_physical_rows]
}
}
// Given a logical position and bounds, calculate the number of rows to skip and take
fn calculate_fetch(
position: Range<u64>, // position of the fragment in dataset/fragment coordinates
bounds: &Range<u64>, // bounds of the scan in dataset/fragment coordinates
) -> (u64, u64) {
// Position: | --- |
// Bounds : | --- |
// Result : to_skip = 0, to_take = 0
//
// Position: | --- |
// Bounds : | --- |
// Result : to_skip = 0, to_take = 0
//
// Position: | --- |
// Bounds : | --- |
// Result : to_skip > 0, to_take = (position.end - bounds.start)
//
// Position: | --- |
// Bounds : | -------- |
// Result : to_skip = 0, to_take = (position.end - position.start)
//
// Position: | --- |
// Bounds : | --- |
// Result : to_skip = 0, to_take = (bounds.end - position.start)
let to_skip = bounds.start.saturating_sub(position.start);
let to_take = bounds
.end
.min(position.end)
.saturating_sub(position.start.max(bounds.start));
// Note: to_skip may be > 0 even if to_take == 0
(to_skip, to_take)
}
#[instrument(level = "debug", skip_all)]
fn trim_ranges(
physical_ranges: Vec<Range<u64>>,
logical_position: Range<u64>,
bounds: &Range<u64>,
) -> Vec<Range<u64>> {
let num_logical_rows = logical_position.end - logical_position.start;
let (mut to_skip, mut to_take) = Self::calculate_fetch(logical_position, bounds);
if to_skip == 0 && to_take == num_logical_rows {
return physical_ranges;
}
let mut trimmed = Vec::with_capacity(physical_ranges.len());
for range in physical_ranges {
let range_len = range.end - range.start;
if to_skip >= range_len {
to_skip -= range_len;
continue;
}
let avail_here = range_len - to_skip;
let to_take_here = avail_here.min(to_take);
to_take -= to_take_here;
if to_take_here > 0 {
trimmed.push(range.start + to_skip..range.start + to_skip + to_take_here);
}
to_skip = 0;
if to_take == 0 {
break;
}
}
trimmed
}
// There is one underlying task stream, and it can be shared by as many partitions as we
// want.
//
// The behavior of this method depends on the threading mode. If the threading mode is
// `OneThreadedPartition` then this method should only be called once. We will create a
// stream with readahead using buffered.
//
// If the threading mode is `MultiplePartitions` then this method should be called once per
// partition. Each stream will have a copy of the same underlying task stream. Only one stream
// can poll the underlying task stream at a time (there is a lock on the task stream). This is
// generally fine because grabbing a task is cheap (unless we are waiting on I/O).
//
// If the threading mode is `MultiplePartitions` then we may operate on the data out-of-order.
fn get_stream(
&self,
metrics: &ExecutionPlanMetricsSet,
partition: usize,
) -> SendableRecordBatchStream {
self.active_partitions_counter
.fetch_add(1, Ordering::Relaxed);
// Each partition needs these to record incremental metrics.
let global_metrics = self.metrics.clone();
let scan_scheduler = self.scan_scheduler.clone();
let partition_metrics = Arc::new(FilteredReadPartitionMetrics::new(metrics, partition));
match self.threading_mode {
FilteredReadThreadingMode::OnePartitionMultipleThreads(num_threads) => {
assert_eq!(partition, 0);
let output_schema = self.output_schema.clone();
let task_stream = self.task_stream.clone();
let partition_metrics_clone = partition_metrics.clone();
let futures_stream = futures::stream::try_unfold(task_stream, {
move |task_stream| {
let partition_metrics = partition_metrics_clone.clone();
async move {
// There is no compute we can meaningfully measure here. The actual work is
// done by spawned background threads.
let _timer =
partition_metrics.baseline_metrics.elapsed_compute().timer();
let _task_wait_timer = partition_metrics.task_wait_time.timer();
let maybe_task = task_stream.lock().await.next().await.transpose()?;
Result::Ok(maybe_task.map(|task| (task, task_stream)))
}
}
});
let partition_metrics_clone = partition_metrics.clone();
let base_batch_stream =
futures_stream
.try_buffered(num_threads)
.try_filter_map(move |batch| {
std::future::ready(Ok(if batch.num_rows() == 0 {
None
} else {
Some(batch)
}))
});
let batch_stream = if let Some(ref range) = self.scan_range_after_filter {
Self::apply_hard_range(base_batch_stream, range.clone()).boxed()
} else {
// Need to box here otherwise the if/else returns incompatible types
base_batch_stream.boxed()
};
let batch_stream = batch_stream
.inspect_ok(move |batch| {
partition_metrics_clone
.baseline_metrics
.record_output(batch.num_rows());
global_metrics.io_metrics.record(&scan_scheduler);
})
.finally(move || {
partition_metrics.baseline_metrics.done();
})
.map_err(|e: lance_core::Error| DataFusionError::External(e.into()))
.boxed();
Box::pin(RecordBatchStreamAdapter::new(output_schema, batch_stream))
}
FilteredReadThreadingMode::MultiplePartitions(num_partitions) => {
assert!(partition < num_partitions);
let output_schema = self.output_schema.clone();
let task_stream = self.task_stream.clone();
let global_metrics_clone = global_metrics.clone();
let scan_scheduler_clone = scan_scheduler.clone();
let batch_stream = futures::stream::try_unfold(task_stream, {
move |task_stream| {
let partition_metrics = partition_metrics.clone();