• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

vortex-data / vortex / 16421522964

21 Jul 2025 03:40PM UTC coverage: 81.54% (+0.02%) from 81.523%
16421522964

push

github

web-flow
Improve work stealing loop (#3946)

Signed-off-by: Nicholas Gates <nick@nickgates.com>

18 of 18 new or added lines in 1 file covered. (100.0%)

110 existing lines in 5 files now uncovered.

42099 of 51630 relevant lines covered (81.54%)

170770.88 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

80.77
/vortex-datafusion/src/persistent/format.rs
1
// SPDX-License-Identifier: Apache-2.0
2
// SPDX-FileCopyrightText: Copyright the Vortex contributors
3

4
use std::any::Any;
5
use std::fmt::{Debug, Formatter};
6
use std::sync::Arc;
7

8
use async_trait::async_trait;
9
use datafusion::arrow::datatypes::{Schema, SchemaRef};
10
use datafusion::catalog::Session;
11
use datafusion::common::parsers::CompressionTypeVariant;
12
use datafusion::common::runtime::SpawnedTask;
13
use datafusion::common::stats::Precision;
14
use datafusion::common::{
15
    ColumnStatistics, DataFusionError, GetExt, Result as DFResult, Statistics,
16
    config_datafusion_err, not_impl_err,
17
};
18
use datafusion::datasource::file_format::file_compression_type::FileCompressionType;
19
use datafusion::datasource::file_format::{FileFormat, FileFormatFactory};
20
use datafusion::datasource::physical_plan::{
21
    FileScanConfig, FileScanConfigBuilder, FileSinkConfig, FileSource,
22
};
23
use datafusion::datasource::sink::DataSinkExec;
24
use datafusion::datasource::source::DataSourceExec;
25
use datafusion::logical_expr::dml::InsertOp;
26
use datafusion::physical_expr::LexRequirement;
27
use datafusion::physical_plan::ExecutionPlan;
28
use futures::{FutureExt, StreamExt as _, TryStreamExt as _, stream};
29
use itertools::Itertools;
30
use object_store::{ObjectMeta, ObjectStore};
31
use vortex::dtype::DType;
32
use vortex::dtype::arrow::FromArrowType;
33
use vortex::error::{VortexExpect, VortexResult, vortex_err};
34
use vortex::file::VORTEX_FILE_EXTENSION;
35
use vortex::metrics::VortexMetrics;
36
use vortex::session::VortexSession;
37
use vortex::stats;
38
use vortex::stats::{Stat, StatsProviderExt, StatsSet};
39

40
use super::cache::VortexFileCache;
41
use super::sink::VortexSink;
42
use super::source::VortexSource;
43
use crate::PrecisionExt as _;
44
use crate::convert::TryToDataFusion;
45

46
/// Vortex implementation of a DataFusion [`FileFormat`].
47
pub struct VortexFormat {
48
    session: Arc<VortexSession>,
49
    file_cache: VortexFileCache,
50
    opts: VortexFormatOptions,
51
}
52

53
impl Debug for VortexFormat {
54
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
×
55
        f.debug_struct("VortexFormat")
×
56
            .field("opts", &self.opts)
×
57
            .finish()
×
UNCOV
58
    }
×
59
}
60

61
/// Options to configure the [`VortexFormat`].
62
#[derive(Debug)]
63
pub struct VortexFormatOptions {
64
    /// The size of the in-memory [`vortex::file::Footer`] cache.
65
    pub footer_cache_size_mb: usize,
66
    /// The size of the in-memory segment cache.
67
    pub segment_cache_size_mb: usize,
68
}
69

70
impl Default for VortexFormatOptions {
71
    fn default() -> Self {
20✔
72
        Self {
20✔
73
            footer_cache_size_mb: 64,
20✔
74
            segment_cache_size_mb: 0,
20✔
75
        }
20✔
76
    }
20✔
77
}
78

79
/// Minimal factory to create [`VortexFormat`] instances.
80
#[derive(Default, Debug)]
81
pub struct VortexFormatFactory {
82
    session: Arc<VortexSession>,
83
}
84

85
impl GetExt for VortexFormatFactory {
86
    fn get_ext(&self) -> String {
18✔
87
        VORTEX_FILE_EXTENSION.to_string()
18✔
88
    }
18✔
89
}
90

