This is an automated email from the ASF dual-hosted git repository.

JingsongLi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/paimon-rust.git


The following commit(s) were added to refs/heads/main by this push:
     new 9485ba6d feat(datafusion): write append-only INSERT INTO with parallel 
writers (#1394)
9485ba6d is described below

commit 9485ba6df03a7105419b53445c66835311ddc516
Author: 龙骑士k <[email protected]>
AuthorDate: Mon Nov 16 13:46:02 2026 +0000

    feat(datafusion): write append-only INSERT INTO with parallel writers 
(#1394)
---
 .../datafusion/src/physical_plan/sink.rs           | 280 ++++++++++++++++-
 crates/integrations/datafusion/src/table/mod.rs    | 337 +++++++++++++++++++++
 docs/src/sql.md                                    |  20 ++
 3 files changed, 621 insertions(+), 16 deletions(-)

diff --git a/crates/integrations/datafusion/src/physical_plan/sink.rs 
b/crates/integrations/datafusion/src/physical_plan/sink.rs
index 437e52d9..76524da0 100644
--- a/crates/integrations/datafusion/src/physical_plan/sink.rs
+++ b/crates/integrations/datafusion/src/physical_plan/sink.rs
@@ -26,14 +26,18 @@ use datafusion::arrow::datatypes::{
     DataType as ArrowDataType, Schema, SchemaRef as ArrowSchemaRef,
 };
 use datafusion::arrow::record_batch::{RecordBatch, RecordBatchOptions};
+use datafusion::common::runtime::SpawnedTask;
 use datafusion::datasource::sink::DataSink;
-use datafusion::error::Result as DFResult;
+use datafusion::error::{DataFusionError, Result as DFResult};
 use datafusion::execution::SendableRecordBatchStream;
 use datafusion::execution::TaskContext;
 use datafusion::physical_plan::DisplayAs;
-use futures::StreamExt;
+use futures::channel::mpsc;
+use futures::future::try_join;
+use futures::stream::FuturesUnordered;
+use futures::{SinkExt, StreamExt, TryStreamExt};
 use paimon::spec::{CoreOptions, ROW_ID_FIELD_NAME};
-use paimon::table::Table;
+use paimon::table::{CommitMessage, Table, WriteBuilder};
 
 use crate::error::to_datafusion_error;
 
@@ -95,11 +99,19 @@ pub(crate) fn to_paimon_batch(
     RecordBatch::try_new_with_options(schema, columns, 
&options).map_err(Into::into)
 }
 
+/// Table option naming the number of concurrent writers, read from table
+/// options as Java's FlinkSinkBuilder does. Only bucket-unaware append-only
+/// `INSERT INTO` honors it.
+const SINK_PARALLELISM: &str = "sink.parallelism";
+
 /// DataSink that writes RecordBatches to a Paimon table.
 ///
 /// Uses the Paimon write pipeline: `WriteBuilder` → `TableWrite` → 
`TableCommit`.
-/// Internal parallelism is handled by `TableWrite` which routes each
-/// (partition, bucket) to its own background tokio task.
+/// A `TableWrite` keeps one file writer per (partition, bucket) and writes the
+/// groups of a batch in turn; only rolled files are closed in background 
tasks.
+/// Bucket-unaware append-only `INSERT INTO` may therefore spread input batches
+/// over `min(sink.parallelism, target_partitions)` `TableWrite`s; their
+/// messages form one commit.
 #[derive(Debug)]
 pub struct PaimonDataSink {
     table: Table,
@@ -119,6 +131,106 @@ impl PaimonDataSink {
             overwrite,
         }
     }
+
+    /// Number of `TableWrite`s for this statement, capped by the session's
+    /// `target_partitions`. The option is validated for every table. Any
+    /// writer may write any partition only for bucket-unaware append-only
+    /// tables, so other tables and overwrites keep the single writer.
+    fn writer_count(&self, target_partitions: usize) -> DFResult<usize> {
+        let options = self.table.schema().options();
+        let parallelism = match options.get(SINK_PARALLELISM) {
+            None => return Ok(1),
+            // Same accepted forms as Java Integer.parseInt.
+            Some(value) => match value.parse::<i32>() {
+                Ok(count) if count > 0 => count as usize,
+                // Flink's PARALLELISM_DEFAULT: Java FlinkSinkBuilder treats -1
+                // like an unset option, so it keeps one writer here as well.
+                Ok(-1) => return Ok(1),
+                _ => {
+                    return Err(DataFusionError::Configuration(format!(
+                        "'{SINK_PARALLELISM}' must be a positive integer or 
-1, got '{value}'"
+                    )))
+                }
+            },
+        };
+        let core_options = CoreOptions::new(options);
+        if self.overwrite
+            || core_options.is_format_table()
+            || !self.table.schema().primary_keys().is_empty()
+            || core_options.bucket() != -1
+        {
+            return Ok(1);
+        }
+        Ok(parallelism.min(target_partitions.max(1)))
+    }
+
+    /// Deal input batches round-robin to `writers` spawned `TableWrite`s and
+    /// gather their commit messages. The input and every writer are polled
+    /// together, so the first failure ends the statement and dropping the
+    /// rest cancels the input and the other writers.
+    async fn write_parallel(
+        &self,
+        wb: &WriteBuilder<'_>,
+        writers: usize,
+        mut data: SendableRecordBatchStream,
+    ) -> DFResult<(u64, Vec<CommitMessage>)> {
+        let mut senders = Vec::with_capacity(writers);
+        let mut tasks = Vec::with_capacity(writers);
+        for _ in 0..writers {
+            let mut tw = wb.new_write().map_err(to_datafusion_error)?;
+            // One queued batch per writer bounds buffered input.
+            let (sender, mut receiver) = mpsc::channel::<RecordBatch>(1);
+            senders.push(sender);
+            tasks.push(SpawnedTask::spawn(async move {
+                while let Some(batch) = receiver.next().await {
+                    tw.write_arrow_batch(&batch).await?;
+                }
+                tw.prepare_commit().await
+            }));
+        }
+
+        let strip_internal_row_id = self.strip_internal_row_id;
+        let dispatch = async move {
+            let mut row_count = 0u64;
+            let mut next = 0;
+            while let Some(batch) = data.next().await {
+                let batch = to_paimon_batch(batch?, strip_internal_row_id)?;
+                row_count += batch.num_rows() as u64;
+                if senders[next].send(batch).await.is_err() {
+                    // The writer stopped on an error, which its task reports.
+                    break;
+                }
+                next = (next + 1) % writers;
+            }
+            // Dropping the senders ends the writers' input.
+            Ok::<_, DataFusionError>(row_count)
+        };
+        // FuturesUnordered yields each writer as it finishes, so a failed
+        // writer is seen while earlier writers still run.
+        let mut finished = tasks
+            .into_iter()
+            .enumerate()
+            .map(|(index, task)| async move {
+                let messages = task
+                    .join_unwind()
+                    .await
+                    .map_err(|error| 
DataFusionError::ExecutionJoin(Box::new(error)))?
+                    .map_err(to_datafusion_error)?;
+                Ok::<_, DataFusionError>((index, messages))
+            })
+            .collect::<FuturesUnordered<_>>();
+        let joins = async move {
+            let mut per_writer = Vec::with_capacity(writers);
+            while let Some(done) = finished.try_next().await? {
+                per_writer.push(done);
+            }
+            // Keep the messages in writer order.
+            per_writer.sort_by_key(|(index, _)| *index);
+            Ok(per_writer.into_iter().flat_map(|(_, messages)| messages))
+        };
+        let (row_count, messages) = try_join(dispatch, joins).await?;
+        Ok((row_count, messages.collect()))
+    }
 }
 
 impl DisplayAs for PaimonDataSink {
@@ -149,18 +261,23 @@ impl DataSink for PaimonDataSink {
         };
         let resources = 
crate::memory::writer_resources(context).map_err(to_datafusion_error)?;
         let wb = wb.with_resources(resources);
-        let mut tw = wb.new_write().map_err(to_datafusion_error)?;
-        let mut row_count = 0u64;
-
-        while let Some(batch) = data.next().await {
-            let batch = to_paimon_batch(batch?, self.strip_internal_row_id)?;
-            row_count += batch.num_rows() as u64;
-            tw.write_arrow_batch(&batch)
-                .await
-                .map_err(to_datafusion_error)?;
-        }
+        let writers = 
self.writer_count(context.session_config().target_partitions())?;
+        let (row_count, messages) = if writers > 1 {
+            self.write_parallel(&wb, writers, data).await?
+        } else {
+            let mut tw = wb.new_write().map_err(to_datafusion_error)?;
+            let mut row_count = 0u64;
+            while let Some(batch) = data.next().await {
+                let batch = to_paimon_batch(batch?, 
self.strip_internal_row_id)?;
+                row_count += batch.num_rows() as u64;
+                tw.write_arrow_batch(&batch)
+                    .await
+                    .map_err(to_datafusion_error)?;
+            }
+            let messages = 
tw.prepare_commit().await.map_err(to_datafusion_error)?;
+            (row_count, messages)
+        };
 
-        let messages = tw.prepare_commit().await.map_err(to_datafusion_error)?;
         let commit = wb.try_new_commit().map_err(to_datafusion_error)?;
 
         if self.overwrite {
@@ -210,4 +327,135 @@ mod tests {
             &ArrowDataType::Utf8
         );
     }
+
+    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+    async fn test_parallel_writer_failure_ends_insert_while_input_pending() {
+        use std::time::Duration;
+
+        use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
+        use datafusion::prelude::SessionConfig;
+        use paimon::catalog::Identifier;
+        use paimon::io::FileIOBuilder;
+        use paimon::spec::{DataType, IntType, Schema as PaimonSchema, 
TableSchema};
+
+        // When a writer fails while the input waits for its next batch, the
+        // INSERT must return the writer's error instead of waiting for input
+        // that may never come.
+        let dir = tempfile::tempdir().unwrap();
+        // A regular file where the bucket directory belongs: opening the
+        // first data file fails with a real filesystem error.
+        std::fs::write(dir.path().join("bucket-0"), b"").unwrap();
+        let schema = PaimonSchema::builder()
+            .column("id", DataType::Int(IntType::new()))
+            .option(SINK_PARALLELISM, "2")
+            .build()
+            .unwrap();
+        let table = Table::new(
+            FileIOBuilder::new("file").build().unwrap(),
+            Identifier::new("default", "t"),
+            format!("file:{}", dir.path().display()),
+            TableSchema::new(0, &schema),
+            None,
+        );
+        let arrow_schema = Arc::new(Schema::new(vec![Field::new(
+            "id",
+            ArrowDataType::Int32,
+            true,
+        )]));
+        let batch = RecordBatch::try_new(
+            arrow_schema.clone(),
+            vec![Arc::new(Int32Array::from(vec![1]))],
+        )
+        .unwrap();
+        // One batch for the first writer, then the input stays pending like a
+        // slow source.
+        let input = 
futures::stream::iter([Ok(batch)]).chain(futures::stream::pending());
+        let data = 
Box::pin(RecordBatchStreamAdapter::new(arrow_schema.clone(), input));
+        let context = Arc::new(
+            TaskContext::default()
+                
.with_session_config(SessionConfig::new().with_target_partitions(2)),
+        );
+        let sink = PaimonDataSink::new(table, arrow_schema, false);
+
+        let result =
+            tokio::time::timeout(Duration::from_secs(10), sink.write_all(data, 
&context)).await;
+
+        let error = result
+            .expect("INSERT still waits for input after a writer failed")
+            .unwrap_err();
+        assert!(error.to_string().contains("bucket-0"), "{error}");
+    }
+
+    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+    async fn 
test_later_writer_failure_ends_insert_while_earlier_writer_waits() {
+        use std::time::Duration;
+
+        use datafusion::arrow::array::StringArray;
+        use datafusion::physical_plan::stream::RecordBatchStreamAdapter;
+        use datafusion::prelude::SessionConfig;
+        use paimon::catalog::Identifier;
+        use paimon::io::FileIOBuilder;
+        use paimon::spec::{DataType, IntType, Schema as PaimonSchema, 
TableSchema, VarCharType};
+
+        // The second writer fails while the first writer is still alive and
+        // waiting for more input. The INSERT must return the second writer's
+        // error; waiting on the writers in creation order would block on the
+        // first writer and never see it.
+        let dir = tempfile::tempdir().unwrap();
+        // A regular file where the bucket directory of partition p=bad
+        // belongs: only writes to that partition fail, with a real filesystem
+        // error.
+        std::fs::create_dir_all(dir.path().join("p=bad")).unwrap();
+        std::fs::write(dir.path().join("p=bad").join("bucket-0"), 
b"").unwrap();
+        let schema = PaimonSchema::builder()
+            .column("id", DataType::Int(IntType::new()))
+            .column("p", DataType::VarChar(VarCharType::string_type()))
+            .partition_keys(["p"])
+            .option(SINK_PARALLELISM, "2")
+            .build()
+            .unwrap();
+        let table = Table::new(
+            FileIOBuilder::new("file").build().unwrap(),
+            Identifier::new("default", "t"),
+            format!("file:{}", dir.path().display()),
+            TableSchema::new(0, &schema),
+            None,
+        );
+        let arrow_schema = Arc::new(Schema::new(vec![
+            Field::new("id", ArrowDataType::Int32, true),
+            Field::new("p", ArrowDataType::Utf8, true),
+        ]));
+        let batch = |id: i32, p: &str| {
+            RecordBatch::try_new(
+                arrow_schema.clone(),
+                vec![
+                    Arc::new(Int32Array::from(vec![id])),
+                    Arc::new(StringArray::from(vec![p])),
+                ],
+            )
+            .unwrap()
+        };
+        // Batches are dealt round-robin: the p=ok batch goes to the first
+        // writer, which buffers it and waits; the p=bad batch goes to the
+        // second writer, which fails. Then the input stays pending like a
+        // slow source.
+        let input = futures::stream::iter([Ok(batch(1, "ok")), Ok(batch(2, 
"bad"))])
+            .chain(futures::stream::pending());
+        let data = 
Box::pin(RecordBatchStreamAdapter::new(arrow_schema.clone(), input));
+        let context = Arc::new(
+            TaskContext::default()
+                
.with_session_config(SessionConfig::new().with_target_partitions(2)),
+        );
+        let sink = PaimonDataSink::new(table, arrow_schema, false);
+
+        let result =
+            tokio::time::timeout(Duration::from_secs(10), sink.write_all(data, 
&context)).await;
+
+        let error = result
+            .expect("INSERT still waits after the second writer failed")
+            .unwrap_err();
+        // The error comes from opening a data file under p=bad/bucket-0, so
+        // it names the failed partition.
+        assert!(error.to_string().contains("p=bad"), "{error}");
+    }
 }
diff --git a/crates/integrations/datafusion/src/table/mod.rs 
b/crates/integrations/datafusion/src/table/mod.rs
index 01115719..08784da7 100644
--- a/crates/integrations/datafusion/src/table/mod.rs
+++ b/crates/integrations/datafusion/src/table/mod.rs
@@ -1395,4 +1395,341 @@ mod tests {
         // Old data fully replaced
         assert_eq!(rows, vec![(4, 40), (5, 50)]);
     }
+
+    /// An INSERT of 8 in-memory batches with 2 rows each into a memory table
+    /// with columns `id`, `value` and `pt`.
+    struct EightBatchInsert<'a> {
+        name: &'a str,
+        options: &'a [(&'a str, &'a str)],
+        primary_keys: &'a [&'a str],
+        partition_keys: &'a [&'a str],
+        overwrite: bool,
+        target_partitions: usize,
+    }
+
+    /// Outcome of an [`EightBatchInsert`].
+    #[derive(Debug)]
+    struct InsertOutcome {
+        /// Row count reported by the INSERT.
+        count: u64,
+        latest_snapshot_id: Option<i64>,
+        /// Row counts of the committed data files, sorted.
+        file_rows: Vec<i64>,
+        /// `(id, value, pt)` read back, sorted.
+        rows: Vec<(i32, i32, i32)>,
+    }
+
+    impl EightBatchInsert<'_> {
+        fn new(name: &str) -> EightBatchInsert<'_> {
+            EightBatchInsert {
+                name,
+                options: &[],
+                primary_keys: &[],
+                partition_keys: &[],
+                overwrite: false,
+                // Fixed so that the writer cap does not depend on the host's 
cores.
+                target_partitions: 8,
+            }
+        }
+
+        /// The source is one in-memory partition; batch `i` holds ids `2i` and
+        /// `2i + 1`, with `value = id * 10` and `pt = id % 2`.
+        async fn run(&self) -> DFResult<InsertOutcome> {
+            use datafusion::arrow::array::{Int32Array, UInt64Array};
+            use datafusion::arrow::datatypes::{DataType as ArrowType, Field, 
Schema};
+            use datafusion::arrow::record_batch::RecordBatch;
+            use datafusion::datasource::MemTable;
+            use paimon::io::FileIOBuilder;
+            use paimon::spec::{DataType, IntType, Schema as PaimonSchema, 
TableSchema};
+
+            let file_io = FileIOBuilder::new("memory").build().unwrap();
+            let table_path = format!("memory:/{}", self.name);
+            for dir in ["snapshot", "manifest"] {
+                file_io
+                    .mkdirs(&format!("{table_path}/{dir}/"))
+                    .await
+                    .unwrap();
+            }
+            let mut builder = PaimonSchema::builder()
+                .column("id", DataType::Int(IntType::with_nullable(false)))
+                .column("value", DataType::Int(IntType::new()))
+                .column("pt", DataType::Int(IntType::with_nullable(false)))
+                .primary_key(self.primary_keys.iter().copied())
+                .partition_keys(self.partition_keys.iter().copied());
+            for (key, value) in self.options {
+                builder = builder.option(*key, *value);
+            }
+            let table = paimon::table::Table::new(
+                file_io,
+                Identifier::new("default", self.name),
+                table_path,
+                TableSchema::new(0, &builder.build().unwrap()),
+                None,
+            );
+
+            let schema = Arc::new(Schema::new(vec![
+                Field::new("id", ArrowType::Int32, false),
+                Field::new("value", ArrowType::Int32, true),
+                Field::new("pt", ArrowType::Int32, false),
+            ]));
+            let batches = (0..8)
+                .map(|i| {
+                    RecordBatch::try_new(
+                        schema.clone(),
+                        vec![
+                            Arc::new(Int32Array::from(vec![2 * i, 2 * i + 1])),
+                            Arc::new(Int32Array::from(vec![20 * i, 20 * i + 
10])),
+                            Arc::new(Int32Array::from(vec![0, 1])),
+                        ],
+                    )
+                    .unwrap()
+                })
+                .collect::<Vec<_>>();
+            let config = 
SessionConfig::new().with_target_partitions(self.target_partitions);
+            let ctx = SessionContext::new_with_config(config);
+            ctx.register_table("src", Arc::new(MemTable::try_new(schema, 
vec![batches])?))?;
+            ctx.register_table("t", 
Arc::new(PaimonTableProvider::try_new(table.clone())?))?;
+
+            let verb = if self.overwrite {
+                "INSERT OVERWRITE"
+            } else {
+                "INSERT INTO"
+            };
+            let result = ctx
+                .sql(&format!("{verb} t SELECT id, value, pt FROM src"))
+                .await?
+                .collect()
+                .await?;
+            let count = result[0]
+                .column(0)
+                .as_any()
+                .downcast_ref::<UInt64Array>()
+                .unwrap()
+                .value(0);
+
+            let latest_snapshot_id = table
+                .snapshot_manager()
+                .get_latest_snapshot_id()
+                .await
+                .unwrap();
+            let plan = 
table.new_read_builder().new_scan().plan().await.unwrap();
+            let mut file_rows = plan
+                .splits()
+                .iter()
+                .flat_map(|split| split.data_files().iter().map(|file| 
file.row_count))
+                .collect::<Vec<_>>();
+            file_rows.sort();
+
+            let mut rows = Vec::new();
+            for batch in ctx
+                .sql("SELECT id, value, pt FROM t")
+                .await?
+                .collect()
+                .await?
+            {
+                let column = |index: usize| {
+                    batch
+                        .column(index)
+                        .as_any()
+                        .downcast_ref::<Int32Array>()
+                        .unwrap()
+                        .clone()
+                };
+                let (ids, values, pts) = (column(0), column(1), column(2));
+                rows.extend(
+                    (0..batch.num_rows()).map(|i| (ids.value(i), 
values.value(i), pts.value(i))),
+                );
+            }
+            rows.sort();
+            Ok(InsertOutcome {
+                count,
+                latest_snapshot_id,
+                file_rows,
+                rows,
+            })
+        }
+    }
+
+    /// The 16 source rows of an [`EightBatchInsert`].
+    fn expected_rows() -> Vec<(i32, i32, i32)> {
+        (0..16).map(|id| (id, id * 10, id % 2)).collect()
+    }
+
+    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+    async fn test_insert_into_parallel_writers_commit_once() {
+        let outcome = EightBatchInsert {
+            options: &[("sink.parallelism", "4")],
+            ..EightBatchInsert::new("test_df_parallel_insert")
+        }
+        .run()
+        .await
+        .unwrap();
+
+        assert_eq!(outcome.count, 16);
+        assert_eq!(outcome.rows, expected_rows());
+        // All writers' messages go into one commit, so one snapshot.
+        assert_eq!(outcome.latest_snapshot_id, Some(1));
+        // 8 batches dealt round-robin to 4 writers: each writer receives
+        // 2 batches (4 rows) and closes one file. A single writer would
+        // leave one file of 16 rows.
+        assert_eq!(outcome.file_rows, vec![4, 4, 4, 4]);
+    }
+
+    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+    async fn test_insert_into_parallel_writers_on_partitioned_table() {
+        let outcome = EightBatchInsert {
+            options: &[("sink.parallelism", "4")],
+            partition_keys: &["pt"],
+            ..EightBatchInsert::new("test_df_parallel_partitioned_insert")
+        }
+        .run()
+        .await
+        .unwrap();
+
+        assert_eq!(outcome.count, 16);
+        assert_eq!(outcome.rows, expected_rows());
+        assert_eq!(outcome.latest_snapshot_id, Some(1));
+        // Every batch holds one row of each of the 2 partitions, so each of
+        // the 4 writers writes a 2-row file in both partitions: 4 x 2 files.
+        assert_eq!(outcome.file_rows, vec![2; 4 * 2]);
+    }
+
+    #[tokio::test]
+    async fn test_insert_into_caps_writers_at_target_partitions() {
+        let outcome = EightBatchInsert {
+            options: &[("sink.parallelism", "4")],
+            target_partitions: 2,
+            ..EightBatchInsert::new("test_df_capped_parallel_insert")
+        }
+        .run()
+        .await
+        .unwrap();
+
+        assert_eq!(outcome.rows, expected_rows());
+        // min(4, 2) writers, each receiving 4 batches (8 rows).
+        assert_eq!(outcome.file_rows, vec![8, 8]);
+    }
+
+    #[tokio::test]
+    async fn test_insert_into_without_sink_parallelism_uses_one_writer() {
+        let outcome = EightBatchInsert::new("test_df_default_insert")
+            .run()
+            .await
+            .unwrap();
+
+        assert_eq!(outcome.count, 16);
+        assert_eq!(outcome.rows, expected_rows());
+        assert_eq!(outcome.latest_snapshot_id, Some(1));
+        assert_eq!(outcome.file_rows, vec![16]);
+    }
+
+    #[tokio::test]
+    async fn 
test_sink_parallelism_keeps_single_writer_outside_unaware_append_insert() {
+        let parallel: &[(&str, &str)] = &[("sink.parallelism", "4")];
+        let fixed_bucket: &[(&str, &str)] = &[
+            ("bucket", "1"),
+            ("bucket-key", "id"),
+            ("sink.parallelism", "4"),
+        ];
+        let cases = [
+            // A fixed bucket is owned by one writer.
+            EightBatchInsert {
+                options: fixed_bucket,
+                ..EightBatchInsert::new("test_df_single_writer_fixed_bucket")
+            },
+            // A primary-key table with the default dynamic bucket (-1).
+            EightBatchInsert {
+                options: parallel,
+                primary_keys: &["id"],
+                ..EightBatchInsert::new("test_df_single_writer_primary_key")
+            },
+            // INSERT OVERWRITE into a bucket-unaware append-only table.
+            EightBatchInsert {
+                options: parallel,
+                overwrite: true,
+                ..EightBatchInsert::new("test_df_single_writer_overwrite")
+            },
+        ];
+        for case in cases {
+            let outcome = case.run().await.unwrap();
+            assert_eq!(outcome.count, 16, "{}", case.name);
+            assert_eq!(outcome.rows, expected_rows(), "{}", case.name);
+            assert_eq!(outcome.latest_snapshot_id, Some(1), "{}", case.name);
+            // One writer leaves one file with all 16 rows; 4 writers would
+            // leave 4 files.
+            assert_eq!(outcome.file_rows, vec![16], "{}", case.name);
+        }
+    }
+
+    #[tokio::test]
+    async fn test_sink_parallelism_minus_one_keeps_single_writer() {
+        // -1 is Flink's PARALLELISM_DEFAULT, and Java FlinkSinkBuilder treats
+        // null or -1 as an unset sink parallelism. A table configured that
+        // way for Flink stays writable and keeps the single writer, as
+        // without the option.
+        let minus_one: &[(&str, &str)] = &[("sink.parallelism", "-1")];
+        let fixed_bucket: &[(&str, &str)] = &[
+            ("bucket", "1"),
+            ("bucket-key", "id"),
+            ("sink.parallelism", "-1"),
+        ];
+        let cases = [
+            EightBatchInsert {
+                options: minus_one,
+                ..EightBatchInsert::new("test_df_minus_one_append")
+            },
+            EightBatchInsert {
+                options: fixed_bucket,
+                ..EightBatchInsert::new("test_df_minus_one_fixed_bucket")
+            },
+            EightBatchInsert {
+                options: minus_one,
+                primary_keys: &["id"],
+                ..EightBatchInsert::new("test_df_minus_one_primary_key")
+            },
+            EightBatchInsert {
+                options: minus_one,
+                overwrite: true,
+                ..EightBatchInsert::new("test_df_minus_one_overwrite")
+            },
+        ];
+        for case in cases {
+            let outcome = case.run().await.unwrap();
+            assert_eq!(outcome.count, 16, "{}", case.name);
+            assert_eq!(outcome.rows, expected_rows(), "{}", case.name);
+            assert_eq!(outcome.latest_snapshot_id, Some(1), "{}", case.name);
+            assert_eq!(outcome.file_rows, vec![16], "{}", case.name);
+        }
+    }
+
+    #[tokio::test]
+    async fn test_insert_into_rejects_invalid_sink_parallelism() {
+        // Java Integer.parseInt rejects " 4", and Flink accepts only a
+        // positive parallelism or -1 (OperatorValidationUtils). The option is
+        // checked before deciding whether it applies, so a primary-key table
+        // fails too.
+        let cases: [(&str, &str, &[&str]); 4] = [
+            ("test_df_invalid_parallelism_zero", "0", &[]),
+            ("test_df_invalid_parallelism_negative", "-2", &[]),
+            ("test_df_invalid_parallelism_space", " 4", &[]),
+            ("test_df_invalid_parallelism_primary_key", "0", &["id"]),
+        ];
+        for (name, value, primary_keys) in cases {
+            let error = EightBatchInsert {
+                options: &[("sink.parallelism", value)],
+                primary_keys,
+                ..EightBatchInsert::new(name)
+            }
+            .run()
+            .await
+            .unwrap_err();
+
+            assert!(
+                error
+                    .to_string()
+                    .contains("'sink.parallelism' must be a positive integer 
or -1"),
+                "{name}: {error}"
+            );
+        }
+    }
 }
