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//! can be found in the `vortex-layout` crate.
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 planning;
26pub mod row_mask;
27pub mod selection;
28pub mod strict_sorted_buffer;
29
30use std::any::Any;
31use std::ops::Range;
32use std::sync::Arc;
33
34use async_trait::async_trait;
35use futures::stream::BoxStream;
36use selection::Selection;
37use vortex_array::aggregate_fn::AggregateFnRef;
38use vortex_array::dtype::DType;
39use vortex_array::dtype::FieldPath;
40use vortex_array::expr::Expression;
41use vortex_array::expr::root;
42use vortex_array::expr::stats::Precision;
43use vortex_array::scalar::Scalar;
44use vortex_array::stats::StatsSet;
45use vortex_array::stream::SendableArrayStream;
46use vortex_error::VortexResult;
47use vortex_error::vortex_bail;
48use vortex_session::VortexSession;
49
50/// A sendable stream of partitions.
51pub type PartitionStream = BoxStream<'static, VortexResult<PartitionRef>>;
52
53/// Opens a Vortex [`DataSource`] from a URI.
54///
55/// Configuration can be passed via the URI query parameters, similar to JDBC / ADBC.
56/// Providers can be registered with the [`VortexSession`] to support additional URI schemes.
57#[async_trait]
58pub trait DataSourceOpener: 'static {
59 /// Attempt to open a new data source from a URI.
60 async fn open(&self, uri: String, session: &VortexSession) -> VortexResult<DataSourceRef>;
61}
62
63/// Supports deserialization of a Vortex [`DataSource`] on a remote worker.
64#[async_trait]
65pub trait DataSourceRemote: 'static {
66 /// Attempt to deserialize the source.
67 fn deserialize_data_source(
68 &self,
69 data: &[u8],
70 session: &VortexSession,
71 ) -> VortexResult<DataSourceRef>;
72}
73
74/// A reference-counted data source.
75pub type DataSourceRef = Arc<dyn DataSource>;
76
77/// A data source represents a streamable dataset that can be scanned with projection and filter
78/// expressions. Each scan produces partitions that can be executed in parallel to read data. Each
79/// partition can be serialized for remote execution.
80///
81/// The DataSource may be used multiple times to create multiple scans, whereas each scan and each
82/// partition of a scan can only be consumed once.
83///
84/// Partitions have indices. Partition index is stable throughout DataSource's
85/// lifetime. For every scan requested on the DataSource, the index will stay
86/// the same.
87/// However, this means you should create another instance of a DataSource if
88/// your environment changes e.g. you have a glob and another file is added to
89/// the filesystem this glob references.
90/// See MultiFileDataSource in vortex-file/src/multi/mod.rs
91#[async_trait]
92pub trait DataSource: 'static + Send + Sync {
93 /// Returns the dtype of the source.
94 fn dtype(&self) -> &DType;
95
96 /// Returns an estimate of the row count of the un-filtered source.
97 fn row_count(&self) -> Precision<u64> {
98 Precision::Absent
99 }
100
101 /// Returns an estimate of the byte size of the un-filtered source.
102 fn byte_size(&self) -> Precision<u64> {
103 Precision::Absent
104 }
105
106 /// Serialize the [`DataSource`] to pass to a remote worker.
107 fn serialize(&self) -> VortexResult<Option<Vec<u8>>> {
108 Ok(None)
109 }
110
111 /// Deserialize a partition that was previously serialized from a compatible data source.
112 fn deserialize_partition(
113 &self,
114 data: &[u8],
115 session: &VortexSession,
116 ) -> VortexResult<PartitionRef> {
117 let _ = (data, session);
118 vortex_bail!("DataSource does not support deserialization")
119 }
120
121 /// Returns a scan over the source.
122 async fn scan(&self, scan_request: ScanRequest) -> VortexResult<DataSourceScanRef>;
123
124 /// Returns the statistics for a given field.
125 async fn field_statistics(&self, field_path: &FieldPath) -> VortexResult<StatsSet>;
126
127 /// Returns a stored aggregate partial over the unfiltered source field.
128 ///
129 /// The scalar has the aggregate's `partial_dtype`; callers merge partials and finalize
130 /// through the requested aggregate. Identity includes bound options. Missing partials,
131 /// incomplete coverage, and incompatible aggregates return [`Precision::Absent`], as
132 /// does the default implementation. Finalized legacy statistics are not partials.
133 ///
134 /// Lookup must not scan payloads. Precision describes the partial state; consumers must
135 /// respect the aggregate's approximation contract. Later scan filters and limits do not
136 /// change this source-level partial. A stored null partial is distinct from absence.
137 async fn field_statistic(
138 &self,
139 _field_path: &FieldPath,
140 _aggregate_fn: &AggregateFnRef,
141 ) -> VortexResult<Precision<Scalar>> {
142 Ok(Precision::Absent)
143 }
144}
145
146/// A request to scan a data source.
147#[derive(Debug, Clone)]
148pub struct ScanRequest {
149 /// Projection expression. Defaults to `root()` which returns all columns.
150 pub projection: Expression,
151 /// Filter expression, `None` implies no filter.
152 pub filter: Option<Expression>,
153 /// The per-partition row range to read. Row range will be applied
154 /// over every partition you scan.
155 pub row_range: Option<Range<u64>>,
156 /// The per-partition row selection to read. Row selection will be applied
157 /// over every partition you scan.
158 pub selection: Selection,
159 /// Partition selection to scan, which allows readers to skip unwanted partitions.
160 pub partition_selection: Selection,
161 /// Partition range to scan, which allows readers to skip unwanted partitions.
162 pub partition_range: Option<Range<u64>>,
163 /// Whether the scan should preserve row order. If false, the scan may produce rows in any
164 /// order, for example to enable parallel execution across partitions.
165 pub ordered: bool,
166 /// Optional limit on the number of rows returned, applied after filtering and row selection.
167 ///
168 /// For an unordered scan the limit is global: partitions share one budget, so together they
169 /// return no more than `limit` rows. An ordered scan cannot share a budget whose reservation
170 /// order is completion order, so each partition applies the limit locally and the caller must
171 /// trim the concatenated result.
172 pub limit: Option<u64>,
173}
174
175impl Default for ScanRequest {
176 fn default() -> Self {
177 Self {
178 projection: root(),
179 filter: None,
180 row_range: None,
181 selection: Selection::default(),
182 partition_selection: Selection::default(),
183 ordered: false,
184 limit: None,
185 partition_range: None,
186 }
187 }
188}
189
190/// A boxed data source scan.
191pub type DataSourceScanRef = Box<dyn DataSourceScan>;
192
193/// A data source scan produces partitions that can be executed to read data from the source.
194pub trait DataSourceScan: 'static + Send {
195 /// The returned dtype of the scan.
196 fn dtype(&self) -> &DType;
197
198 /// Returns an estimate of the total number of partitions the scan will produce.
199 fn partition_count(&self) -> Precision<usize>;
200
201 /// Returns a stream of partitions to be processed.
202 fn partitions(self: Box<Self>) -> PartitionStream;
203}
204
205/// A reference-counted partition.
206pub type PartitionRef = Box<dyn Partition>;
207
208/// A partition represents a unit of work that can be executed to produce a stream of arrays.
209pub trait Partition: 'static + Send {
210 /// Downcast the partition to a concrete type.
211 fn as_any(&self) -> &dyn Any;
212
213 /// Some unique identifier for partition.
214 /// If you have an instance of a DataSource, the indices of emitted
215 /// partitions will stay stable for every scan in this DataSource.
216 fn index(&self) -> usize;
217
218 /// Returns an estimate of the row count for this partition.
219 fn row_count(&self) -> Precision<u64>;
220
221 /// Returns an estimate of the byte size for this partition.
222 fn byte_size(&self) -> Precision<u64>;
223
224 /// Serialize this partition for a remote worker.
225 fn serialize(&self) -> VortexResult<Option<Vec<u8>>> {
226 Ok(None)
227 }
228
229 /// Executes the partition, returning an array stream.
230 ///
231 /// This method must be fast. The returned stream should be lazy — all non-trivial work
232 /// (I/O, decoding, filtering) must be deferred to when the stream is polled. Expensive
233 /// operations should be spawned onto the runtime to enable parallel execution across
234 /// threads.
235 fn execute(self: Box<Self>) -> VortexResult<SendableArrayStream>;
236}