From a35d0ec21d196cf1cf4ef2abfc5a876c8b0f25c6 Mon Sep 17 00:00:00 2001 From: HairstonE Date: Tue, 1 Dec 2026 17:20:18 -0500 Subject: [PATCH 1/3] feat: add pinned object store wrapper and ObjectVersionType --- datafusion/datasource/src/mod.rs | 18 +++ datafusion/datasource/src/pinned_store.rs | 179 ++++++++++++++++++++++ 2 files changed, 197 insertions(+) create mode 100644 datafusion/datasource/src/pinned_store.rs diff --git a/datafusion/datasource/src/mod.rs b/datafusion/datasource/src/mod.rs index 1847aab6fa2c6..0d43394248f70 100644 --- a/datafusion/datasource/src/mod.rs +++ b/datafusion/datasource/src/mod.rs @@ -27,6 +27,15 @@ pub mod file_sink_config; pub mod file_stream; pub mod memory; pub mod morsel; +/// Pin file reads to a planning-time etag or version. +/// +/// # Public Only for Internal Use: +/// +/// This is not a public API and is for internal use only; see [API policy] for details. +/// +/// [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis +#[doc(hidden)] +pub mod pinned_store; pub mod projection; /// Protobuf conversions for [`FileRange`], [`PartitionedFile`] and /// [`FileGroup`], gated on the `proto` feature. @@ -67,6 +76,15 @@ pub use table_schema::{TableSchema, TableSchemaBuilder}; /// and other extension fields throughout DataFusion. pub type FileExtensions = datafusion_common::extensions::Extensions; +/// Which [`ObjectMeta`] field pins reads to the object seen at planning time +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ObjectVersionType { + /// Pin with `If-Match` on the etag + ETag, + /// Pin with the store's object version + Version, +} + /// Stream of files get listed from object store #[deprecated( since = "54.0.0", diff --git a/datafusion/datasource/src/pinned_store.rs b/datafusion/datasource/src/pinned_store.rs new file mode 100644 index 0000000000000..25ce6100a660d --- /dev/null +++ b/datafusion/datasource/src/pinned_store.rs @@ -0,0 +1,179 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! Pin every read of one object to its planning-time etag or version + +use crate::ObjectVersionType; +use async_trait::async_trait; +use datafusion_common::{Result, exec_err}; +use futures::stream::BoxStream; +use object_store::path::Path; +use object_store::{ + CopyOptions, GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, + ObjectStore, PutMultipartOptions, PutOptions, PutPayload, PutResult, + Result as StoreResult, +}; +use std::fmt::{self, Display}; +use std::sync::Arc; + +/// Decorates a store so every `get_opts` carries the etag or version of one object. +/// +/// `get_range` / `get_ranges` / `head` are deliberately not overridden: their +/// default implementations route through [`ObjectStore::get_opts`], so they are +/// pinned too and range coalescing is preserved. +#[derive(Debug)] +struct PinnedObjectStore { + inner: Arc, + if_match: Option, + version: Option, +} + +impl PinnedObjectStore { + fn try_new( + inner: Arc, + meta: &ObjectMeta, + version_type: ObjectVersionType, + ) -> Result { + let (if_match, version) = match version_type { + ObjectVersionType::ETag => (meta.e_tag.clone(), None), + ObjectVersionType::Version => (None, meta.version.clone()), + }; + if if_match.is_none() && version.is_none() { + return exec_err!( + "Cannot pin {} to its {version_type:?}: object metadata has none", + meta.location + ); + } + Ok(Self { + inner, + if_match, + version, + }) + } +} + +/// Returns `store` pinned to `meta`, or `store` itself when versioning is off. +pub fn pin_store( + store: &Arc, + version_type: Option, + meta: &ObjectMeta, +) -> Result> { + let Some(version_type) = version_type else { + return Ok(Arc::clone(store)); + }; + Ok(Arc::new(PinnedObjectStore::try_new( + Arc::clone(store), + meta, + version_type, + )?)) +} + +impl Display for PinnedObjectStore { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "PinnedObjectStore({})", self.inner) + } +} + +#[async_trait] +impl ObjectStore for PinnedObjectStore { + async fn put_opts( + &self, + location: &Path, + payload: PutPayload, + opts: PutOptions, + ) -> StoreResult { + self.inner.put_opts(location, payload, opts).await + } + + async fn put_multipart_opts( + &self, + location: &Path, + opts: PutMultipartOptions, + ) -> StoreResult> { + self.inner.put_multipart_opts(location, opts).await + } + + async fn get_opts( + &self, + location: &Path, + mut options: GetOptions, + ) -> StoreResult { + if options.if_match.is_none() { + options.if_match = self.if_match.clone(); + } + if options.version.is_none() { + options.version = self.version.clone(); + } + self.inner.get_opts(location, options).await + } + + fn delete_stream( + &self, + locations: BoxStream<'static, StoreResult>, + ) -> BoxStream<'static, StoreResult> { + self.inner.delete_stream(locations) + } + + fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, StoreResult> { + self.inner.list(prefix) + } + + async fn list_with_delimiter( + &self, + prefix: Option<&Path>, + ) -> StoreResult { + self.inner.list_with_delimiter(prefix).await + } + + async fn copy_opts( + &self, + from: &Path, + to: &Path, + options: CopyOptions, + ) -> StoreResult<()> { + self.inner.copy_opts(from, to, options).await + } +} + +#[cfg(test)] +mod tests { + use super::*; + use object_store::memory::InMemory; + + fn meta(e_tag: Option<&str>, version: Option<&str>) -> ObjectMeta { + ObjectMeta { + location: Path::from("f"), + last_modified: chrono::DateTime::UNIX_EPOCH, + size: 1000, + e_tag: e_tag.map(str::to_string), + version: version.map(str::to_string), + } + } + + #[test] + fn missing_pin_data_is_an_error() { + let store: Arc = Arc::new(InMemory::new()); + let err = pin_store( + &store, + Some(ObjectVersionType::ETag), + &meta(None, Some("v")), + ) + .unwrap_err(); + assert!(err.to_string().contains("ETag"), "{err}"); + let err = pin_store( + &store, + Some(ObjectVersionType::Version), + &meta(Some("e"), None), + ) + .unwrap_err(); + assert!(err.to_string().contains("Version"), "{err}"); + } + + #[test] + fn pin_store_is_noop_when_off() { + let store: Arc = Arc::new(InMemory::new()); + let out = pin_store(&store, None, &meta(None, None)).unwrap(); + assert!(Arc::ptr_eq(&store, &out)); + } +} From ef50005545b8c7bc751225ea55ac5cdebe8ba67b Mon Sep 17 00:00:00 2001 From: HairstonE Date: Tue, 1 Dec 2026 17:20:18 -0500 Subject: [PATCH 2/3] feat: wire object_version_type from ListingOptions to the file openers --- datafusion/catalog-listing/src/options.rs | 15 ++++- datafusion/catalog-listing/src/table.rs | 1 + datafusion/datasource-csv/src/source.rs | 13 ++++- datafusion/datasource-json/src/source.rs | 14 ++++- .../datasource-parquet/src/file_format.rs | 6 +- datafusion/datasource-parquet/src/reader.rs | 55 ++++++++++++++----- datafusion/datasource-parquet/src/source.rs | 5 +- .../datasource/src/file_scan_config/mod.rs | 19 +++++++ .../datasource/src/file_scan_config/proto.rs | 8 +++ 9 files changed, 113 insertions(+), 23 deletions(-) diff --git a/datafusion/catalog-listing/src/options.rs b/datafusion/catalog-listing/src/options.rs index 5ce2081cc09a9..1cee1e7845834 100644 --- a/datafusion/catalog-listing/src/options.rs +++ b/datafusion/catalog-listing/src/options.rs @@ -5,8 +5,8 @@ use arrow::datatypes::{DataType, SchemaRef}; use datafusion_catalog::Session; use datafusion_common::plan_err; -use datafusion_datasource::ListingTableUrl; use datafusion_datasource::file_format::FileFormat; +use datafusion_datasource::{ListingTableUrl, ObjectVersionType}; use datafusion_expr::{Partitioning, SortExpr}; use futures::StreamExt; use futures::TryStreamExt; @@ -81,6 +81,9 @@ pub struct ListingOptions { /// partition 3: [] /// ``` pub output_partitioning: Option, + /// Pin parquet, CSV, and JSON reads to the etag or version captured at planning + /// time. Other formats and custom `ParquetFileReaderFactory` implementations are unpinned. + pub object_version_type: Option, } impl ListingOptions { @@ -95,9 +98,19 @@ impl ListingOptions { table_partition_cols: vec![], file_sort_order: vec![], output_partitioning: None, + object_version_type: None, } } + /// Set object version pinning on [`ListingOptions`] and returns self. + pub fn with_object_version_type( + mut self, + object_version_type: Option, + ) -> Self { + self.object_version_type = object_version_type; + self + } + /// Set file extension on [`ListingOptions`] and returns self. /// /// # Example diff --git a/datafusion/catalog-listing/src/table.rs b/datafusion/catalog-listing/src/table.rs index 05e3c6c9d1674..ddd315057303d 100644 --- a/datafusion/catalog-listing/src/table.rs +++ b/datafusion/catalog-listing/src/table.rs @@ -801,6 +801,7 @@ impl ListingTable { .with_output_ordering(output_ordering) .with_output_partitioning(output_partitioning) .with_expr_adapter(self.expr_adapter_factory.clone()) + .with_object_version_type(self.options.object_version_type) .build(); // create the execution plan diff --git a/datafusion/datasource-csv/src/source.rs b/datafusion/datasource-csv/src/source.rs index 81b43667d72af..437b4a2d7e67b 100644 --- a/datafusion/datasource-csv/src/source.rs +++ b/datafusion/datasource-csv/src/source.rs @@ -5,6 +5,7 @@ //! Execution plan for reading CSV files use datafusion_datasource::boundary_stream::AlignedBoundaryStream; +use datafusion_datasource::pinned_store::pin_store; use datafusion_datasource::projection::{ProjectionOpener, SplitProjection}; use datafusion_physical_plan::projection::ProjectionExprs; use std::fmt; @@ -16,7 +17,8 @@ use datafusion_datasource::decoder::{DecoderDeserializer, deserialize_stream}; use datafusion_datasource::file_compression_type::FileCompressionType; use datafusion_datasource::file_stream::{FileOpenFuture, FileOpener}; use datafusion_datasource::{ - FileRange, ListingTableUrl, PartitionedFile, TableSchema, as_file_source, + FileRange, ListingTableUrl, ObjectVersionType, PartitionedFile, TableSchema, + as_file_source, }; use arrow::array::RecordBatch; @@ -557,6 +559,7 @@ pub struct CsvOpener { object_store: Arc, partition_index: usize, expr_adapter_factory: Arc, + object_version_type: Option, } impl CsvOpener { @@ -572,6 +575,7 @@ impl CsvOpener { object_store, partition_index: 0, expr_adapter_factory: Arc::new(DefaultPhysicalExprAdapterFactory), + object_version_type: None, } } @@ -614,6 +618,7 @@ impl FileSource for CsvSource { object_store, partition_index, expr_adapter_factory, + object_version_type: base_config.object_version_type, }) as Arc; opener = ProjectionOpener::try_new( self.projection.clone(), @@ -781,7 +786,11 @@ impl FileOpener for CsvOpener { ); } - let store = Arc::clone(&self.object_store); + let store = pin_store( + &self.object_store, + self.object_version_type, + &partitioned_file.object_meta, + )?; let line_end = self.config.terminator().unwrap_or(b'\n'); let baseline_metrics = diff --git a/datafusion/datasource-json/src/source.rs b/datafusion/datasource-json/src/source.rs index c3ca46a170b17..a90e6ff72eeb4 100644 --- a/datafusion/datasource-json/src/source.rs +++ b/datafusion/datasource-json/src/source.rs @@ -20,8 +20,11 @@ use datafusion_datasource::boundary_stream::AlignedBoundaryStream; use datafusion_datasource::decoder::{DecoderDeserializer, deserialize_stream}; use datafusion_datasource::file_compression_type::FileCompressionType; use datafusion_datasource::file_stream::{FileOpenFuture, FileOpener}; +use datafusion_datasource::pinned_store::pin_store; use datafusion_datasource::projection::{ProjectionOpener, SplitProjection}; -use datafusion_datasource::{ListingTableUrl, PartitionedFile, as_file_source}; +use datafusion_datasource::{ + ListingTableUrl, ObjectVersionType, PartitionedFile, as_file_source, +}; use datafusion_physical_plan::projection::ProjectionExprs; use datafusion_physical_plan::{ExecutionPlan, ExecutionPlanProperties}; @@ -95,6 +98,7 @@ pub struct JsonOpener { /// When `true`, a JSON number or boolean read into a string column is kept as its text. /// When `false` (default), it is an error. coerce_primitive: bool, + object_version_type: Option, } impl JsonOpener { @@ -113,6 +117,7 @@ impl JsonOpener { object_store, newline_delimited, coerce_primitive: false, + object_version_type: None, } } @@ -211,6 +216,7 @@ impl FileSource for JsonSource { object_store, newline_delimited: self.newline_delimited, coerce_primitive: self.coerce_primitive, + object_version_type: base_config.object_version_type, }) as Arc; // Wrap with ProjectionOpener @@ -368,7 +374,11 @@ impl FileOpener for JsonOpener { /// /// Note: JSON array format does not support range-based scanning. fn open(&self, partitioned_file: PartitionedFile) -> Result { - let store = Arc::clone(&self.object_store); + let store = pin_store( + &self.object_store, + self.object_version_type, + &partitioned_file.object_meta, + )?; let schema = Arc::clone(&self.projected_schema); let batch_size = self.batch_size; let file_compression_type = self.file_compression_type.to_owned(); diff --git a/datafusion/datasource-parquet/src/file_format.rs b/datafusion/datasource-parquet/src/file_format.rs index 0305eb1ab45dc..a0a8b5da70cb4 100644 --- a/datafusion/datasource-parquet/src/file_format.rs +++ b/datafusion/datasource-parquet/src/file_format.rs @@ -695,8 +695,10 @@ impl FileFormat for ParquetFormat { let store = state .runtime_env() .object_store(conf.object_store_url.clone())?; - let cached_parquet_read_factory = - Arc::new(CachedParquetFileReaderFactory::new(store, metadata_cache)); + let cached_parquet_read_factory = Arc::new( + CachedParquetFileReaderFactory::new(store, metadata_cache) + .with_object_version_type(conf.object_version_type), + ); source = source.with_parquet_file_reader_factory(cached_parquet_read_factory); if let Some(metadata_size_hint) = metadata_size_hint { diff --git a/datafusion/datasource-parquet/src/reader.rs b/datafusion/datasource-parquet/src/reader.rs index f9a5e11fddffd..2860a91253805 100644 --- a/datafusion/datasource-parquet/src/reader.rs +++ b/datafusion/datasource-parquet/src/reader.rs @@ -10,7 +10,8 @@ use crate::metadata::DFParquetMetadata; use arrow::datatypes::SchemaRef; use bytes::Bytes; use datafusion_common::HashMap; -use datafusion_datasource::PartitionedFile; +use datafusion_datasource::pinned_store::pin_store; +use datafusion_datasource::{ObjectVersionType, PartitionedFile}; use datafusion_execution::cache::cache_manager::FileMetadata; use datafusion_execution::cache::cache_manager::FileMetadataCache; use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet; @@ -100,12 +101,24 @@ impl dyn ParquetFileReaderFactory { #[derive(Debug)] pub struct DefaultParquetFileReaderFactory { store: Arc, + object_version_type: Option, } impl DefaultParquetFileReaderFactory { /// Create a new `DefaultParquetFileReaderFactory`. pub fn new(store: Arc) -> Self { - Self { store } + Self { + store, + object_version_type: None, + } + } + + pub(crate) fn with_object_version_type( + mut self, + object_version_type: Option, + ) -> Self { + self.object_version_type = object_version_type; + self } } @@ -123,12 +136,13 @@ impl ParquetFileReaderFactory for DefaultParquetFileReaderFactory { metrics, ); - let reader = ParquetFileReader::new( - file_metrics, - Arc::clone(&self.store), - partitioned_file, - ) - .with_metadata_hint(metadata_size_hint); + let store = pin_store( + &self.store, + self.object_version_type, + &partitioned_file.object_meta, + )?; + let reader = ParquetFileReader::new(file_metrics, store, partitioned_file) + .with_metadata_hint(metadata_size_hint); Ok(Box::new(reader)) } } @@ -143,6 +157,7 @@ impl ParquetFileReaderFactory for DefaultParquetFileReaderFactory { pub struct CachedParquetFileReaderFactory { store: Arc, metadata_cache: Arc, + object_version_type: Option, } impl CachedParquetFileReaderFactory { @@ -153,8 +168,17 @@ impl CachedParquetFileReaderFactory { Self { store, metadata_cache, + object_version_type: None, } } + + pub(crate) fn with_object_version_type( + mut self, + object_version_type: Option, + ) -> Self { + self.object_version_type = object_version_type; + self + } } impl ParquetFileReaderFactory for CachedParquetFileReaderFactory { @@ -171,13 +195,14 @@ impl ParquetFileReaderFactory for CachedParquetFileReaderFactory { metrics, ); - let reader = ParquetFileReader::new( - file_metrics, - Arc::clone(&self.store), - partitioned_file, - ) - .with_metadata_hint(metadata_size_hint) - .with_metadata_cache(Some(Arc::clone(&self.metadata_cache))); + let store = pin_store( + &self.store, + self.object_version_type, + &partitioned_file.object_meta, + )?; + let reader = ParquetFileReader::new(file_metrics, store, partitioned_file) + .with_metadata_hint(metadata_size_hint) + .with_metadata_cache(Some(Arc::clone(&self.metadata_cache))); Ok(Box::new(reader)) } diff --git a/datafusion/datasource-parquet/src/source.rs b/datafusion/datasource-parquet/src/source.rs index 62a003d24fa5c..278cf86cecc8b 100644 --- a/datafusion/datasource-parquet/src/source.rs +++ b/datafusion/datasource-parquet/src/source.rs @@ -573,7 +573,10 @@ impl FileSource for ParquetSource { let parquet_file_reader_factory = self.parquet_file_reader_factory.clone().unwrap_or_else(|| { - Arc::new(DefaultParquetFileReaderFactory::new(object_store)) as _ + Arc::new( + DefaultParquetFileReaderFactory::new(object_store) + .with_object_version_type(base_config.object_version_type), + ) as _ }); #[cfg(feature = "parquet_encryption")] diff --git a/datafusion/datasource/src/file_scan_config/mod.rs b/datafusion/datasource/src/file_scan_config/mod.rs index ddc1a2ddd5ba0..ce1fb0a69aa8b 100644 --- a/datafusion/datasource/src/file_scan_config/mod.rs +++ b/datafusion/datasource/src/file_scan_config/mod.rs @@ -14,6 +14,7 @@ pub(crate) mod sort_pushdown; #[cfg(feature = "proto")] mod proto; +use crate::ObjectVersionType; use crate::file_groups::FileGroup; use crate::{ PartitionedFile, display::FileGroupsDisplay, file::FileSource, @@ -190,6 +191,10 @@ pub struct FileScanConfig { pub output_ordering: Vec, /// File compression type pub file_compression_type: FileCompressionType, + /// Pin parquet, CSV, and JSON reads to the etag or version in + /// [`PartitionedFile::object_meta`](crate::PartitionedFile). + /// A config with this set cannot be serialized to protobuf. + pub object_version_type: Option, /// File source such as `ParquetSource`, `CsvSource`, `JsonSource`, etc. pub file_source: Arc, /// Batch size while creating new batches @@ -285,6 +290,7 @@ pub struct FileScanConfigBuilder { output_ordering: Vec, output_partitioning: Option, file_compression_type: Option, + object_version_type: Option, batch_size: Option, expr_adapter_factory: Option>, } @@ -308,6 +314,7 @@ impl FileScanConfigBuilder { output_ordering: vec![], output_partitioning: None, file_compression_type: None, + object_version_type: None, limit: None, preserve_order: false, constraints: None, @@ -486,6 +493,15 @@ impl FileScanConfigBuilder { self } + /// Set the object_version_type property + pub fn with_object_version_type( + mut self, + object_version_type: Option, + ) -> Self { + self.object_version_type = object_version_type; + self + } + /// Set the batch_size property pub fn with_batch_size(mut self, batch_size: Option) -> Self { self.batch_size = batch_size; @@ -525,6 +541,7 @@ impl FileScanConfigBuilder { output_ordering, output_partitioning, file_compression_type, + object_version_type, batch_size, expr_adapter_factory: expr_adapter, } = self; @@ -549,6 +566,7 @@ impl FileScanConfigBuilder { file_groups, output_ordering, file_compression_type, + object_version_type, batch_size, expr_adapter_factory: expr_adapter, statistics, @@ -593,6 +611,7 @@ impl From for FileScanConfigBuilder { output_ordering: config.output_ordering, output_partitioning: config.output_partitioning, file_compression_type: Some(config.file_compression_type), + object_version_type: config.object_version_type, limit: config.limit, preserve_order: config.preserve_order, constraints: Some(config.constraints), diff --git a/datafusion/datasource/src/file_scan_config/proto.rs b/datafusion/datasource/src/file_scan_config/proto.rs index 0e98d89f5e14f..91769afa51011 100644 --- a/datafusion/datasource/src/file_scan_config/proto.rs +++ b/datafusion/datasource/src/file_scan_config/proto.rs @@ -74,6 +74,7 @@ impl FileScanConfig { // Serialized through `statistics()` so its pushed-filter policy // remains centralized. statistics: _, + object_version_type, output_partitioning, } = self; @@ -88,6 +89,13 @@ impl FileScanConfig { ); } + // The `PartitionedFile` proto drops the etag/version a pin needs. + if object_version_type.is_some() { + return datafusion_common::not_impl_err!( + "FileScanConfig with object_version_type set cannot be serialized" + ); + } + let proto_file_groups = file_groups .iter() .map(TryInto::try_into) From 206825ce71948a7db7e00eef8f47611965456639 Mon Sep 17 00:00:00 2001 From: HairstonE Date: Tue, 1 Dec 2026 17:20:18 -0500 Subject: [PATCH 3/3] test: object version pinning across parquet, csv and json scans --- datafusion/core/tests/datasource/mod.rs | 1 + .../tests/datasource/object_store_access.rs | 12 +- .../datasource/object_version_pinning.rs | 209 ++++++++++++++++++ 3 files changed, 216 insertions(+), 6 deletions(-) create mode 100644 datafusion/core/tests/datasource/object_version_pinning.rs diff --git a/datafusion/core/tests/datasource/mod.rs b/datafusion/core/tests/datasource/mod.rs index 7fcc120bf3d55..532d35e8e87d1 100644 --- a/datafusion/core/tests/datasource/mod.rs +++ b/datafusion/core/tests/datasource/mod.rs @@ -11,3 +11,4 @@ mod compression; // Include tests in csv module mod csv; mod object_store_access; +mod object_version_pinning; diff --git a/datafusion/core/tests/datasource/object_store_access.rs b/datafusion/core/tests/datasource/object_store_access.rs index b0fa71890dbb9..2edb8b4236607 100644 --- a/datafusion/core/tests/datasource/object_store_access.rs +++ b/datafusion/core/tests/datasource/object_store_access.rs @@ -1429,7 +1429,7 @@ impl Test { /// Details of individual requests made through the [`RequestCountingObjectStore`] #[derive(Clone, Debug)] -enum RequestDetails { +pub(crate) enum RequestDetails { GetOpts { path: Path, get_options: GetOptions }, GetRanges { path: Path, ranges: Vec> }, List { prefix: Option }, @@ -1508,7 +1508,7 @@ impl Display for RequestDetails { } #[derive(Debug)] -struct RequestCountingObjectStore { +pub(crate) struct RequestCountingObjectStore { /// Inner (memory) store inner: Arc, requests: Mutex>, @@ -1550,11 +1550,11 @@ impl RequestCountingObjectStore { impl ObjectStore for RequestCountingObjectStore { async fn put_opts( &self, - _location: &Path, - _payload: PutPayload, - _opts: PutOptions, + location: &Path, + payload: PutPayload, + opts: PutOptions, ) -> object_store::Result { - unimplemented!() + self.inner.put_opts(location, payload, opts).await } async fn put_multipart_opts( diff --git a/datafusion/core/tests/datasource/object_version_pinning.rs b/datafusion/core/tests/datasource/object_version_pinning.rs new file mode 100644 index 0000000000000..49a5b5eb4d18c --- /dev/null +++ b/datafusion/core/tests/datasource/object_version_pinning.rs @@ -0,0 +1,209 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +use super::object_store_access::{RequestCountingObjectStore, RequestDetails}; +use arrow::array::{ArrayRef, Int32Array, RecordBatch}; +use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; +use datafusion::physical_plan::{ExecutionPlan, collect}; +use datafusion::prelude::SessionContext; +use datafusion_catalog_listing::{ListingOptions, ListingTable, ListingTableConfig}; +use datafusion_common::Result; +use datafusion_datasource::file_format::FileFormat; +use datafusion_datasource::{ListingTableUrl, ObjectVersionType}; +use datafusion_datasource_csv::CsvFormat; +use datafusion_datasource_json::JsonFormat; +use datafusion_datasource_parquet::file_format::ParquetFormat; +use object_store::path::Path; +use object_store::{ObjectStore, ObjectStoreExt}; +use parquet::arrow::ArrowWriter; +use std::sync::Arc; +use url::Url; + +#[derive(Clone, Copy, Debug)] +enum Kind { + Parquet, + Csv, + Json, +} + +impl Kind { + fn all() -> [Kind; 3] { + [Kind::Parquet, Kind::Csv, Kind::Json] + } + + fn format(self) -> Arc { + match self { + Kind::Parquet => Arc::new(ParquetFormat::default()), + Kind::Csv => Arc::new(CsvFormat::default().with_has_header(true)), + Kind::Json => Arc::new(JsonFormat::default()), + } + } + + fn path(self) -> &'static str { + match self { + Kind::Parquet => "t/data.parquet", + Kind::Csv => "t/data.csv", + Kind::Json => "t/data.json", + } + } + + fn bytes(self, values: &[i32]) -> Vec { + match self { + Kind::Parquet => { + let array: ArrayRef = Arc::new(Int32Array::from(values.to_vec())); + let batch = RecordBatch::try_new(schema(), vec![array]).unwrap(); + let mut out = vec![]; + let mut writer = ArrowWriter::try_new(&mut out, schema(), None).unwrap(); + writer.write(&batch).unwrap(); + writer.close().unwrap(); + out + } + Kind::Csv => lines(values, "v\n", |v| v.to_string()), + Kind::Json => lines(values, "", |v| format!("{{\"v\":{v}}}")), + } + } +} + +fn lines(values: &[i32], header: &str, line: fn(&i32) -> String) -> Vec { + let mut out = header.to_string(); + for v in values { + out.push_str(&line(v)); + out.push('\n'); + } + out.into_bytes() +} + +fn schema() -> SchemaRef { + Arc::new(Schema::new(vec![Field::new("v", DataType::Int32, false)])) +} + +struct Fixture { + ctx: SessionContext, + store: Arc, + kind: Kind, +} + +impl Fixture { + async fn new(kind: Kind, pin: Option) -> Self { + let store = Arc::new(RequestCountingObjectStore::new()); + store + .put(&Path::from(kind.path()), kind.bytes(&[1, 2, 3]).into()) + .await + .unwrap(); + let ctx = SessionContext::new(); + ctx.runtime_env().register_object_store( + &Url::parse("mem://").unwrap(), + Arc::clone(&store) as Arc, + ); + let options = ListingOptions::new(kind.format()) + .with_file_extension(kind.path().rsplit('.').next().unwrap()) + .with_object_version_type(pin); + let config = + ListingTableConfig::new(ListingTableUrl::parse("mem:///t/").unwrap()) + .with_listing_options(options) + .with_schema(schema()); + ctx.register_table("t", Arc::new(ListingTable::try_new(config).unwrap())) + .unwrap(); + Self { ctx, store, kind } + } + + async fn plan(&self) -> Arc { + let df = self.ctx.sql("SELECT v FROM t").await.unwrap(); + let plan = df.create_physical_plan().await.unwrap(); + self.store.clear_requests(); + plan + } + + async fn run(&self, plan: Arc) -> Result> { + collect(plan, self.ctx.task_ctx()).await + } + + async fn current_etag(&self) -> String { + let meta = self + .store + .head(&Path::from(self.kind.path())) + .await + .unwrap(); + meta.e_tag.unwrap() + } + + fn recorded_reads(&self) -> Vec { + self.store + .recorded_requests() + .into_iter() + .filter(|r| { + matches!( + r, + RequestDetails::GetOpts { .. } | RequestDetails::GetRanges { .. } + ) + }) + .collect() + } +} + +#[tokio::test] +async fn execution_reads_carry_the_pin_only_when_pinned() { + for kind in Kind::all() { + for pin in [Some(ObjectVersionType::ETag), None] { + let fx = Fixture::new(kind, pin).await; + let etag = fx.current_etag().await; + let plan = fx.plan().await; + + let batches = fx.run(plan).await.unwrap(); + assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 3); + + let want = pin.map(|_| etag.clone()); + let reads = fx.recorded_reads(); + assert!(!reads.is_empty(), "{kind:?}: no reads recorded"); + for read in reads { + match read { + RequestDetails::GetOpts { get_options, .. } => { + assert_eq!(get_options.if_match, want, "{kind:?} pin={pin:?}"); + } + // A raw `get_ranges` bypasses `get_opts`, so it can never carry a pin + other => assert!(pin.is_none(), "{kind:?}: unpinned {other:?}"), + } + } + } + } +} + +#[tokio::test] +async fn overwrite_between_plan_and_execute_fails_only_when_pinned() { + for kind in Kind::all() { + for pin in [Some(ObjectVersionType::ETag), None] { + let fx = Fixture::new(kind, pin).await; + let plan = fx.plan().await; + + // Same size, different content, new etag + fx.store + .put(&Path::from(kind.path()), kind.bytes(&[7, 8, 9]).into()) + .await + .unwrap(); + + let run = fx.run(plan).await; + if pin.is_none() { + // Documents the bug this feature guards against + assert!(run.is_ok(), "{kind:?}"); + continue; + } + let err = run.unwrap_err().to_string(); + assert!( + err.contains("Precondition") || err.contains("does not match"), + "{kind:?}: unexpected error: {err}" + ); + } + } +} + +#[tokio::test] +async fn version_pinning_without_version_errors_at_open() { + // InMemory reports no `version`, so Version pinning must fail cleanly + for kind in Kind::all() { + let fx = Fixture::new(kind, Some(ObjectVersionType::Version)).await; + let plan = fx.plan().await; + let err = fx.run(plan).await.unwrap_err().to_string(); + assert!(err.contains("Cannot pin"), "{kind:?}: {err}"); + } +}