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
5 changes: 3 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
192 changes: 2 additions & 190 deletions crates/datafusion/src/table_provider/catalog_table_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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.
///
Expand Down Expand Up @@ -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::<bool>().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));
Expand Down Expand Up @@ -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<dyn ExecutionPlan>;

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<dyn ExecutionPlan>;

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<bool>,
) -> (Arc<dyn Catalog>, 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<dyn ExecutionPlan>) -> bool {
if plan.name() == "SortExec" {
return true;
}
for child in plan.children() {
if plan_contains_sort(child) {
return true;
}
}
false
}
}
27 changes: 25 additions & 2 deletions crates/datafusion/src/write/exec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,19 @@ 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::{
DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties,
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,
};
Expand Down Expand Up @@ -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<Option<OrderingRequirements>> {
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<bool> {
// Maintains ordering in the sense that the written file will reflect the ordering of the input.
vec![true; self.children().len()]
Expand Down
1 change: 0 additions & 1 deletion crates/datafusion/src/write/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading