gabotechs commented on code in PR #157:
URL:
https://github.com/apache/datafusion-iceberg/pull/157#discussion_r4783008189
##########
crates/datafusion/src/write/commit.rs:
##########
@@ -146,757 +95,285 @@ impl DisplayAs for IcebergCommitExec {
.map(|field| field.to_string().trim_end().to_string())
.collect::<Vec<_>>()
.join(", ");
- write!(
- f,
- "IcebergCommitExec: table={}, schema=[{fields}]",
- self.table.identifier()
- )
- }
- DisplayFormatType::TreeRender => {
- write!(f, "IcebergCommitExec: table={}",
self.table.identifier())
+ write!(f, "IcebergCommitSink(table={table},
schema=[{fields}])")
}
}
}
}
-impl ExecutionPlan for IcebergCommitExec {
- fn name(&self) -> &str {
- "IcebergCommitExec"
- }
-
- fn properties(&self) -> &Arc<PlanProperties> {
- &self.plan_properties
- }
-
- fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
- vec![&self.input]
- }
-
- fn apply_expressions(
- &self,
- _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) ->
Result<TreeNodeRecursion>,
- ) -> Result<TreeNodeRecursion> {
- Ok(TreeNodeRecursion::Continue)
+#[async_trait]
+impl DataSink for IcebergCommitSink {
+ fn schema(&self) -> &ArrowSchemaRef {
+ &self.schema
}
- fn required_input_distribution(
+ async fn write_all(
&self,
- ) -> Vec<datafusion::physical_plan::Distribution> {
- vec![
- datafusion::physical_plan::Distribution::SinglePartition;
- self.children().len()
- ]
- }
-
- fn benefits_from_input_partitioning(&self) -> Vec<bool> {
- vec![false]
- }
-
- fn with_new_children(
- self: Arc<Self>,
- children: Vec<Arc<dyn ExecutionPlan>>,
- ) -> Result<Arc<dyn ExecutionPlan>> {
- if children.len() != 1 {
- return internal_err!(
- "IcebergCommitExec expects exactly one child, but provided {}",
- children.len()
- );
- }
-
- Ok(Arc::new(IcebergCommitExec::new(
- self.table.clone(),
- self.catalog.clone(),
- children[0].clone(),
- )))
- }
-
- fn execute(
- &self,
- partition: usize,
- context: Arc<TaskContext>,
- ) -> Result<SendableRecordBatchStream> {
- // IcebergCommitExec only has one partition (partition 0)
- if partition != 0 {
- return internal_err!(
- "IcebergCommitExec only has one partition, but got partition
{partition}"
- );
- }
-
- // Only partition 0 of the input is read below, so the files of any
- // other partition would silently go uncommitted.
- let input_partitions =
self.input.properties().partitioning.partition_count();
- if input_partitions != 1 {
- return exec_err!(
- "IcebergCommitExec requires an input with one partition, but
it has \
- {input_partitions}; coalesce the input first"
- );
- }
-
- let table = self.table.clone();
- let input_plan = self.input.clone();
-
- // todo revisit this
- let spec_id = self.table.metadata().default_partition_spec_id();
- let partition_type =
self.table.metadata().default_partition_type().clone();
- let current_schema = self.table.metadata().current_schema().clone();
- let format_version = self.table.metadata().format_version();
-
- let catalog = Arc::clone(&self.catalog);
-
- // Process the input streams from all partitions and commit the data
files
- let stream = futures::stream::once(async move {
- let mut data_files: Vec<DataFile> = Vec::new();
- let mut total_record_count: u64 = 0;
-
- // Execute and collect results from the input coalesced plan
- let mut batch_stream = input_plan.execute(0, context)?;
-
- while let Some(batch_result) = batch_stream.next().await {
- let batch = batch_result?;
-
- let files_array = batch
- .column_by_name(DATA_FILES_COL_NAME)
- .ok_or_else(|| {
- internal_datafusion_err!(
- "Expected 'data_files' column in input batch"
- )
- })?
- .as_any()
- .downcast_ref::<LargeBinaryArray>()
- .ok_or_else(|| {
- internal_datafusion_err!(
- "Expected 'data_files' column to be
LargeBinaryArray"
- )
- })?;
-
- // Each value is a separate Avro container with one or more
data files.
- files_array.iter().try_for_each(|payload| {
- let mut payload = payload.ok_or_else(|| {
- internal_datafusion_err!("Null Avro data file payload")
- })?;
- if payload.is_empty() {
- return internal_err!("Empty Avro data file payload");
- }
- let files = read_data_files_from_avro(
- &mut payload,
- ¤t_schema,
- spec_id,
- &partition_type,
- format_version,
+ mut data: SendableRecordBatchStream,
+ _context: &Arc<TaskContext>,
+ ) -> Result<u64> {
+ let metadata = self.table.metadata();
+ let spec_id = metadata.default_partition_spec_id();
+ let partition_type = metadata.default_partition_type();
+ let current_schema = metadata.current_schema();
+ let format_version = metadata.format_version();
+
+ let mut data_files: Vec<DataFile> = Vec::new();
+ let mut total_record_count: u64 = 0;
+ while let Some(batch) = data.next().await {
+ let batch = batch?;
+ let payloads = batch
+ .column_by_name(DATA_FILES_COL_NAME)
+ .and_then(|column| column.as_binary_opt::<i64>())
+ .ok_or_else(|| {
Review Comment:
In debug builds, this error is only reached when the input has exactly one
column.
Before `write_all` runs, `DataSinkExec` uses `execute_input_stream`, which
calls `debug_assert_eq!` on the sink's and the input's field counts, so any
other column count panics first. Validating the input schema when the plan is
built would give a proper error in both build modes.
1. Build `DataSinkExec::new(input_with_2_columns,
Arc::new(IcebergCommitSink::new(..)), None)`.
2. Call `execute(0)` in a debug build.
3. It panics on the assertion instead of returning this Execution error.
##########
crates/datafusion/src/write/commit.rs:
##########
@@ -146,757 +95,285 @@ impl DisplayAs for IcebergCommitExec {
.map(|field| field.to_string().trim_end().to_string())
.collect::<Vec<_>>()
.join(", ");
- write!(
- f,
- "IcebergCommitExec: table={}, schema=[{fields}]",
- self.table.identifier()
- )
- }
- DisplayFormatType::TreeRender => {
- write!(f, "IcebergCommitExec: table={}",
self.table.identifier())
+ write!(f, "IcebergCommitSink(table={table},
schema=[{fields}])")
}
}
}
}
-impl ExecutionPlan for IcebergCommitExec {
- fn name(&self) -> &str {
- "IcebergCommitExec"
- }
-
- fn properties(&self) -> &Arc<PlanProperties> {
- &self.plan_properties
- }
-
- fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
- vec![&self.input]
- }
-
- fn apply_expressions(
- &self,
- _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) ->
Result<TreeNodeRecursion>,
- ) -> Result<TreeNodeRecursion> {
- Ok(TreeNodeRecursion::Continue)
+#[async_trait]
+impl DataSink for IcebergCommitSink {
+ fn schema(&self) -> &ArrowSchemaRef {
+ &self.schema
}
- fn required_input_distribution(
+ async fn write_all(
Review Comment:
A multi-partition input now commits only partition 0 and silently drops the
rest.
`IcebergCommitExec::execute` used to reject an input with more than one
partition, but that check and `rejects_multiple_input_partitions` were removed.
`DataSinkExec::execute` doesn't replace it, since it only runs input partition
0. Could we keep an explicit error for this case, or at least keep a test that
pins the behavior?
1. Build `DataSinkExec::new(write_with_4_partitions,
Arc::new(IcebergCommitSink::new(..)), None)` without a `CoalescePartitionsExec`.
2. Call `execute(0)`.
3. Only partition 0's data files are committed; the other files are orphaned
and the count is too low, with no error.
##########
crates/datafusion/src/write/commit.rs:
##########
@@ -18,120 +18,69 @@
use std::fmt::{Debug, Formatter};
use std::sync::Arc;
-use datafusion::arrow::array::{
- Array, ArrayRef, LargeBinaryArray, RecordBatch, UInt64Array,
-};
-use datafusion::arrow::datatypes::{
- DataType, Field, Schema as ArrowSchema, SchemaRef as ArrowSchemaRef,
-};
-use datafusion::common::{
- exec_err, internal_datafusion_err, internal_err,
tree_node::TreeNodeRecursion,
-};
-use datafusion::error::{DataFusionError, Result};
+use async_trait::async_trait;
+use datafusion::arrow::array::AsArray;
+use datafusion::arrow::datatypes::SchemaRef as ArrowSchemaRef;
+use datafusion::common::{exec_datafusion_err, exec_err};
+use datafusion::datasource::sink::DataSink;
+use datafusion::error::Result;
use datafusion::execution::{SendableRecordBatchStream, TaskContext};
-use datafusion::physical_expr::{EquivalenceProperties, Partitioning,
PhysicalExpr};
-use datafusion::physical_plan::execution_plan::{Boundedness, EmissionType};
-use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
-use datafusion::physical_plan::{
- DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties,
-};
+use datafusion::physical_plan::{DisplayAs, DisplayFormatType};
use futures::StreamExt;
use iceberg::Catalog;
use iceberg::spec::{DataFile, read_data_files_from_avro};
use iceberg::table::Table;
use iceberg::transaction::{ApplyTransactionAction, Transaction};
+use super::IcebergWriteExec;
use super::exec::DATA_FILES_COL_NAME;
use crate::to_datafusion_error;
-/// IcebergCommitExec is responsible for collecting the files written and use
-/// [`Transaction::fast_append`] to commit the data files written.
+/// Commits the data files an [`IcebergWriteExec`] wrote, in one
+/// [`Transaction::fast_append`].
///
-/// Its input produces the data files to commit, in the form
-/// [`IcebergWriteExec`](super::IcebergWriteExec) outputs them, in a single
-/// partition. Its output is one row holding the number of rows committed.
+/// Run it in a [`DataSinkExec`] over the write. The `DataSinkExec` outputs one
+/// row holding the number of rows committed. It reads only partition 0 of its
+/// input, so the write must be coalesced to one partition with a
+/// [`CoalescePartitionsExec`]; the physical optimizer adds one when it is
Review Comment:
The optimizer only adds the `CoalescePartitionsExec` when the plan goes
through `EnforceDistribution`.
Callers that build, rebuild or deserialize the plan by hand (e.g.
distributed engines on workers) will read this as a guarantee and skip the
coalesce. I'd state the single-partition input as a hard requirement.
--
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]