Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion datafusion/catalog-listing/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -81,6 +81,9 @@ pub struct ListingOptions {
/// partition 3: []
/// ```
pub output_partitioning: Option<Partitioning>,
/// 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<ObjectVersionType>,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AVRO, Arrow, and custom ParquetFileReaderFactory implementations are not pinned.

}

impl ListingOptions {
Expand All @@ -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<ObjectVersionType>,
) -> Self {
self.object_version_type = object_version_type;
self
}

/// Set file extension on [`ListingOptions`] and returns self.
///
/// # Example
Expand Down
1 change: 1 addition & 0 deletions datafusion/catalog-listing/src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions datafusion/core/tests/datasource/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ mod compression;
// Include tests in csv module
mod csv;
mod object_store_access;
mod object_version_pinning;
12 changes: 6 additions & 6 deletions datafusion/core/tests/datasource/object_store_access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Range<u64>> },
List { prefix: Option<Path> },
Expand Down Expand Up @@ -1508,7 +1508,7 @@ impl Display for RequestDetails {
}

#[derive(Debug)]
struct RequestCountingObjectStore {
pub(crate) struct RequestCountingObjectStore {
/// Inner (memory) store
inner: Arc<dyn ObjectStore>,
requests: Mutex<Vec<RequestDetails>>,
Expand Down Expand Up @@ -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<PutResult> {
unimplemented!()
self.inner.put_opts(location, payload, opts).await
}

async fn put_multipart_opts(
Expand Down
209 changes: 209 additions & 0 deletions datafusion/core/tests/datasource/object_version_pinning.rs
Original file line number Diff line number Diff line change
@@ -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<dyn FileFormat> {
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<u8> {
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<u8> {
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<RequestCountingObjectStore>,
kind: Kind,
}

impl Fixture {
async fn new(kind: Kind, pin: Option<ObjectVersionType>) -> 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<dyn ObjectStore>,
);
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<dyn ExecutionPlan> {
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<dyn ExecutionPlan>) -> Result<Vec<RecordBatch>> {
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<RequestDetails> {
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::<usize>(), 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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

InMemory reports no version ids, so there is no end-to-end Version test. Version shares the ETag path except which field it copies.

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}");
}
}
13 changes: 11 additions & 2 deletions datafusion/datasource-csv/src/source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -557,6 +559,7 @@ pub struct CsvOpener {
object_store: Arc<dyn ObjectStore>,
partition_index: usize,
expr_adapter_factory: Arc<dyn PhysicalExprAdapterFactory>,
object_version_type: Option<ObjectVersionType>,
}

impl CsvOpener {
Expand All @@ -572,6 +575,7 @@ impl CsvOpener {
object_store,
partition_index: 0,
expr_adapter_factory: Arc::new(DefaultPhysicalExprAdapterFactory),
object_version_type: None,
}
}

Expand Down Expand Up @@ -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<dyn FileOpener>;
opener = ProjectionOpener::try_new(
self.projection.clone(),
Expand Down Expand Up @@ -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 =
Expand Down
Loading