HairstonE commented on code in PR #27934:
URL: https://github.com/apache/datafusion/pull/27934#discussion_r4762027434


##########
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<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

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



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to