91
impl FileFormatFactory for VortexFormatFactory {
92
    #[allow(clippy::disallowed_types)]
93
    fn create(
3✔
94
        &self,
3✔
95
        _state: &dyn Session,
3✔
96
        format_options: &std::collections::HashMap<String, String>,
3✔
97
    ) -> DFResult<Arc<dyn FileFormat>> {
3✔
98
        if !format_options.is_empty() {
3✔
99
            return Err(config_datafusion_err!(
1✔
100
                "Vortex tables don't support any options"
1✔
101
            ));
1✔
102
        }
2✔
103

104
        Ok(Arc::new(VortexFormat::new(self.session.clone())))
2✔
105
    }
3✔
106

107
    fn default(&self) -> Arc<dyn FileFormat> {
×
108
        Arc::new(VortexFormat::default())
×
UNCOV
109
    }
×
110

111
    fn as_any(&self) -> &dyn Any {
×
112
        self
×
UNCOV
113
    }
×
114
}
115

116
impl Default for VortexFormat {
117
    fn default() -> Self {
18✔
118
        Self::new(Arc::new(VortexSession::default()))
18✔
119
    }
18✔
120
}
121

122
impl VortexFormat {
123
    /// Create a new instance of the [`VortexFormat`].
124
    pub fn new(session: Arc<VortexSession>) -> Self {
20✔
125
        let opts = VortexFormatOptions::default();
20✔
126
        Self {
20✔
127
            session: session.clone(),
20✔
128
            file_cache: VortexFileCache::new(
20✔
129
                opts.footer_cache_size_mb,
20✔
130
                opts.segment_cache_size_mb,
20✔
131
                session,
20✔
132
            ),
20✔
133
            opts,
20✔
134
        }
20✔
135
    }
20✔
136

137
    /// Return the format specific configuration
138
    pub fn options(&self) -> &VortexFormatOptions {
×
139
        &self.opts
×
UNCOV
140
    }
×
141
}
142

143
#[async_trait]
144
impl FileFormat for VortexFormat {
145
    fn as_any(&self) -> &dyn Any {
×
146
        self
×
UNCOV
147
    }
×
148

149
    fn get_ext(&self) -> String {
22✔
150
        VORTEX_FILE_EXTENSION.to_string()
22✔
151
    }
22✔
152

153
    fn get_ext_with_compression(
×
154
        &self,
×
155
        file_compression_type: &FileCompressionType,
×
156
    ) -> DFResult<String> {
×
157
        match file_compression_type.get_variant() {
×
158
            CompressionTypeVariant::UNCOMPRESSED => Ok(self.get_ext()),
×
159
            _ => Err(DataFusionError::Internal(
×
160
                "Vortex does not support file level compression.".into(),
×
UNCOV
161
            )),
×
162
        }
UNCOV
163
    }
×
164

165
    async fn infer_schema(
166
        &self,
167
        state: &dyn Session,
168
        store: &Arc<dyn ObjectStore>,
169
        objects: &[ObjectMeta],
170
    ) -> DFResult<SchemaRef> {
4✔
171
        let mut file_schemas = stream::iter(objects.iter().cloned())
2✔
172
            .map(|o| {
2✔
173
                let store = store.clone();
2✔
174
                let cache = self.file_cache.clone();
2✔
175
                SpawnedTask::spawn(async move {
2✔
176
                    let vxf = cache.try_get(&o, store).await?;
2✔
177
                    let inferred_schema = vxf.dtype().to_arrow_schema()?;
2✔
178
                    VortexResult::Ok((o.location, inferred_schema))
2✔
179
                })
2✔
180
                .map(|f| f.vortex_expect("Failed to spawn infer_schema"))
2✔
181
            })
2✔
182
            .buffer_unordered(state.config_options().execution.meta_fetch_concurrency)
2✔
183
            .try_collect::<Vec<_>>()
2✔
184
            .await
2✔
185
            .map_err(|e| DataFusionError::Execution(format!("Failed to infer schema: {e}")))?;
2✔
186

187
        // Get consistent order of schemas for `Schema::try_merge`, as some filesystems don't have deterministic listing orders
188
        file_schemas.sort_by(|(l1, _), (l2, _)| l1.cmp(l2));
2✔
189
        let file_schemas = file_schemas.into_iter().map(|(_, schema)| schema);
2✔
190

191
        Ok(Arc::new(Schema::try_merge(file_schemas)?))
2✔
192
    }
4✔
193

194
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all, fields(location = object.location.as_ref()
195
    )))]