diff --git a/docs/src/sql.md b/docs/src/sql.md
index 9191f64c..8ae7c4aa 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -935,6 +935,26 @@ INSERT INTO paimon.my_db.users VALUES (1, 'alice'), (2, 
'bob'), (3, 'carol');
 INSERT INTO paimon.my_db.users SELECT * FROM source_table;
 ```
 
+An `INSERT INTO` an append-only table with `'bucket' = '-1'` (the default) can
+encode data files with several writers. The writer count is the table option
+`sink.parallelism`, capped at `datafusion.execution.target_partitions`; the 
sink
+deals input batches to the writers round-robin, and their files are committed
+together as one snapshot. Without the option, or with `-1` (Flink's default
+parallelism), one writer is used. Primary-key tables, fixed-bucket tables and
+`INSERT OVERWRITE` always use one writer, but the option must still be a
+positive integer or `-1`.
+
+Each writer rolls its own files in every partition it receives rows for, so on
+a partitioned table the file count grows to writers × partitions where one
+writer leaves one file per partition.
+`sink.parallelism` is the same option Flink reads for its sink, so a table that
+already sets it for Flink jobs also writes in parallel from DataFusion, with at
+most `target_partitions` writers whatever the Flink value is.
+
+```sql
+ALTER TABLE paimon.my_db.events SET TBLPROPERTIES ('sink.parallelism' = '4');
+```
+
 For `VARIANT` columns, convert JSON text with `parse_json` or `try_parse_json`:
 
 ```sql

Reply via email to