vortex_scan/lib.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4#![deny(missing_docs)]
5
6//! The Vortex Scan API implements an abstract table scan interface that can be used to
7//! read data from various data sources.
8//!
9//! It supports arbitrary projection expressions, filter expressions, and limit pushdown as well
10//! as mechanisms for parallel and distributed execution via partitions.
11//!
12//! The API is currently under development and may change in future releases, however we hope to
13//! stabilize into stable C ABI for use within foreign language bindings.
14//!
15//! If you are looking to scan Vortex files or layouts, the Vortex implementation of the Scan API
16//! is lowered by `vortex-layout` into this crate's plans and executor.
17//!
18//! ## Open Issues
19//!
20//! * We probably want to make the DataSource serializable as well, so that we can share
21//! source-level state with workers, separately from partition serialization.
22//! * We should add a way for the client to negotiate capabilities with the data source, for
23//! example which encodings it knows about.
24
25pub mod analysis;
26pub mod arrays;
27pub mod execution;
28pub mod plan;
29pub mod planning;
30pub mod prepare;
31pub mod row_mask;
32pub mod selection;
33pub mod source;
34pub mod strict_sorted_buffer;
35
36use std::any::Any;
37use std::num::NonZeroUsize;
38use std::ops::Range;
39use std::sync::Arc;
40
41use async_trait::async_trait;
42use futures::StreamExt;
43use futures::TryStreamExt;
44use futures::stream::BoxStream;
45use selection::Selection;
46use vortex_array::aggregate_fn::AggregateFnRef;
47use vortex_array::dtype::DType;
48use vortex_array::dtype::FieldPath;
49use vortex_array::scalar::Scalar;
50use vortex_array::stats::Precision;
51use vortex_array::stats::StatsSet;
52use vortex_array::stream::ArrayStream;
53use vortex_array::stream::ArrayStreamAdapter;
54use vortex_array::stream::SendableArrayStream;
55use vortex_error::VortexResult;
56use vortex_error::vortex_bail;
57use vortex_expr::Expression;
58use vortex_expr::root;
59use vortex_session::VortexSession;
60
61/// A sendable stream of partitions.
62pub type PartitionStream = BoxStream<'static, VortexResult<PartitionRef>>;
63
64/// Opens a Vortex [`DataSource`] from a URI.
65///
66/// Configuration can be passed via the URI query parameters, similar to JDBC / ADBC.
67/// Providers can be registered with the [`VortexSession`] to support additional URI schemes.
68#[async_trait]
69pub trait DataSourceOpener: 'static {
70 /// Attempt to open a new data source from a URI.
71 async fn open(&self, uri: String, session: &VortexSession) -> VortexResult<DataSourceRef>;
72}
73
74/// Supports deserialization of a Vortex [`DataSource`] on a remote worker.
75#[async_trait]
76pub trait DataSourceRemote: 'static {
77 /// Attempt to deserialize the source.
78 fn deserialize_data_source(
79 &self,
80 data: &[u8],
81 session: &VortexSession,
82 ) -> VortexResult<DataSourceRef>;
83}
84
85/// A reference-counted data source.
86pub type DataSourceRef = Arc<dyn DataSource>;
87
88/// A data source represents a streamable dataset that can be scanned with projection and filter
89/// expressions. Each scan produces partitions that can be executed in parallel to read data. Each
90/// partition can be serialized for remote execution.
91///
92/// The DataSource may be used multiple times to create multiple scans, whereas each scan and each
93/// partition of a scan can only be consumed once.
94///
95/// Partitions have indices. Partition index is stable throughout DataSource's
96/// lifetime. For every scan requested on the DataSource, the index will stay
97/// the same.
98/// However, this means you should create another instance of a DataSource if
99/// your environment changes e.g. you have a glob and another file is added to
100/// the filesystem this glob references.
101/// See MultiFileDataSource in vortex-file/src/multi/mod.rs
102#[async_trait]
103pub trait DataSource: 'static + Send + Sync {
104 /// Returns the dtype of the source.
105 fn dtype(&self) -> &DType;
106
107 /// Returns an estimate of the row count of the un-filtered source.
108 fn row_count(&self) -> Precision<u64> {
109 Precision::Absent
110 }
111
112 /// Returns an estimate of the byte size of the un-filtered source.
113 fn byte_size(&self) -> Precision<u64> {
114 Precision::Absent
115 }
116
117 /// Serialize the [`DataSource`] to pass to a remote worker.
118 fn serialize(&self) -> VortexResult<Option<Vec<u8>>> {
119 Ok(None)
120 }
121
122 /// Deserialize a partition that was previously serialized from a compatible data source.
123 fn deserialize_partition(
124 &self,
125 data: &[u8],
126 session: &VortexSession,
127 ) -> VortexResult<PartitionRef> {
128 let _ = (data, session);
129 vortex_bail!("DataSource does not support deserialization")
130 }
131
132 /// Returns a scan over the source.
133 async fn scan(&self, scan_request: ScanRequest) -> VortexResult<DataSourceScanRef>;
134
135 /// Returns the statistics for a given field.
136 async fn field_statistics(&self, field_path: &FieldPath) -> VortexResult<StatsSet>;
137
138 /// Returns a stored aggregate partial over the unfiltered source field.
139 ///
140 /// The scalar has the aggregate's `partial_dtype`; callers merge partials and finalize
141 /// through the requested aggregate. Identity includes bound options. Missing partials,
142 /// incomplete coverage, and incompatible aggregates return [`Precision::Absent`], as
143 /// does the default implementation. Finalized legacy statistics are not partials.
144 ///
145 /// Lookup must not scan payloads. Precision describes the partial state; consumers must
146 /// respect the aggregate's approximation contract. Later scan filters and limits do not
147 /// change this source-level partial. A stored null partial is distinct from absence.
148 async fn field_statistic(
149 &self,
150 _field_path: &FieldPath,
151 _aggregate_fn: &AggregateFnRef,
152 ) -> VortexResult<Precision<Scalar>> {
153 Ok(Precision::Absent)
154 }
155}
156
157/// A request to scan a data source.
158#[derive(Debug, Clone)]
159pub struct ScanRequest {
160 /// Projection expression. Defaults to `root()` which returns all columns.
161 pub projection: Expression,
162 /// Filter expression, `None` implies no filter.
163 pub filter: Option<Expression>,
164 /// The per-partition row range to read. Row range will be applied
165 /// over every partition you scan. A range that starts after it ends selects no rows.
166 pub row_range: Option<Range<u64>>,
167 /// The per-partition row selection to read. Row selection will be applied
168 /// over every partition you scan.
169 pub selection: Selection,
170 /// Partition selection to scan, which allows readers to skip unwanted partitions.
171 pub partition_selection: Selection,
172 /// Partition range to scan, which allows readers to skip unwanted partitions.
173 pub partition_range: Option<Range<u64>>,
174 /// Whether the scan should preserve row order. If false, the scan may produce rows in any
175 /// order, for example to enable parallel execution across partitions.
176 pub ordered: bool,
177 /// Optional limit on the number of rows returned, applied after filtering and row selection.
178 ///
179 /// For an unordered scan the limit is global: partitions share one budget, so together they
180 /// return no more than `limit` rows. An ordered scan cannot share a budget whose reservation
181 /// order is completion order, so each partition applies the limit locally and the caller must
182 /// trim the concatenated result.
183 pub limit: Option<u64>,
184 /// The most splits of each partition to decode at once, in all.
185 ///
186 /// `None` keeps the reader's default, which scales with the machine's cores. Each split being
187 /// decoded holds the decoded chunks of every column it overlaps, so a scan that runs alongside
188 /// others, such as one task of several on a machine, can set this to bound its memory. It does
189 /// not bound I/O: segment reads for later splits may still be coalesced ahead of them.
190 pub split_concurrency: Option<NonZeroUsize>,
191}
192
193impl Default for ScanRequest {
194 fn default() -> Self {
195 Self {
196 projection: root(),
197 filter: None,
198 row_range: None,
199 selection: Selection::default(),
200 partition_selection: Selection::default(),
201 ordered: false,
202 limit: None,
203 partition_range: None,
204 split_concurrency: None,
205 }
206 }
207}
208
209/// A boxed data source scan.
210pub type DataSourceScanRef = Box<dyn DataSourceScan>;
211
212/// A data source scan produces partitions that can be executed to read data from the source.
213pub trait DataSourceScan: 'static + Send {
214 /// The returned dtype of the scan.
215 fn dtype(&self) -> &DType;
216
217 /// Returns an estimate of the total number of partitions the scan will produce.
218 fn partition_count(&self) -> Precision<usize>;
219
220 /// Returns a stream of partitions to be processed.
221 fn partitions(self: Box<Self>) -> PartitionStream;
222}
223
224impl dyn DataSourceScan {
225 /// Execute partitions lazily, yielding their arrays in the order the partitions are emitted.
226 pub fn into_array_stream(self: Box<Self>) -> impl ArrayStream + Send {
227 let dtype = self.dtype().clone();
228 let arrays = self
229 .partitions()
230 .map(|partition| partition?.execute())
231 .try_flatten();
232 ArrayStreamAdapter::new(dtype, arrays)
233 }
234}
235
236/// A reference-counted partition.
237pub type PartitionRef = Box<dyn Partition>;
238
239/// A partition represents a unit of work that can be executed to produce a stream of arrays.
240pub trait Partition: 'static + Send {
241 /// Downcast the partition to a concrete type.
242 fn as_any(&self) -> &dyn Any;
243
244 /// Some unique identifier for partition.
245 /// If you have an instance of a DataSource, the indices of emitted
246 /// partitions will stay stable for every scan in this DataSource.
247 fn index(&self) -> usize;
248
249 /// Returns an estimate of the row count for this partition.
250 fn row_count(&self) -> Precision<u64>;
251
252 /// Returns an estimate of the byte size for this partition.
253 fn byte_size(&self) -> Precision<u64>;
254
255 /// Serialize this partition for a remote worker.
256 fn serialize(&self) -> VortexResult<Option<Vec<u8>>> {
257 Ok(None)
258 }
259
260 /// Executes the partition, returning an array stream.
261 ///
262 /// This method must be fast. The returned stream should be lazy — all non-trivial work
263 /// (I/O, decoding, filtering) must be deferred to when the stream is polled. Expensive
264 /// operations should be spawned onto the runtime to enable parallel execution across
265 /// threads.
266 fn execute(self: Box<Self>) -> VortexResult<SendableArrayStream>;
267}
268
269/// Expressions referring to the global scan row index.
270pub mod row_idx {
271 pub use crate::plan::builtins::row_idx::expr::*;
272}
273
274#[cfg(test)]
275mod test;