196
    async fn infer_stats(
197
        &self,
198
        _state: &dyn Session,
199
        store: &Arc<dyn ObjectStore>,
200
        table_schema: SchemaRef,
201
        object: &ObjectMeta,
202
    ) -> DFResult<Statistics> {
52✔
203
        let object = object.clone();
28✔
204
        let store = store.clone();
28✔
205
        let cache = self.file_cache.clone();
28✔
206
        SpawnedTask::spawn(async move {
28✔
207
            let vxf = cache.try_get(&object, store.clone()).await.map_err(|e| {
28✔
208
                DataFusionError::Execution(format!(
×
209
                    "Failed to open Vortex file {}: {e}",
×
210
                    object.location
×
211
                ))
×
UNCOV
212
            })?;
×
213

214
            let struct_dtype = vxf
28✔
215
                .dtype()
28✔
216
                .as_struct()
28✔
217
                .vortex_expect("dtype is not a struct");
28✔
218

219
            // Evaluate the statistics for each column that we are able to return to DataFusion.
220
            let Some(file_stats) = vxf.file_stats() else {
28✔
221
                // If the file has no column stats, the best we can do is return a row count.
222
                return Ok(Statistics {
223
                    num_rows: Precision::Exact(
224
                        usize::try_from(vxf.row_count())
×
225
                            .map_err(|_| vortex_err!("Row count overflow"))
×
UNCOV
226
                            .vortex_expect("Row count overflow"),
×
227
                    ),
228
                    total_byte_size: Precision::Absent,
×
UNCOV
229
                    column_statistics: vec![ColumnStatistics::default(); struct_dtype.nfields()],
×
230
                });
231
            };
232

233
            let stats = table_schema
28✔
234
                .fields()
28✔
235
                .iter()
28✔
236
                .map(|field| struct_dtype.find(field.name()))
168✔
237
                .map(|idx| match idx {
168✔
UNCOV
238
                    None => StatsSet::default(),
×
239
                    Some(id) => file_stats[id].clone(),
168✔
240
                })
168✔
241
                .collect_vec();
28✔
242

243
            let total_byte_size = stats
28✔
244
                .iter()
28✔
245
                .map(|stats_set| {
168✔
246
                    stats_set
168✔
247
                        .get_as::<usize>(Stat::UncompressedSizeInBytes)
168✔
248
                        .unwrap_or_else(|| stats::Precision::inexact(0_usize))
168✔
249
                })
168✔
250
                .fold(stats::Precision::exact(0_usize), |acc, stats_set| {
168✔
251
                    acc.zip(stats_set).map(|(acc, stats_set)| acc + stats_set)
168✔
252
                });
168✔
253

254
            // Sum up the total byte size across all the columns.
255
            let total_byte_size = total_byte_size.to_df();
28✔
256

257
            let column_statistics = stats
28✔
258
                .into_iter()
28✔
259
                .zip(table_schema.fields().iter())
28✔
260
                .map(|(stats_set, field)| {
168✔
261
                    let null_count = stats_set.get_as::<usize>(Stat::NullCount);
168✔
262
                    let min = stats_set
168✔
263
                        .get_scalar(Stat::Min, &DType::from_arrow(field.as_ref()))
168✔
264
                        .and_then(|n| n.map(|n| n.try_to_df().ok()).transpose());
168✔
265

266
                    let max = stats_set
168✔
267
                        .get_scalar(Stat::Max, &DType::from_arrow(field.as_ref()))
168✔
268
                        .and_then(|n| n.map(|n| n.try_to_df().ok()).transpose());
168✔
269

270
                    ColumnStatistics {
271
                        null_count: null_count.to_df(),
168✔
272
                        max_value: max.to_df(),
168✔
273
                        min_value: min.to_df(),
168✔
274
                        sum_value: Precision::Absent,
168✔
275
                        distinct_count: stats_set
168✔
276
                            .get_as::<bool>(Stat::IsConstant)
168✔
277
                            .and_then(|is_constant| {
168✔
278
                                is_constant.as_exact().map(|_| Precision::Exact(1))
×
UNCOV
279
                            })
×
280
                            .unwrap_or(Precision::Absent),
168✔
281
                    }
282
                })
168✔
283
                .collect::<Vec<_>>();
28✔
284

285
            Ok(Statistics {
286
                num_rows: Precision::Exact(
287
                    usize::try_from(vxf.row_count())
28✔
288
                        .map_err(|_| vortex_err!("Row count overflow"))
28✔
289
                        .vortex_expect("Row count overflow"),
28✔
290
                ),
291
                total_byte_size,
28✔
292
                column_statistics,
28✔
293
            })
294
        })
28✔
295
        .await
28✔
296
        .vortex_expect("Failed to spawn infer_stats")
28✔
297
    }
52✔
298

