From 18ac36f61b8528d69e181f34ee06fa913a136259 Mon Sep 17 00:00:00 2001 From: Noah Date: Sun, 22 Nov 2026 13:31:44 -0500 Subject: [PATCH 1/2] fix: require IcebergWriteExec's input sorted by partition without fanout insert_into added a sort on `_partition` when fanout was disabled, but no node required it, so the physical optimizer removed it and the clustered writer failed on unsorted input. For unpartitioned tables the sort was added anyway and failed at planning, since they have no `_partition` column. IcebergWriteExec now declares the ordering through `required_input_ordering`, only for partitioned tables written without fanout, and the optimizer adds the sort. `write/sort.rs` and the fanout parsing in insert_into are removed, along with the unit tests that inspected the unoptimized plan. --- AGENTS.md | 5 +- .../table_provider/catalog_table_provider.rs | 192 +------------- crates/datafusion/src/write/exec.rs | 27 +- crates/datafusion/src/write/mod.rs | 1 - crates/datafusion/src/write/sort.rs | 247 ------------------ crates/datafusion/tests/insert_into.rs | 98 ++++++- 6 files changed, 127 insertions(+), 443 deletions(-) delete mode 100644 crates/datafusion/src/write/sort.rs diff --git a/AGENTS.md b/AGENTS.md index 1859768..cacaea3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -100,13 +100,14 @@ Both providers report every filter as `Inexact`, so DataFusion re-applies the or input → project_with_partition partitioned tables only: appends a `_partition` struct column computed by `PartitionExpr` → repartition hash on `_partition` for identity/bucket transforms, otherwise round-robin; uses session target_partitions - → sort_by_partition only when table property `write.datafusion.fanout.enabled` is false (default: true) + → (optimizer) sort on `_partition`, which IcebergWriteExec requires when table property `write.datafusion.fanout.enabled` is false (default: true) → IcebergWriteExec per partition: `TaskWriter` writes Parquet files and emits Avro-serialized DataFiles in a `data_files: LargeBinary` column → CoalescePartitionsExec → IcebergCommitExec single partition: one `fast_append` transaction; outputs a `count` row ``` -- **`TaskWriter`** picks one of three writers: `UnpartitionedWriter`; `FanoutWriter` (accepts unsorted input, keeps many files open); or `ClusteredWriter` (requires sorted input, which is why the sort step exists). +- **`TaskWriter`** picks one of three writers: `UnpartitionedWriter`; `FanoutWriter` (accepts unsorted input, keeps many files open); or `ClusteredWriter` (requires sorted input, which is why `IcebergWriteExec` requires a sort without fanout). +- **Input requirements** belong on `IcebergWriteExec` (e.g. `required_input_ordering`), not as nodes added in `insert_into`: the physical optimizer removes a `SortExec` or `RepartitionExec` that no parent requires. - **Writer limits:** only Parquet is supported. The writer honors `write.parquet.*` table properties and table encryption. It matches columns by name, because DataFusion batches carry no field IDs. - **`PartitionExpr`** is public and retains its partition spec and table schema so that distributed engines can serialize them and rebuild the expression on workers with `try_new`. Its equality and hash are by value; don't go back to pointer equality. diff --git a/crates/datafusion/src/table_provider/catalog_table_provider.rs b/crates/datafusion/src/table_provider/catalog_table_provider.rs index 90eb52b..48c7b76 100644 --- a/crates/datafusion/src/table_provider/catalog_table_provider.rs +++ b/crates/datafusion/src/table_provider/catalog_table_provider.rs @@ -32,7 +32,6 @@ use datafusion::physical_plan::ExecutionPlan; use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec; use iceberg::arrow::schema_to_arrow_schema; use iceberg::inspect::MetadataTableType; -use iceberg::spec::TableProperties; use iceberg::{Catalog, NamespaceIdent, TableIdent}; use crate::error::to_datafusion_error; @@ -42,7 +41,6 @@ use crate::write::commit::IcebergCommitExec; use crate::write::exec::IcebergWriteExec; use crate::write::project::project_with_partition; use crate::write::repartition::repartition; -use crate::write::sort::sort_by_partition; /// Catalog-backed table provider with automatic metadata refresh. /// @@ -207,29 +205,8 @@ impl TableProvider for IcebergCatalogTableProvider { let repartitioned_plan = repartition(plan_with_partition, table.metadata_ref(), target_partitions)?; - // Apply sort node when it's not fanout mode - let fanout_enabled = table - .metadata() - .properties() - .get(TableProperties::PROPERTY_DATAFUSION_WRITE_FANOUT_ENABLED) - .map(|value| { - value.parse::().map_err(|e| { - config_datafusion_err!( - "Invalid value for {}, expected 'true' or 'false': {e}", - TableProperties::PROPERTY_DATAFUSION_WRITE_FANOUT_ENABLED - ) - }) - }) - .transpose()? - .unwrap_or(TableProperties::PROPERTY_DATAFUSION_WRITE_FANOUT_ENABLED_DEFAULT); - - let write_input = if fanout_enabled { - repartitioned_plan - } else { - sort_by_partition(repartitioned_plan)? - }; - - let write_plan = Arc::new(IcebergWriteExec::new(table.clone(), write_input)); + let write_plan = + Arc::new(IcebergWriteExec::new(table.clone(), repartitioned_plan)); // Merge the outputs of write_plan into one so we can commit all files together let coalesce_partitions = Arc::new(CoalescePartitionsExec::new(write_plan)); @@ -512,169 +489,4 @@ mod tests { temp_dir, ) } - - #[tokio::test] - async fn test_insert_plan_fanout_enabled_no_sort() { - use datafusion::datasource::TableProvider; - use datafusion::logical_expr::dml::InsertOp; - use datafusion::physical_plan::empty::EmptyExec; - - // When fanout is enabled (default), no sort node should be added - let (catalog, namespace, table_name, _temp_dir) = - get_partitioned_test_catalog_and_table(Some(true)).await; - - let provider = IcebergCatalogTableProvider::try_new( - catalog.clone(), - namespace.clone(), - table_name.clone(), - ) - .await - .unwrap(); - - let ctx = SessionContext::new(); - let input_schema = provider.schema(); - let input = Arc::new(EmptyExec::new(input_schema)) as Arc; - - let state = ctx.state(); - let insert_plan = provider - .insert_into(&state, input, InsertOp::Append) - .await - .unwrap(); - - // With fanout enabled, there should be no SortExec in the plan - assert!( - !plan_contains_sort(&insert_plan), - "Plan should NOT contain SortExec when fanout is enabled" - ); - } - - #[tokio::test] - async fn test_insert_plan_fanout_disabled_has_sort() { - use datafusion::datasource::TableProvider; - use datafusion::logical_expr::dml::InsertOp; - use datafusion::physical_plan::empty::EmptyExec; - - // When fanout is disabled, a sort node should be added - let (catalog, namespace, table_name, _temp_dir) = - get_partitioned_test_catalog_and_table(Some(false)).await; - - let provider = IcebergCatalogTableProvider::try_new( - catalog.clone(), - namespace.clone(), - table_name.clone(), - ) - .await - .unwrap(); - - let ctx = SessionContext::new(); - let input_schema = provider.schema(); - let input = Arc::new(EmptyExec::new(input_schema)) as Arc; - - let state = ctx.state(); - let insert_plan = provider - .insert_into(&state, input, InsertOp::Append) - .await - .unwrap(); - - // With fanout disabled, there should be a SortExec in the plan - assert!( - plan_contains_sort(&insert_plan), - "Plan should contain SortExec when fanout is disabled" - ); - } - - async fn get_partitioned_test_catalog_and_table( - fanout_enabled: Option, - ) -> (Arc, NamespaceIdent, String, TempDir) { - use iceberg::spec::{Transform, UnboundPartitionField, UnboundPartitionSpec}; - - let temp_dir = TempDir::new().unwrap(); - let warehouse_path = temp_dir.path().to_str().unwrap().to_string(); - - let catalog = MemoryCatalogBuilder::default() - .load( - "memory", - HashMap::from([( - MEMORY_CATALOG_WAREHOUSE.to_string(), - warehouse_path.clone(), - )]), - ) - .await - .unwrap(); - - let namespace = NamespaceIdent::new("test_ns".to_string()); - catalog - .create_namespace(&namespace, HashMap::new()) - .await - .unwrap(); - - let schema = Schema::builder() - .with_schema_id(0) - .with_fields(vec![ - NestedField::required(1, "id", Type::Primitive(PrimitiveType::Int)) - .into(), - NestedField::required( - 2, - "category", - Type::Primitive(PrimitiveType::String), - ) - .into(), - ]) - .build() - .unwrap(); - - let partition_spec = UnboundPartitionSpec::builder() - .with_spec_id(0) - .add_partition_field( - UnboundPartitionField::builder() - .source_ids(vec![2]) - .name("category") - .transform(Transform::Identity) - .build() - .unwrap(), - ) - .unwrap() - .build(); - - let mut properties = HashMap::new(); - if let Some(enabled) = fanout_enabled { - properties.insert( - TableProperties::PROPERTY_DATAFUSION_WRITE_FANOUT_ENABLED.to_string(), - enabled.to_string(), - ); - } - - let table_creation = TableCreation::builder() - .name("partitioned_table".to_string()) - .location(format!("{warehouse_path}/partitioned_table")) - .schema(schema) - .partition_spec(partition_spec) - .properties(properties) - .build(); - - catalog - .create_table(&namespace, table_creation) - .await - .unwrap(); - - ( - Arc::new(catalog), - namespace, - "partitioned_table".to_string(), - temp_dir, - ) - } - - /// Helper to check if a plan contains a SortExec node. - fn plan_contains_sort(plan: &Arc) -> bool { - if plan.name() == "SortExec" { - return true; - } - for child in plan.children() { - if plan_contains_sort(child) { - return true; - } - } - false - } } diff --git a/crates/datafusion/src/write/exec.rs b/crates/datafusion/src/write/exec.rs index 0beaaa9..5c9418e 100644 --- a/crates/datafusion/src/write/exec.rs +++ b/crates/datafusion/src/write/exec.rs @@ -28,7 +28,11 @@ use datafusion::common::{internal_err, not_impl_err, tree_node::TreeNodeRecursio use datafusion::error::DataFusionError; use datafusion::error::Result; use datafusion::execution::{SendableRecordBatchStream, TaskContext}; -use datafusion::physical_expr::{EquivalenceProperties, Partitioning, PhysicalExpr}; +use datafusion::physical_expr::expressions::col; +use datafusion::physical_expr::{ + EquivalenceProperties, LexOrdering, OrderingRequirements, Partitioning, PhysicalExpr, + PhysicalSortExpr, +}; use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType}; use datafusion::physical_plan::stream::RecordBatchStreamAdapter; use datafusion::physical_plan::{ @@ -36,7 +40,7 @@ use datafusion::physical_plan::{ execute_input_stream, }; use futures::StreamExt; -use iceberg::arrow::FieldMatchMode; +use iceberg::arrow::{FieldMatchMode, PROJECTED_PARTITION_VALUE_COLUMN}; use iceberg::spec::{ DataFile, DataFileFormat, FormatVersion, StructType, write_data_files_to_avro, }; @@ -175,6 +179,25 @@ impl ExecutionPlan for IcebergWriteExec { vec![false] } + /// Without fanout, a partitioned table is written by the clustered writer, which + /// needs each task's rows sorted by `_partition`. An invalid fanout property + /// declares no requirement; `execute` reports it. + fn required_input_ordering(&self) -> Vec> { + let metadata = self.table.metadata(); + let fanout = metadata + .table_properties() + .write_datafusion_fanout_enabled(); + let clustered = !metadata.default_partition_spec().is_unpartitioned() + && matches!(fanout, Ok(false)); + let ordering = match col(PROJECTED_PARTITION_VALUE_COLUMN, &self.input.schema()) { + Ok(partition) if clustered => { + Some(LexOrdering::from([PhysicalSortExpr::new_default(partition)]).into()) + } + _ => None, + }; + vec![ordering] + } + fn maintains_input_order(&self) -> Vec { // Maintains ordering in the sense that the written file will reflect the ordering of the input. vec![true; self.children().len()] diff --git a/crates/datafusion/src/write/mod.rs b/crates/datafusion/src/write/mod.rs index 7c57a16..be664ed 100644 --- a/crates/datafusion/src/write/mod.rs +++ b/crates/datafusion/src/write/mod.rs @@ -19,7 +19,6 @@ pub(crate) mod commit; pub(crate) mod exec; pub(crate) mod project; pub(crate) mod repartition; -pub(crate) mod sort; pub(crate) mod task_writer; pub use commit::IcebergCommitExec; diff --git a/crates/datafusion/src/write/sort.rs b/crates/datafusion/src/write/sort.rs deleted file mode 100644 index 1993e08..0000000 --- a/crates/datafusion/src/write/sort.rs +++ /dev/null @@ -1,247 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -//! Partition-based sorting for Iceberg tables. - -use std::sync::Arc; - -use datafusion::arrow::compute::SortOptions; -use datafusion::common::plan_datafusion_err; -use datafusion::error::Result; -use datafusion::physical_expr::{LexOrdering, PhysicalSortExpr}; -use datafusion::physical_plan::ExecutionPlan; -use datafusion::physical_plan::expressions::Column; -use datafusion::physical_plan::sorts::sort::SortExec; -use iceberg::arrow::PROJECTED_PARTITION_VALUE_COLUMN; - -/// Sorts an ExecutionPlan by partition values for Iceberg tables. -/// -/// This function takes an input ExecutionPlan that has been extended with partition values -/// (via `project_with_partition`) and returns a SortExec that sorts by the partition column. -/// The partition values are expected to be in a struct column named `PROJECTED_PARTITION_VALUE_COLUMN`. -/// -/// For unpartitioned tables or plans without the partition column, returns an error. -/// -/// # Arguments -/// * `input` - The input ExecutionPlan with projected partition values -/// -/// # Returns -/// * `Ok(Arc)` - A SortExec that sorts by partition values -/// * `Err` - If the partition column is not found -pub(crate) fn sort_by_partition( - input: Arc, -) -> Result> { - let schema = input.schema(); - - // Find the partition column in the schema - let (partition_column_index, _partition_field) = schema - .column_with_name(PROJECTED_PARTITION_VALUE_COLUMN) - .ok_or_else(|| plan_datafusion_err!( - "Partition column '{PROJECTED_PARTITION_VALUE_COLUMN}' not found in schema. Ensure the plan has been extended with partition values using project_with_partition." - ))?; - - // Create a single sort expression for the partition column - let column_expr = Arc::new(Column::new( - PROJECTED_PARTITION_VALUE_COLUMN, - partition_column_index, - )); - - let sort_expr = PhysicalSortExpr { - expr: column_expr, - options: SortOptions::default(), // Ascending, nulls last - }; - - // Create a SortExec with preserve_partitioning=true to ensure the output partitioning - // is the same as the input partitioning, and the data is sorted within each partition - let lex_ordering = LexOrdering::new(vec![sort_expr]).ok_or_else(|| { - plan_datafusion_err!("Failed to create LexOrdering from sort expression") - })?; - - let sort_exec = SortExec::new(lex_ordering, input).with_preserve_partitioning(true); - - Ok(Arc::new(sort_exec)) -} - -#[cfg(test)] -mod tests { - use datafusion::arrow::array::{Int32Array, RecordBatch, StringArray, StructArray}; - use datafusion::arrow::datatypes::{DataType, Field, Fields, Schema as ArrowSchema}; - use datafusion::datasource::{MemTable, TableProvider}; - use datafusion::prelude::SessionContext; - - use super::*; - - #[tokio::test] - async fn test_sort_by_partition_basic() { - // Create a schema with a partition column - let partition_fields = - Fields::from(vec![Field::new("id_partition", DataType::Int32, false)]); - - let schema = Arc::new(ArrowSchema::new(vec![ - Field::new("id", DataType::Int32, false), - Field::new("name", DataType::Utf8, false), - Field::new( - PROJECTED_PARTITION_VALUE_COLUMN, - DataType::Struct(partition_fields.clone()), - false, - ), - ])); - - // Create test data with partition values - let id_array = Arc::new(Int32Array::from(vec![3, 1, 2])); - let name_array = Arc::new(StringArray::from(vec!["c", "a", "b"])); - let partition_array = Arc::new(StructArray::from(vec![( - Arc::new(Field::new("id_partition", DataType::Int32, false)), - Arc::new(Int32Array::from(vec![3, 1, 2])) as _, - )])); - - let batch = RecordBatch::try_new( - schema.clone(), - vec![id_array, name_array, partition_array], - ) - .unwrap(); - - let ctx = SessionContext::new(); - let mem_table = MemTable::try_new(schema.clone(), vec![vec![batch]]).unwrap(); - let input = mem_table.scan(&ctx.state(), None, &[], None).await.unwrap(); - - // Apply sort - let sorted_plan = sort_by_partition(input).unwrap(); - - // Execute and verify - let result = datafusion::physical_plan::collect(sorted_plan, ctx.task_ctx()) - .await - .unwrap(); - - assert_eq!(result.len(), 1); - let result_batch = &result[0]; - - let id_col = result_batch - .column(0) - .as_any() - .downcast_ref::() - .unwrap(); - - // Verify data is sorted by partition value - assert_eq!(id_col.value(0), 1); - assert_eq!(id_col.value(1), 2); - assert_eq!(id_col.value(2), 3); - } - - #[tokio::test] - async fn test_sort_by_partition_missing_column() { - let schema = Arc::new(ArrowSchema::new(vec![ - Field::new("id", DataType::Int32, false), - Field::new("name", DataType::Utf8, false), - ])); - - let batch = RecordBatch::try_new( - schema.clone(), - vec![ - Arc::new(Int32Array::from(vec![1, 2, 3])), - Arc::new(StringArray::from(vec!["a", "b", "c"])), - ], - ) - .unwrap(); - - let ctx = SessionContext::new(); - let mem_table = MemTable::try_new(schema.clone(), vec![vec![batch]]).unwrap(); - let input = mem_table.scan(&ctx.state(), None, &[], None).await.unwrap(); - - let result = sort_by_partition(input); - assert!(result.is_err()); - assert!( - result - .unwrap_err() - .to_string() - .contains("Partition column '_partition' not found") - ); - } - - #[tokio::test] - async fn test_sort_by_partition_multi_field() { - // Test with multiple partition fields in the struct - let partition_fields = Fields::from(vec![ - Field::new("year", DataType::Int32, false), - Field::new("month", DataType::Int32, false), - ]); - - let schema = Arc::new(ArrowSchema::new(vec![ - Field::new("id", DataType::Int32, false), - Field::new("data", DataType::Utf8, false), - Field::new( - PROJECTED_PARTITION_VALUE_COLUMN, - DataType::Struct(partition_fields.clone()), - false, - ), - ])); - - // Create test data with partition values (year, month) - let id_array = Arc::new(Int32Array::from(vec![1, 2, 3, 4])); - let data_array = Arc::new(StringArray::from(vec!["a", "b", "c", "d"])); - - // Partition values: (2024, 2), (2024, 1), (2023, 12), (2024, 1) - let year_array = Arc::new(Int32Array::from(vec![2024, 2024, 2023, 2024])); - let month_array = Arc::new(Int32Array::from(vec![2, 1, 12, 1])); - - let partition_array = Arc::new(StructArray::from(vec![ - ( - Arc::new(Field::new("year", DataType::Int32, false)), - year_array as _, - ), - ( - Arc::new(Field::new("month", DataType::Int32, false)), - month_array as _, - ), - ])); - - let batch = RecordBatch::try_new( - schema.clone(), - vec![id_array, data_array, partition_array], - ) - .unwrap(); - - let ctx = SessionContext::new(); - let mem_table = MemTable::try_new(schema.clone(), vec![vec![batch]]).unwrap(); - let input = mem_table.scan(&ctx.state(), None, &[], None).await.unwrap(); - - // Apply sort - let sorted_plan = sort_by_partition(input).unwrap(); - - // Execute and verify - let result = datafusion::physical_plan::collect(sorted_plan, ctx.task_ctx()) - .await - .unwrap(); - - assert_eq!(result.len(), 1); - let result_batch = &result[0]; - - let id_col = result_batch - .column(0) - .as_any() - .downcast_ref::() - .unwrap(); - - // Verify data is sorted by partition value (struct comparison) - // Expected order: (2023, 12), (2024, 1), (2024, 1), (2024, 2) - // Which corresponds to ids: 3, 2, 4, 1 - assert_eq!(id_col.value(0), 3); - assert_eq!(id_col.value(1), 2); - assert_eq!(id_col.value(2), 4); - assert_eq!(id_col.value(3), 1); - } -} diff --git a/crates/datafusion/tests/insert_into.rs b/crates/datafusion/tests/insert_into.rs index 58ca01d..0eab93e 100644 --- a/crates/datafusion/tests/insert_into.rs +++ b/crates/datafusion/tests/insert_into.rs @@ -31,7 +31,7 @@ use iceberg::spec::{ Literal, NestedField, PrimitiveType, Schema, Struct, StructType, Transform, Type, }; use iceberg_datafusion::IcebergCatalogProvider; -use iceberg_datafusion_test_tools::{FixtureCatalog, display_schema}; +use iceberg_datafusion_test_tools::{FixtureCatalog, IcebergTestHarness, display_schema}; #[tokio::test] async fn test_insert_into() -> Result<(), Box> { @@ -489,3 +489,99 @@ async fn test_insert_into_partitioned() -> Result<(), Box> { Ok(()) } + +/// Inserts four rows into a new table `t (id, cat)` written without fanout, +/// partitioned by `transform` of `cat` if given, and returns the insert's plan and +/// the rows read back. +async fn insert_without_fanout( + transform: Option, +) -> Result<(String, String), Box> { + let fixtures = FixtureCatalog::try_new().await?; + let mut table = fixtures + .table( + TableIdent::from_strs(["default", "t"])?, + Schema::builder() + .with_fields(vec![ + NestedField::required(1, "id", Type::Primitive(PrimitiveType::Int)) + .into(), + NestedField::required(2, "cat", Type::Primitive(PrimitiveType::Int)) + .into(), + ]) + .build()?, + ) + .property("write.datafusion.fanout.enabled", "false"); + if let Some(transform) = transform { + table = table.partition_by("cat", transform); + } + table.create().await?; + let harness = IcebergTestHarness::builder() + .with_catalog( + "iceberg", + Arc::new(IcebergCatalogProvider::try_new(fixtures.catalog()).await?), + ) + .build() + .await?; + + let (plan, _) = harness + .query("INSERT INTO iceberg.default.t VALUES (1, 1), (2, 2), (3, 1), (4, 2)") + .await?; + let (_, rows) = harness + .query("SELECT * FROM iceberg.default.t ORDER BY id") + .await?; + Ok((plan, rows)) +} + +/// The clustered writer needs its input sorted by partition, so `IcebergWriteExec` +/// requires that order and the optimizer adds the sort. +#[tokio::test] +async fn sorts_partitioned_writes_by_partition_without_fanout() +-> Result<(), Box> { + let (plan, rows) = insert_without_fanout(Some(Transform::Identity)).await?; + + insta::assert_snapshot!(plan, @r#" + IcebergCommitExec: table=default.t, schema=[1: id: required int, 2: cat: required int] + IcebergWriteExec: table=default.t, result_schema=Schema { fields: [Field { name: "data_files", data_type: LargeBinary }], metadata: {} } + SortExec: expr=[_partition@2 ASC], preserve_partitioning=[false] + ProjectionExec: expr=[column1@0 as id, column2@1 as cat, iceberg_partition_values(cat) as _partition] + DataSourceExec: partitions=1, partition_sizes=[1] + "#); + insta::assert_snapshot!(rows, @r" + +----+-----+ + | id | cat | + +----+-----+ + | 1 | 1 | + | 2 | 2 | + | 3 | 1 | + | 4 | 2 | + +----+-----+ + "); + + Ok(()) +} + +/// An unpartitioned table has no partition column to sort by, so no sort is +/// required. +#[tokio::test] +async fn inserts_into_an_unpartitioned_table_without_fanout() -> Result<(), Box> +{ + let (plan, rows) = insert_without_fanout(None).await?; + + insta::assert_snapshot!(plan, @r#" + IcebergCommitExec: table=default.t, schema=[1: id: required int, 2: cat: required int] + IcebergWriteExec: table=default.t, result_schema=Schema { fields: [Field { name: "data_files", data_type: LargeBinary }], metadata: {} } + ProjectionExec: expr=[column1@0 as id, column2@1 as cat] + DataSourceExec: partitions=1, partition_sizes=[1] + "#); + insta::assert_snapshot!(rows, @r" + +----+-----+ + | id | cat | + +----+-----+ + | 1 | 1 | + | 2 | 2 | + | 3 | 1 | + | 4 | 2 | + +----+-----+ + "); + + Ok(()) +} From 9b3faa7ece0a57fa1521b8e06510983fc9b4b7f6 Mon Sep 17 00:00:00 2001 From: Noah Date: Sun, 22 Nov 2026 14:34:31 -0500 Subject: [PATCH 2/2] test: check that partitioned writes with fanout aren't sorted --- crates/datafusion/tests/insert_into.rs | 40 +++++++++++++++++++++----- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/crates/datafusion/tests/insert_into.rs b/crates/datafusion/tests/insert_into.rs index 0eab93e..fc04ddb 100644 --- a/crates/datafusion/tests/insert_into.rs +++ b/crates/datafusion/tests/insert_into.rs @@ -490,11 +490,12 @@ async fn test_insert_into_partitioned() -> Result<(), Box> { Ok(()) } -/// Inserts four rows into a new table `t (id, cat)` written without fanout, -/// partitioned by `transform` of `cat` if given, and returns the insert's plan and -/// the rows read back. -async fn insert_without_fanout( +/// Inserts four rows into a new table `t (id, cat)`, partitioned by `transform` of +/// `cat` if given and written with or without fanout, and returns the insert's +/// plan and the rows read back. +async fn insert( transform: Option, + fanout: bool, ) -> Result<(String, String), Box> { let fixtures = FixtureCatalog::try_new().await?; let mut table = fixtures @@ -509,7 +510,7 @@ async fn insert_without_fanout( ]) .build()?, ) - .property("write.datafusion.fanout.enabled", "false"); + .property("write.datafusion.fanout.enabled", fanout.to_string()); if let Some(transform) = transform { table = table.partition_by("cat", transform); } @@ -536,7 +537,7 @@ async fn insert_without_fanout( #[tokio::test] async fn sorts_partitioned_writes_by_partition_without_fanout() -> Result<(), Box> { - let (plan, rows) = insert_without_fanout(Some(Transform::Identity)).await?; + let (plan, rows) = insert(Some(Transform::Identity), false).await?; insta::assert_snapshot!(plan, @r#" IcebergCommitExec: table=default.t, schema=[1: id: required int, 2: cat: required int] @@ -559,12 +560,37 @@ async fn sorts_partitioned_writes_by_partition_without_fanout() Ok(()) } +/// The fanout writer accepts rows in any order, so no sort is required. +#[tokio::test] +async fn writes_partitioned_tables_unsorted_with_fanout() -> Result<(), Box> { + let (plan, rows) = insert(Some(Transform::Identity), true).await?; + + insta::assert_snapshot!(plan, @r#" + IcebergCommitExec: table=default.t, schema=[1: id: required int, 2: cat: required int] + IcebergWriteExec: table=default.t, result_schema=Schema { fields: [Field { name: "data_files", data_type: LargeBinary }], metadata: {} } + ProjectionExec: expr=[column1@0 as id, column2@1 as cat, iceberg_partition_values(cat) as _partition] + DataSourceExec: partitions=1, partition_sizes=[1] + "#); + insta::assert_snapshot!(rows, @r" + +----+-----+ + | id | cat | + +----+-----+ + | 1 | 1 | + | 2 | 2 | + | 3 | 1 | + | 4 | 2 | + +----+-----+ + "); + + Ok(()) +} + /// An unpartitioned table has no partition column to sort by, so no sort is /// required. #[tokio::test] async fn inserts_into_an_unpartitioned_table_without_fanout() -> Result<(), Box> { - let (plan, rows) = insert_without_fanout(None).await?; + let (plan, rows) = insert(None, false).await?; insta::assert_snapshot!(plan, @r#" IcebergCommitExec: table=default.t, schema=[1: id: required int, 2: cat: required int]