Skip to main content

vortex_layout/scan/
layout.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::any::Any;
5use std::ops::Range;
6use std::pin::Pin;
7use std::sync::Arc;
8use std::task::Context;
9use std::task::Poll;
10
11use async_trait::async_trait;
12use futures::FutureExt;
13use futures::Stream;
14use futures::stream;
15use futures::stream::StreamExt;
16use vortex_array::IntoArray;
17use vortex_array::arrays::ConstantArray;
18use vortex_array::dtype::DType;
19use vortex_array::dtype::FieldPath;
20use vortex_array::dtype::Nullability;
21use vortex_array::expr::BoundExpression;
22use vortex_array::expr::stats::Precision;
23use vortex_array::scalar::Scalar;
24use vortex_array::stats::StatsSet;
25use vortex_array::stream::ArrayStreamAdapter;
26use vortex_array::stream::ArrayStreamExt;
27use vortex_array::stream::SendableArrayStream;
28use vortex_error::VortexResult;
29use vortex_error::vortex_bail;
30use vortex_mask::Mask;
31use vortex_metrics::MetricsRegistry;
32use vortex_scan::DataSource;
33use vortex_scan::DataSourceScan;
34use vortex_scan::DataSourceScanRef;
35use vortex_scan::Partition;
36use vortex_scan::PartitionRef;
37use vortex_scan::PartitionStream;
38use vortex_scan::ScanRequest;
39use vortex_scan::selection::Selection;
40use vortex_session::VortexSession;
41
42use crate::LayoutReaderRef;
43use crate::scan::scan_builder::ScanBuilder;
44
45/// An implementation of a [`DataSource`] that reads data from a [`LayoutReaderRef`].
46pub struct LayoutReaderDataSource {
47    reader: LayoutReaderRef,
48    session: VortexSession,
49    split_max_row_count: u64,
50    metrics_registry: Option<Arc<dyn MetricsRegistry>>,
51}
52
53impl LayoutReaderDataSource {
54    /// Creates a new [`LayoutReaderDataSource`].
55    ///
56    /// By default, the entire scan is returned as a single split. This best preserves V1
57    /// `ScanBuilder` behavior where one scan covers the full row range, allowing the internal
58    /// I/O pipeline and `SplitBy::Layout` chunking to operate without per-split overhead from
59    /// redundant expression resolution and layout tree traversal.
60    pub fn new(reader: LayoutReaderRef, session: VortexSession) -> Self {
61        Self {
62            reader,
63            session,
64            split_max_row_count: u64::MAX,
65            metrics_registry: None,
66        }
67    }
68
69    /// Sets the maximum number of rows per Scan API split.
70    ///
71    /// Each split drives a [`ScanBuilder`] over its row range, which internally handles
72    /// physical layout alignment and I/O pipelining. This controls the engine-level
73    /// parallelism granularity, not the I/O granularity.
74    pub fn with_split_max_row_count(mut self, row_count: u64) -> Self {
75        self.split_max_row_count = row_count;
76        self
77    }
78
79    /// Sets the metrics registry for tracking scan performance.
80    pub fn with_metrics_registry(mut self, metrics: Arc<dyn MetricsRegistry>) -> Self {
81        self.metrics_registry = Some(metrics);
82        self
83    }
84
85    /// Optionally sets the metrics registry for tracking scan performance.
86    pub fn with_some_metrics_registry(mut self, metrics: Option<Arc<dyn MetricsRegistry>>) -> Self {
87        self.metrics_registry = metrics;
88        self
89    }
90}
91
92#[async_trait]
93impl DataSource for LayoutReaderDataSource {
94    fn dtype(&self) -> &DType {
95        self.reader.dtype()
96    }
97
98    fn row_count(&self) -> Precision<u64> {
99        Precision::exact(self.reader.row_count())
100    }
101
102    fn byte_size(&self) -> Precision<u64> {
103        Precision::Absent
104    }
105
106    fn deserialize_partition(
107        &self,
108        _data: &[u8],
109        _session: &VortexSession,
110    ) -> VortexResult<PartitionRef> {
111        vortex_bail!("LayoutReader splits are not yet serializable");
112    }
113
114    async fn scan(&self, scan_request: ScanRequest) -> VortexResult<DataSourceScanRef> {
115        let total_rows = self.reader.row_count();
116        let row_range = scan_request.row_range.unwrap_or(0..total_rows);
117
118        let projection = scan_request
119            .projection
120            .bind(self.reader.dtype())?
121            .optimize_recursive()?;
122        let filter = scan_request
123            .filter
124            .map(|expr| expr.bind(self.reader.dtype())?.optimize_recursive())
125            .transpose()?;
126        let dtype = projection.dtype().clone();
127
128        // If the dtype is an empty struct, and there is no filter, we can return a special
129        // length-only scan.
130        if let DType::Struct(fields, Nullability::NonNullable) = &dtype
131            && fields.nfields() == 0
132            && filter.is_none()
133        {
134            // FIXME(ngates): extract out maybe?
135            let row_count = row_range.end - row_range.start;
136            let row_count = scan_request.selection.row_count(row_count);
137
138            // Apply the limit.
139            let row_count = if let Some(limit) = scan_request.limit {
140                row_count.min(limit)
141            } else {
142                row_count
143            };
144
145            return Ok(Box::new(Empty { dtype, row_count }));
146        }
147
148        // Check file-level pruning: if the filter can be proven false for the entire row range
149        // using file-level statistics (e.g. via FileStatsLayoutReader), skip the scan entirely.
150        if let Some(filter) = &filter {
151            let mask = Mask::new_true(
152                usize::try_from(row_range.end - row_range.start).unwrap_or(usize::MAX),
153            );
154            let pruning_result = self
155                .reader
156                .pruning_evaluation(&row_range, filter, mask)?
157                .now_or_never();
158            if let Some(Ok(result_mask)) = pruning_result
159                && result_mask.all_false()
160            {
161                return Ok(Box::new(Empty {
162                    dtype,
163                    row_count: 0,
164                }));
165            }
166        }
167
168        Ok(Box::new(LayoutReaderScan {
169            reader: Arc::clone(&self.reader),
170            session: self.session.clone(),
171            dtype,
172            projection,
173            filter,
174            limit: scan_request.limit,
175            selection: scan_request.selection,
176            ordered: scan_request.ordered,
177            metrics_registry: self.metrics_registry.clone(),
178            next_row: row_range.start,
179            end_row: row_range.end,
180            split_size: self.split_max_row_count,
181        }))
182    }
183
184    async fn field_statistics(&self, _field_path: &FieldPath) -> VortexResult<StatsSet> {
185        Ok(StatsSet::default())
186    }
187}
188
189struct LayoutReaderScan {
190    reader: LayoutReaderRef,
191    session: VortexSession,
192    dtype: DType,
193    projection: BoundExpression,
194    filter: Option<BoundExpression>,
195    limit: Option<u64>,
196    ordered: bool,
197    selection: Selection,
198    metrics_registry: Option<Arc<dyn MetricsRegistry>>,
199    next_row: u64,
200    end_row: u64,
201    split_size: u64,
202}
203
204impl DataSourceScan for LayoutReaderScan {
205    fn dtype(&self) -> &DType {
206        &self.dtype
207    }
208
209    fn partition_count(&self) -> Precision<usize> {
210        let (lower, upper) = self.size_hint();
211        match upper {
212            Some(u) if u == lower => Precision::exact(lower),
213            Some(u) => Precision::inexact(u),
214            None => Precision::inexact(lower),
215        }
216    }
217
218    fn partitions(self: Box<Self>) -> PartitionStream {
219        (*self).boxed()
220    }
221}
222
223impl Stream for LayoutReaderScan {
224    type Item = VortexResult<PartitionRef>;
225
226    fn poll_next(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
227        let this = self.get_mut();
228
229        if this.next_row >= this.end_row {
230            return Poll::Ready(None);
231        }
232
233        if this.limit.is_some_and(|limit| limit == 0) {
234            return Poll::Ready(None);
235        }
236
237        let split_end = this
238            .next_row
239            .saturating_add(this.split_size)
240            .min(this.end_row);
241        let row_range = this.next_row..split_end;
242        let split_rows = split_end - this.next_row;
243
244        let split_limit = this.limit;
245        // Only decrement the remaining limit when there is no filter. With a filter,
246        // the actual output row count is unknown (could be anywhere from 0 to split_rows),
247        // so decrementing by split_rows would be too aggressive and could stop producing
248        // splits before the limit is reached. Instead, pass the full remaining limit to
249        // each split and let the engine enforce the exact limit at the stream level.
250        if this.filter.is_none()
251            && let Some(ref mut limit) = this.limit
252        {
253            *limit = limit.saturating_sub(split_rows);
254        }
255
256        let split = Box::new(LayoutReaderSplit {
257            reader: Arc::clone(&this.reader),
258            session: this.session.clone(),
259            projection: this.projection.clone(),
260            filter: this.filter.clone(),
261            limit: split_limit,
262            ordered: this.ordered,
263            row_range,
264            selection: this.selection.clone(),
265            metrics_registry: this.metrics_registry.clone(),
266        }) as PartitionRef;
267
268        this.next_row = split_end;
269
270        Poll::Ready(Some(Ok(split)))
271    }
272
273    fn size_hint(&self) -> (usize, Option<usize>) {
274        if self.next_row >= self.end_row {
275            return (0, Some(0));
276        }
277        let remaining_rows = self.end_row - self.next_row;
278        let splits = remaining_rows.div_ceil(self.split_size);
279        (0, Some(usize::try_from(splits).unwrap_or(usize::MAX)))
280    }
281}
282
283struct LayoutReaderSplit {
284    reader: LayoutReaderRef,
285    session: VortexSession,
286    projection: BoundExpression,
287    filter: Option<BoundExpression>,
288    limit: Option<u64>,
289    ordered: bool,
290    row_range: Range<u64>,
291    selection: Selection,
292    metrics_registry: Option<Arc<dyn MetricsRegistry>>,
293}
294
295impl Partition for LayoutReaderSplit {
296    fn as_any(&self) -> &dyn Any {
297        self
298    }
299
300    #[expect(clippy::cast_possible_truncation)]
301    fn index(&self) -> usize {
302        // Row range is unique per split
303        self.row_range.start as usize
304    }
305
306    fn row_count(&self) -> Precision<u64> {
307        let row_count = self.row_range.end - self.row_range.start;
308        let row_count = self.selection.row_count(row_count);
309        let row_count = self.limit.map_or(row_count, |limit| row_count.min(limit));
310
311        if self.filter.is_some() {
312            Precision::inexact(row_count)
313        } else {
314            Precision::exact(row_count)
315        }
316    }
317
318    fn byte_size(&self) -> Precision<u64> {
319        Precision::Absent
320    }
321
322    fn execute(self: Box<Self>) -> VortexResult<SendableArrayStream> {
323        let builder = ScanBuilder::new(self.session, self.reader)
324            .with_row_range(self.row_range)
325            .with_selection(self.selection)
326            .with_projection(self.projection)
327            .with_some_filter(self.filter)
328            .with_some_limit(self.limit)
329            .with_some_metrics_registry(self.metrics_registry)
330            .with_ordered(self.ordered);
331
332        let dtype = builder.dtype()?;
333        // Use into_stream() which creates a LazyScanStream that spawns individual I/O
334        // tasks onto the runtime, enabling parallel execution across executor threads.
335        let stream = builder.into_stream()?;
336
337        Ok(ArrayStreamExt::boxed(ArrayStreamAdapter::new(
338            dtype, stream,
339        )))
340    }
341}
342
343/// A scan that produces no data, only empty arrays with the correct row count.
344struct Empty {
345    dtype: DType,
346    row_count: u64,
347}
348
349impl DataSourceScan for Empty {
350    fn dtype(&self) -> &DType {
351        &self.dtype
352    }
353
354    fn partition_count(&self) -> Precision<usize> {
355        Precision::exact(1usize)
356    }
357
358    fn partitions(self: Box<Self>) -> PartitionStream {
359        stream::iter([Ok(self as _)]).boxed()
360    }
361}
362
363impl Partition for Empty {
364    fn as_any(&self) -> &dyn Any {
365        self
366    }
367
368    fn index(&self) -> usize {
369        0
370    }
371
372    fn row_count(&self) -> Precision<u64> {
373        Precision::exact(self.row_count)
374    }
375
376    fn byte_size(&self) -> Precision<u64> {
377        Precision::exact(0u64)
378    }
379
380    fn execute(mut self: Box<Self>) -> VortexResult<SendableArrayStream> {
381        let scalar = Scalar::default_value(&self.dtype);
382        let dtype = self.dtype.clone();
383
384        // Create an iterator of arrays with the correct row count, respecting u64::MAX limits.
385        let iter = std::iter::from_fn(move || {
386            if self.row_count == 0 {
387                return None;
388            }
389            let chunk_size = usize::try_from(self.row_count).unwrap_or(usize::MAX);
390            self.row_count -= chunk_size as u64;
391            Some(VortexResult::Ok(
392                ConstantArray::new(scalar.clone(), chunk_size).into_array(),
393            ))
394        });
395
396        Ok(ArrayStreamExt::boxed(ArrayStreamAdapter::new(
397            dtype,
398            stream::iter(iter),
399        )))
400    }
401}