299
    async fn create_physical_plan(
300
        &self,
301
        _state: &dyn Session,
302
        file_scan_config: FileScanConfig,
303
    ) -> DFResult<Arc<dyn ExecutionPlan>> {
360✔
304
        if file_scan_config
180✔
305
            .file_groups
180✔
306
            .iter()
180✔
307
            .flat_map(|fg| fg.files())
182✔
308
            .any(|f| f.range.is_some())
182✔
309
        {
UNCOV
310
            return not_impl_err!("File level partitioning isn't implemented yet for Vortex");
×
311
        }
180✔
312

313
        if !file_scan_config.table_partition_cols.is_empty() {
180✔
UNCOV
314
            return not_impl_err!("Hive style partitioning isn't implemented yet for Vortex");
×
315
        }
180✔
316

317
        if !file_scan_config.output_ordering.is_empty() {
180✔
UNCOV
318
            return not_impl_err!("Vortex doesn't support output ordering");
×
319
        }
180✔
320

321
        let source = VortexSource::new(self.file_cache.clone(), self.session.metrics().clone());
180✔
322
        Ok(DataSourceExec::from_data_source(
180✔
323
            FileScanConfigBuilder::from(file_scan_config)
180✔
324
                .with_source(Arc::new(source))
180✔
325
                .build(),
180✔
326
        ))
180✔
327
    }
360✔
328

329
    async fn create_writer_physical_plan(
330
        &self,
331
        input: Arc<dyn ExecutionPlan>,
332
        _state: &dyn Session,
333
        conf: FileSinkConfig,
334
        order_requirements: Option<LexRequirement>,
335
    ) -> DFResult<Arc<dyn ExecutionPlan>> {
4✔
336
        if conf.insert_op != InsertOp::Append {
2✔
UNCOV
337
            return not_impl_err!("Overwrites are not implemented yet for Vortex");
×
338
        }
2✔
339

340
        if !conf.table_partition_cols.is_empty() {
2✔
UNCOV
341
            return not_impl_err!("Hive style partitioning isn't implemented yet for Vortex");
×
342
        }
2✔
343

344
        let schema = conf.output_schema().clone();
2✔
345
        let sink = Arc::new(VortexSink::new(conf, schema));
2✔
346

347
        Ok(Arc::new(DataSinkExec::new(input, sink, order_requirements)) as _)
2✔
348
    }
4✔
349

350
    fn file_source(&self) -> Arc<dyn FileSource> {
180✔
351
        Arc::new(VortexSource::new(
180✔
352
            self.file_cache.clone(),
180✔
353
            VortexMetrics::default(),
180✔
354
        ))
180✔
355
    }
180✔
356
}
357

358
#[cfg(test)]
359
mod tests {
360
    use datafusion::execution::SessionStateBuilder;
361
    use datafusion::prelude::SessionContext;
362
    use tempfile::TempDir;
363

364
    use super::*;
365
    use crate::persistent::register_vortex_format_factory;
366

367
    #[tokio::test]
368
    async fn create_table() {
1✔
369
        let dir = TempDir::new().unwrap();
1✔
370

371
        let factory: VortexFormatFactory = Default::default();
1✔
372
        let mut session_state_builder = SessionStateBuilder::new().with_default_features();
1✔
373
        register_vortex_format_factory(factory, &mut session_state_builder);
1✔
374
        let session = SessionContext::new_with_state(session_state_builder.build());
1✔
375

376
        let df = session
1✔
377
            .sql(&format!(
1✔
378
                "CREATE EXTERNAL TABLE my_tbl \
1✔
379
                (c1 VARCHAR NOT NULL, c2 INT NOT NULL) \
1✔
380
                STORED AS vortex LOCATION '{}'",
1✔
381
                dir.path().to_str().unwrap()
1✔
382
            ))
1✔
383
            .await
1✔
384
            .unwrap();
1✔
385

386
        assert_eq!(df.count().await.unwrap(), 0);
1✔
387
    }
1✔
388

389
    #[tokio::test]
390
    #[should_panic]
391
    async fn fail_table_config() {
1✔
392
        let dir = TempDir::new().unwrap();
1✔
393

394
        let factory: VortexFormatFactory = Default::default();
1✔
395
        let mut session_state_builder = SessionStateBuilder::new().with_default_features();
1✔
396
        register_vortex_format_factory(factory, &mut session_state_builder);
1✔
397
        let session = SessionContext::new_with_state(session_state_builder.build());
1✔
398

399
        session
1✔
400
            .sql(&format!(
1✔
401
                "CREATE EXTERNAL TABLE my_tbl \
1✔
402
                (c1 VARCHAR NOT NULL, c2 INT NOT NULL) \
1✔
403
                STORED AS vortex LOCATION '{}' \
1✔
404
                OPTIONS( some_key 'value' );",
1✔
405
                dir.path().to_str().unwrap()
1✔
406
            ))
1✔
407
            .await
1✔
408
            .unwrap()
1✔
409
            .collect()
1✔
410
            .await
1✔
411
            .unwrap();
1✔
412
    }
1✔
413
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc