You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hudi.apache.org by "morningstarxcdcode (via GitHub)" <gi...@apache.org> on 2026/05/01 15:01:32 UTC

[PR] feat(core): add bulk insert for append-only tables [hudi-rs]

morningstarxcdcode opened a new pull request, #588:
URL: https://github.com/apache/hudi-rs/pull/588

   ## Description\n\nAdd bulk insert support for append-only tables in . The writer now creates a Parquet base file, writes commit metadata, and rejects partitioned tables until partition-aware writes are implemented.\n\nFixes #565.\n\n## How are the changes test-covered\n\n- [ ] N/A\n- [x] Automated tests (unit and/or integration tests)\n- [ ] Manual tests\n  - [x] Details are described below\n\nValidated with:\n- 
   running 2 tests
   test bulk_insert_rejects_partitioned_tables ... ok
   test bulk_insert_writes_records_and_commit ... ok
   
   test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.03s\n\nThe test suite covers the happy path and the partitioned-table rejection path.


-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(core): add bulk insert for append-only tables [hudi-rs]

Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #588:
URL: https://github.com/apache/hudi-rs/pull/588#discussion_r3173746677


##########
crates/core/src/table/writer.rs:
##########
@@ -0,0 +1,280 @@
+/*
+ * 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.
+ */
+
+use std::collections::HashMap;
+use std::io::Cursor;
+use std::str::FromStr;
+use std::sync::atomic::{AtomicI64, Ordering};
+
+use apache_avro::schema::AvroSchema;
+use apache_avro::Writer as AvroWriter;
+use arrow::record_batch::RecordBatch;
+use bytes::Bytes;
+use chrono::Utc;
+use object_store::PutPayload;
+use object_store::path::Path;
+use parquet::arrow::ArrowWriter;
+
+use crate::Result;
+use crate::config::table::HudiTableConfig::{RecordMergeStrategy, TableVersion, TimelineLayoutVersion, TimelinePath};
+use crate::error::CoreError;
+use crate::metadata::HUDI_METADATA_DIR;
+use crate::metadata::commit::{HoodieCommitMetadata, HoodieWriteStat};
+use crate::merge::RecordMergeStrategyValue;
+use crate::storage::error::StorageError;
+use crate::storage::util::join_url_segments;
+use crate::table::Table;
+use crate::timeline::instant::Instant;
+
+/// Result of a bulk insert write.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct BulkInsertResult {
+    pub instant: String,
+    pub base_file_path: String,
+    pub num_rows: usize,
+}
+
+/// Minimal bulk insert writer for append-only tables.
+#[derive(Clone, Debug)]
+pub struct BulkInsertWriter {
+    table: Table,
+}
+
+static LAST_EPOCH_MILLIS: AtomicI64 = AtomicI64::new(0);
+
+impl BulkInsertWriter {
+    pub fn new(table: &Table) -> Self {
+        Self { table: table.clone() }
+    }
+
+    pub async fn write(&self, batch: RecordBatch) -> Result<BulkInsertResult> {
+        self.ensure_append_only()?;
+        self.ensure_unpartitioned()?;
+
+        let request_instant = Self::current_timestamp();
+        let completion_instant = request_instant.clone();
+        let layout_two = self.is_layout_two();
+        let instant_name = if layout_two {
+            format!("{request_instant}_{completion_instant}.commit")
+        } else {
+            format!("{request_instant}.commit")
+        };
+        let instant = Instant::from_str(&instant_name)?;
+        let timeline_dir = self.timeline_dir();
+
+        let file_id = format!("bulk-insert-{request_instant}");
+        let write_token = "0-0-0";
+        let base_file_name = format!("{file_id}_{write_token}_{request_instant}.parquet");
+        let base_file_path = base_file_name.clone();
+
+        let file_bytes = self.write_parquet_bytes(&batch)?;
+        let file_size = file_bytes.len() as i64;
+
+        self.put_file(&base_file_path, file_bytes).await?;
+
+        let commit_metadata = self.build_commit_metadata(
+            &file_id,
+            &base_file_path,
+            batch.num_rows() as i64,
+            file_size,
+        );
+        if let Err(error) = self
+            .write_commit_file(&instant, &timeline_dir, &commit_metadata)
+            .await
+        {
+            let _ = self.delete_file(&base_file_path).await;
+            return Err(error);
+        }
+
+        Ok(BulkInsertResult {
+            instant: request_instant,
+            base_file_path,
+            num_rows: batch.num_rows(),
+        })

Review Comment:
   BulkInsertResult.instant` is set to `request_instant`, but for timeline layout v2 the commit file name is `{request}_{completion}.commit`. Returning only `request_instant` makes it impossible for callers to reliably locate the written commit file under layout v2. Consider returning the actual instant identifier used for persistence (e.g., the full `instant_name` or a separate `commit_file_name`/`commit_relative_path` field), or change `instant` to represent the timeline file-stem consistently across layouts.



##########
crates/core/src/table/writer.rs:
##########
@@ -0,0 +1,280 @@
+/*
+ * 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.
+ */
+
+use std::collections::HashMap;
+use std::io::Cursor;
+use std::str::FromStr;
+use std::sync::atomic::{AtomicI64, Ordering};
+
+use apache_avro::schema::AvroSchema;

Review Comment:
   This import appears unused in this file. Removing it avoids warnings and potential CI failures in crates that compile with warnings-as-errors.



##########
crates/core/src/table/writer.rs:
##########
@@ -0,0 +1,280 @@
+/*
+ * 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.
+ */
+
+use std::collections::HashMap;
+use std::io::Cursor;
+use std::str::FromStr;
+use std::sync::atomic::{AtomicI64, Ordering};
+
+use apache_avro::schema::AvroSchema;
+use apache_avro::Writer as AvroWriter;
+use arrow::record_batch::RecordBatch;
+use bytes::Bytes;
+use chrono::Utc;
+use object_store::PutPayload;
+use object_store::path::Path;
+use parquet::arrow::ArrowWriter;
+
+use crate::Result;
+use crate::config::table::HudiTableConfig::{RecordMergeStrategy, TableVersion, TimelineLayoutVersion, TimelinePath};
+use crate::error::CoreError;
+use crate::metadata::HUDI_METADATA_DIR;
+use crate::metadata::commit::{HoodieCommitMetadata, HoodieWriteStat};
+use crate::merge::RecordMergeStrategyValue;
+use crate::storage::error::StorageError;
+use crate::storage::util::join_url_segments;
+use crate::table::Table;
+use crate::timeline::instant::Instant;
+
+/// Result of a bulk insert write.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct BulkInsertResult {
+    pub instant: String,
+    pub base_file_path: String,
+    pub num_rows: usize,
+}
+
+/// Minimal bulk insert writer for append-only tables.
+#[derive(Clone, Debug)]
+pub struct BulkInsertWriter {
+    table: Table,
+}
+
+static LAST_EPOCH_MILLIS: AtomicI64 = AtomicI64::new(0);
+
+impl BulkInsertWriter {
+    pub fn new(table: &Table) -> Self {
+        Self { table: table.clone() }
+    }
+
+    pub async fn write(&self, batch: RecordBatch) -> Result<BulkInsertResult> {
+        self.ensure_append_only()?;
+        self.ensure_unpartitioned()?;
+
+        let request_instant = Self::current_timestamp();
+        let completion_instant = request_instant.clone();
+        let layout_two = self.is_layout_two();
+        let instant_name = if layout_two {
+            format!("{request_instant}_{completion_instant}.commit")
+        } else {
+            format!("{request_instant}.commit")
+        };
+        let instant = Instant::from_str(&instant_name)?;
+        let timeline_dir = self.timeline_dir();

Review Comment:
   BulkInsertResult.instant` is set to `request_instant`, but for timeline layout v2 the commit file name is `{request}_{completion}.commit`. Returning only `request_instant` makes it impossible for callers to reliably locate the written commit file under layout v2. Consider returning the actual instant identifier used for persistence (e.g., the full `instant_name` or a separate `commit_file_name`/`commit_relative_path` field), or change `instant` to represent the timeline file-stem consistently across layouts.



##########
crates/core/tests/table_bulk_insert_tests.rs:
##########
@@ -0,0 +1,123 @@
+use std::sync::Arc;
+use std::fs;
+
+use arrow::array::{Int32Array, StringArray};
+use arrow::compute::concat_batches;
+use arrow::record_batch::RecordBatch;
+use arrow_schema::{DataType, Field, Schema};
+use hudi_core::error::Result;
+use hudi_core::table::Table;
+use tempfile::tempdir;
+use url::Url;
+
+fn write_table_properties(base_dir: &std::path::Path) -> Result<()> {
+    let hoodie_dir = base_dir.join(".hoodie");
+    fs::create_dir_all(&hoodie_dir)?;
+
+    let properties = [
+        "hoodie.table.name=test_table",
+        "hoodie.table.type=COPY_ON_WRITE",
+        "hoodie.table.version=6",
+        "hoodie.timeline.layout.version=1",
+        "hoodie.populate.meta.fields=false",
+        "hoodie.base.file.format=parquet",
+    ]
+    .join("\n");
+
+    fs::write(hoodie_dir.join("hoodie.properties"), properties)?;
+    Ok(())
+}
+
+fn write_partitioned_table_properties(base_dir: &std::path::Path) -> Result<()> {
+    let hoodie_dir = base_dir.join(".hoodie");
+    fs::create_dir_all(&hoodie_dir)?;
+
+    let properties = [
+        "hoodie.table.name=test_table",
+        "hoodie.table.type=COPY_ON_WRITE",
+        "hoodie.table.version=6",
+        "hoodie.timeline.layout.version=1",
+        "hoodie.populate.meta.fields=false",
+        "hoodie.base.file.format=parquet",
+        "hoodie.table.partition.fields=region",
+    ]
+    .join("\n");
+
+    fs::write(hoodie_dir.join("hoodie.properties"), properties)?;
+    Ok(())
+}
+
+#[tokio::test]
+async fn bulk_insert_writes_records_and_commit() -> Result<()> {
+    let temp_dir = tempdir()?;
+    write_table_properties(temp_dir.path())?;
+
+    let base_url = Url::from_file_path(temp_dir.path()).unwrap();
+    let table = Table::new(base_url.path()).await?;
+
+    let schema = Schema::new(vec![
+        Field::new("id", DataType::Int32, false),
+        Field::new("name", DataType::Utf8, false),
+    ]);
+
+    let batch = RecordBatch::try_new(
+        schema.into(),
+        vec![
+            Arc::new(Int32Array::from(vec![1, 2, 3])),
+            Arc::new(StringArray::from(vec!["alice", "bob", "carol"])),
+        ],
+    )?;
+
+    let result = table.bulk_insert(batch).await?;
+    assert_eq!(result.num_rows, 3);
+
+    let reopened = Table::new(base_url.path()).await?;
+    let records = reopened.read_snapshot(std::iter::empty::<(&str, &str, &str)>()).await?;
+    assert_eq!(records.len(), 1);
+
+    let read_batch = concat_batches(&records[0].schema(), &records)?;
+    assert_eq!(read_batch.num_rows(), 3);
+
+    let ids = read_batch
+        .column_by_name("id")
+        .and_then(|array| array.as_any().downcast_ref::<Int32Array>())
+        .expect("expected id column");
+    let names = read_batch
+        .column_by_name("name")
+        .and_then(|array| array.as_any().downcast_ref::<StringArray>())
+        .expect("expected name column");
+
+    assert_eq!(ids.values(), &[1, 2, 3]);
+    assert_eq!(names.value(0), "alice");
+    assert_eq!(names.value(1), "bob");
+    assert_eq!(names.value(2), "carol");
+
+    let commit_file = temp_dir
+        .path()
+        .join(".hoodie")
+        .join(format!("{}.commit", result.instant));
+    assert!(commit_file.exists(), "commit file should exist");
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn bulk_insert_rejects_partitioned_tables() -> Result<()> {
+    let temp_dir = tempdir()?;
+    write_partitioned_table_properties(temp_dir.path())?;
+
+    let base_url = Url::from_file_path(temp_dir.path()).unwrap();
+    let table = Table::new(base_url.path()).await?;
+
+    let schema = Schema::new(vec![Field::new("id", DataType::Int32, false)]);
+    let batch = RecordBatch::try_new(schema.into(), vec![Arc::new(Int32Array::from(vec![1]))])?;
+
+    let error = table.bulk_insert(batch).await.unwrap_err();
+    assert!(
+        error
+            .to_string()
+            .contains("Bulk insert currently supports only unpartitioned append-only tables")
+    );

Review Comment:
   Asserting on a substring of `error.to_string()` is brittle and can lead to flaky tests when error formatting changes (even if semantics don’t). If the error type is a concrete enum (e.g., `CoreError::Unsupported`), prefer matching on the variant and then asserting on the message/value, or expose a stable error code/kind to assert against.



##########
crates/core/src/table/writer.rs:
##########
@@ -0,0 +1,280 @@
+/*
+ * 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.
+ */
+
+use std::collections::HashMap;
+use std::io::Cursor;
+use std::str::FromStr;
+use std::sync::atomic::{AtomicI64, Ordering};
+
+use apache_avro::schema::AvroSchema;
+use apache_avro::Writer as AvroWriter;
+use arrow::record_batch::RecordBatch;
+use bytes::Bytes;
+use chrono::Utc;
+use object_store::PutPayload;
+use object_store::path::Path;
+use parquet::arrow::ArrowWriter;
+
+use crate::Result;
+use crate::config::table::HudiTableConfig::{RecordMergeStrategy, TableVersion, TimelineLayoutVersion, TimelinePath};
+use crate::error::CoreError;
+use crate::metadata::HUDI_METADATA_DIR;
+use crate::metadata::commit::{HoodieCommitMetadata, HoodieWriteStat};
+use crate::merge::RecordMergeStrategyValue;
+use crate::storage::error::StorageError;
+use crate::storage::util::join_url_segments;
+use crate::table::Table;
+use crate::timeline::instant::Instant;
+
+/// Result of a bulk insert write.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct BulkInsertResult {
+    pub instant: String,
+    pub base_file_path: String,
+    pub num_rows: usize,
+}
+
+/// Minimal bulk insert writer for append-only tables.
+#[derive(Clone, Debug)]
+pub struct BulkInsertWriter {
+    table: Table,
+}
+
+static LAST_EPOCH_MILLIS: AtomicI64 = AtomicI64::new(0);
+
+impl BulkInsertWriter {
+    pub fn new(table: &Table) -> Self {
+        Self { table: table.clone() }
+    }
+
+    pub async fn write(&self, batch: RecordBatch) -> Result<BulkInsertResult> {
+        self.ensure_append_only()?;
+        self.ensure_unpartitioned()?;
+
+        let request_instant = Self::current_timestamp();
+        let completion_instant = request_instant.clone();
+        let layout_two = self.is_layout_two();
+        let instant_name = if layout_two {
+            format!("{request_instant}_{completion_instant}.commit")
+        } else {
+            format!("{request_instant}.commit")
+        };
+        let instant = Instant::from_str(&instant_name)?;
+        let timeline_dir = self.timeline_dir();
+
+        let file_id = format!("bulk-insert-{request_instant}");
+        let write_token = "0-0-0";
+        let base_file_name = format!("{file_id}_{write_token}_{request_instant}.parquet");
+        let base_file_path = base_file_name.clone();
+
+        let file_bytes = self.write_parquet_bytes(&batch)?;
+        let file_size = file_bytes.len() as i64;
+
+        self.put_file(&base_file_path, file_bytes).await?;
+
+        let commit_metadata = self.build_commit_metadata(
+            &file_id,
+            &base_file_path,
+            batch.num_rows() as i64,
+            file_size,
+        );
+        if let Err(error) = self
+            .write_commit_file(&instant, &timeline_dir, &commit_metadata)
+            .await
+        {
+            let _ = self.delete_file(&base_file_path).await;
+            return Err(error);
+        }
+
+        Ok(BulkInsertResult {
+            instant: request_instant,
+            base_file_path,
+            num_rows: batch.num_rows(),
+        })
+    }
+
+    fn ensure_append_only(&self) -> Result<()> {
+        let strategy: String = self
+            .table
+            .hudi_configs
+            .get_or_default(RecordMergeStrategy)
+            .into();
+
+        if RecordMergeStrategyValue::from_str(&strategy)? != RecordMergeStrategyValue::AppendOnly {
+            return Err(CoreError::Unsupported(format!(
+                "Bulk insert is only supported for append-only tables. Found merge strategy '{strategy}'"
+            )));
+        }
+
+        Ok(())
+    }
+
+    fn ensure_unpartitioned(&self) -> Result<()> {
+        let partition_fields: Vec<String> = self
+            .table
+            .hudi_configs
+            .get_or_default(crate::config::table::HudiTableConfig::PartitionFields)
+            .into();
+
+        if !partition_fields.is_empty() {
+            return Err(CoreError::Unsupported(
+                "Bulk insert currently supports only unpartitioned append-only tables".to_string(),
+            ));
+        }
+
+        Ok(())
+    }
+
+    fn is_layout_two(&self) -> bool {
+        let table_version: isize = self.table.hudi_configs.get_or_default(TableVersion).into();
+        let layout_version: isize = self
+            .table
+            .hudi_configs
+            .get_or_default(TimelineLayoutVersion)
+            .into();
+        table_version >= 8 && layout_version == 2
+    }

Review Comment:
   The layout v2 commit-writing branch (layout detection + Avro serialization) is newly introduced but not exercised by the added tests. Adding a test case with `hoodie.table.version >= 8` and `hoodie.timeline.layout.version = 2` would cover both the v2 filename format and Avro commit metadata path.



##########
crates/core/tests/table_bulk_insert_tests.rs:
##########
@@ -0,0 +1,123 @@
+use std::sync::Arc;
+use std::fs;
+
+use arrow::array::{Int32Array, StringArray};
+use arrow::compute::concat_batches;
+use arrow::record_batch::RecordBatch;
+use arrow_schema::{DataType, Field, Schema};
+use hudi_core::error::Result;
+use hudi_core::table::Table;
+use tempfile::tempdir;
+use url::Url;
+
+fn write_table_properties(base_dir: &std::path::Path) -> Result<()> {
+    let hoodie_dir = base_dir.join(".hoodie");
+    fs::create_dir_all(&hoodie_dir)?;
+
+    let properties = [
+        "hoodie.table.name=test_table",
+        "hoodie.table.type=COPY_ON_WRITE",
+        "hoodie.table.version=6",
+        "hoodie.timeline.layout.version=1",
+        "hoodie.populate.meta.fields=false",
+        "hoodie.base.file.format=parquet",
+    ]
+    .join("\n");
+
+    fs::write(hoodie_dir.join("hoodie.properties"), properties)?;
+    Ok(())
+}
+
+fn write_partitioned_table_properties(base_dir: &std::path::Path) -> Result<()> {
+    let hoodie_dir = base_dir.join(".hoodie");
+    fs::create_dir_all(&hoodie_dir)?;
+
+    let properties = [
+        "hoodie.table.name=test_table",
+        "hoodie.table.type=COPY_ON_WRITE",
+        "hoodie.table.version=6",
+        "hoodie.timeline.layout.version=1",
+        "hoodie.populate.meta.fields=false",
+        "hoodie.base.file.format=parquet",
+        "hoodie.table.partition.fields=region",
+    ]
+    .join("\n");
+
+    fs::write(hoodie_dir.join("hoodie.properties"), properties)?;
+    Ok(())
+}
+
+#[tokio::test]
+async fn bulk_insert_writes_records_and_commit() -> Result<()> {
+    let temp_dir = tempdir()?;
+    write_table_properties(temp_dir.path())?;
+
+    let base_url = Url::from_file_path(temp_dir.path()).unwrap();
+    let table = Table::new(base_url.path()).await?;

Review Comment:
   Passing `base_url.path()` can produce a URL-path (e.g., on Windows it may look like `/C:/...`) rather than a native filesystem path, which can break `Table::new(...)` if it expects an OS path. Prefer passing the tempdir path directly (e.g., `temp_dir.path()` converted appropriately) instead of round-tripping through `Url`.



##########
crates/core/tests/table_bulk_insert_tests.rs:
##########
@@ -0,0 +1,123 @@
+use std::sync::Arc;
+use std::fs;
+
+use arrow::array::{Int32Array, StringArray};
+use arrow::compute::concat_batches;
+use arrow::record_batch::RecordBatch;
+use arrow_schema::{DataType, Field, Schema};
+use hudi_core::error::Result;
+use hudi_core::table::Table;
+use tempfile::tempdir;
+use url::Url;
+
+fn write_table_properties(base_dir: &std::path::Path) -> Result<()> {
+    let hoodie_dir = base_dir.join(".hoodie");
+    fs::create_dir_all(&hoodie_dir)?;
+
+    let properties = [
+        "hoodie.table.name=test_table",
+        "hoodie.table.type=COPY_ON_WRITE",
+        "hoodie.table.version=6",
+        "hoodie.timeline.layout.version=1",
+        "hoodie.populate.meta.fields=false",
+        "hoodie.base.file.format=parquet",
+    ]
+    .join("\n");
+
+    fs::write(hoodie_dir.join("hoodie.properties"), properties)?;
+    Ok(())
+}
+
+fn write_partitioned_table_properties(base_dir: &std::path::Path) -> Result<()> {
+    let hoodie_dir = base_dir.join(".hoodie");
+    fs::create_dir_all(&hoodie_dir)?;
+
+    let properties = [
+        "hoodie.table.name=test_table",
+        "hoodie.table.type=COPY_ON_WRITE",
+        "hoodie.table.version=6",
+        "hoodie.timeline.layout.version=1",
+        "hoodie.populate.meta.fields=false",
+        "hoodie.base.file.format=parquet",
+        "hoodie.table.partition.fields=region",
+    ]
+    .join("\n");
+
+    fs::write(hoodie_dir.join("hoodie.properties"), properties)?;
+    Ok(())
+}
+
+#[tokio::test]
+async fn bulk_insert_writes_records_and_commit() -> Result<()> {
+    let temp_dir = tempdir()?;
+    write_table_properties(temp_dir.path())?;
+
+    let base_url = Url::from_file_path(temp_dir.path()).unwrap();
+    let table = Table::new(base_url.path()).await?;
+
+    let schema = Schema::new(vec![
+        Field::new("id", DataType::Int32, false),
+        Field::new("name", DataType::Utf8, false),
+    ]);
+
+    let batch = RecordBatch::try_new(
+        schema.into(),
+        vec![
+            Arc::new(Int32Array::from(vec![1, 2, 3])),
+            Arc::new(StringArray::from(vec!["alice", "bob", "carol"])),
+        ],
+    )?;
+
+    let result = table.bulk_insert(batch).await?;
+    assert_eq!(result.num_rows, 3);
+
+    let reopened = Table::new(base_url.path()).await?;
+    let records = reopened.read_snapshot(std::iter::empty::<(&str, &str, &str)>()).await?;
+    assert_eq!(records.len(), 1);
+
+    let read_batch = concat_batches(&records[0].schema(), &records)?;
+    assert_eq!(read_batch.num_rows(), 3);
+
+    let ids = read_batch
+        .column_by_name("id")
+        .and_then(|array| array.as_any().downcast_ref::<Int32Array>())
+        .expect("expected id column");
+    let names = read_batch
+        .column_by_name("name")
+        .and_then(|array| array.as_any().downcast_ref::<StringArray>())
+        .expect("expected name column");
+
+    assert_eq!(ids.values(), &[1, 2, 3]);
+    assert_eq!(names.value(0), "alice");
+    assert_eq!(names.value(1), "bob");
+    assert_eq!(names.value(2), "carol");
+
+    let commit_file = temp_dir
+        .path()
+        .join(".hoodie")
+        .join(format!("{}.commit", result.instant));
+    assert!(commit_file.exists(), "commit file should exist");
+
+    Ok(())
+}
+
+#[tokio::test]
+async fn bulk_insert_rejects_partitioned_tables() -> Result<()> {
+    let temp_dir = tempdir()?;
+    write_partitioned_table_properties(temp_dir.path())?;
+
+    let base_url = Url::from_file_path(temp_dir.path()).unwrap();
+    let table = Table::new(base_url.path()).await?;

Review Comment:
   Passing `base_url.path()` can produce a URL-path (e.g., on Windows it may look like `/C:/...`) rather than a native filesystem path, which can break `Table::new(...)` if it expects an OS path. Prefer passing the tempdir path directly (e.g., `temp_dir.path()` converted appropriately) instead of round-tripping through `Url`.



##########
crates/core/src/table/writer.rs:
##########
@@ -0,0 +1,280 @@
+/*
+ * 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.
+ */
+
+use std::collections::HashMap;
+use std::io::Cursor;
+use std::str::FromStr;
+use std::sync::atomic::{AtomicI64, Ordering};
+
+use apache_avro::schema::AvroSchema;
+use apache_avro::Writer as AvroWriter;
+use arrow::record_batch::RecordBatch;
+use bytes::Bytes;
+use chrono::Utc;
+use object_store::PutPayload;
+use object_store::path::Path;
+use parquet::arrow::ArrowWriter;
+
+use crate::Result;
+use crate::config::table::HudiTableConfig::{RecordMergeStrategy, TableVersion, TimelineLayoutVersion, TimelinePath};
+use crate::error::CoreError;
+use crate::metadata::HUDI_METADATA_DIR;
+use crate::metadata::commit::{HoodieCommitMetadata, HoodieWriteStat};
+use crate::merge::RecordMergeStrategyValue;
+use crate::storage::error::StorageError;
+use crate::storage::util::join_url_segments;
+use crate::table::Table;
+use crate::timeline::instant::Instant;
+
+/// Result of a bulk insert write.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct BulkInsertResult {
+    pub instant: String,
+    pub base_file_path: String,
+    pub num_rows: usize,
+}
+
+/// Minimal bulk insert writer for append-only tables.
+#[derive(Clone, Debug)]
+pub struct BulkInsertWriter {
+    table: Table,
+}
+
+static LAST_EPOCH_MILLIS: AtomicI64 = AtomicI64::new(0);
+
+impl BulkInsertWriter {
+    pub fn new(table: &Table) -> Self {
+        Self { table: table.clone() }
+    }
+
+    pub async fn write(&self, batch: RecordBatch) -> Result<BulkInsertResult> {
+        self.ensure_append_only()?;
+        self.ensure_unpartitioned()?;
+
+        let request_instant = Self::current_timestamp();
+        let completion_instant = request_instant.clone();
+        let layout_two = self.is_layout_two();
+        let instant_name = if layout_two {
+            format!("{request_instant}_{completion_instant}.commit")
+        } else {
+            format!("{request_instant}.commit")
+        };
+        let instant = Instant::from_str(&instant_name)?;
+        let timeline_dir = self.timeline_dir();
+
+        let file_id = format!("bulk-insert-{request_instant}");
+        let write_token = "0-0-0";
+        let base_file_name = format!("{file_id}_{write_token}_{request_instant}.parquet");
+        let base_file_path = base_file_name.clone();
+
+        let file_bytes = self.write_parquet_bytes(&batch)?;
+        let file_size = file_bytes.len() as i64;
+
+        self.put_file(&base_file_path, file_bytes).await?;
+
+        let commit_metadata = self.build_commit_metadata(
+            &file_id,
+            &base_file_path,
+            batch.num_rows() as i64,
+            file_size,
+        );
+        if let Err(error) = self
+            .write_commit_file(&instant, &timeline_dir, &commit_metadata)
+            .await
+        {
+            let _ = self.delete_file(&base_file_path).await;
+            return Err(error);
+        }
+
+        Ok(BulkInsertResult {
+            instant: request_instant,
+            base_file_path,
+            num_rows: batch.num_rows(),
+        })
+    }
+
+    fn ensure_append_only(&self) -> Result<()> {
+        let strategy: String = self
+            .table
+            .hudi_configs
+            .get_or_default(RecordMergeStrategy)
+            .into();
+
+        if RecordMergeStrategyValue::from_str(&strategy)? != RecordMergeStrategyValue::AppendOnly {
+            return Err(CoreError::Unsupported(format!(
+                "Bulk insert is only supported for append-only tables. Found merge strategy '{strategy}'"
+            )));
+        }
+
+        Ok(())
+    }
+
+    fn ensure_unpartitioned(&self) -> Result<()> {
+        let partition_fields: Vec<String> = self
+            .table
+            .hudi_configs
+            .get_or_default(crate::config::table::HudiTableConfig::PartitionFields)
+            .into();
+
+        if !partition_fields.is_empty() {
+            return Err(CoreError::Unsupported(
+                "Bulk insert currently supports only unpartitioned append-only tables".to_string(),
+            ));
+        }
+
+        Ok(())
+    }
+
+    fn is_layout_two(&self) -> bool {
+        let table_version: isize = self.table.hudi_configs.get_or_default(TableVersion).into();
+        let layout_version: isize = self
+            .table
+            .hudi_configs
+            .get_or_default(TimelineLayoutVersion)
+            .into();
+        table_version >= 8 && layout_version == 2
+    }
+
+    fn timeline_dir(&self) -> String {
+        if self.is_layout_two() {
+            let timeline_path: String = self
+                .table
+                .hudi_configs
+                .get_or_default(TimelinePath)
+                .into();
+            format!("{HUDI_METADATA_DIR}/{timeline_path}")
+        } else {
+            HUDI_METADATA_DIR.to_string()
+        }
+    }
+
+    fn current_timestamp() -> String {
+        let now = Utc::now().timestamp_millis();
+
+        loop {
+            let last = LAST_EPOCH_MILLIS.load(Ordering::Relaxed);
+            let next = if now <= last { last + 1 } else { now };
+
+            if LAST_EPOCH_MILLIS
+                .compare_exchange(last, next, Ordering::SeqCst, Ordering::Relaxed)
+                .is_ok()
+            {
+                return format!("{next:017}");
+            }
+        }
+    }
+
+    fn write_parquet_bytes(&self, batch: &RecordBatch) -> Result<Vec<u8>> {
+        let cursor = Cursor::new(Vec::new());
+        let mut writer = ArrowWriter::try_new(cursor, batch.schema(), None)?;
+        writer.write(batch)?;
+        let cursor = writer.into_inner()?;
+        Ok(cursor.into_inner())
+    }
+
+    async fn put_file(&self, relative_path: &str, bytes: Vec<u8>) -> Result<()> {
+        let storage = self.table.file_system_view.storage.clone();
+        let object_url = join_url_segments(&storage.base_url, &[relative_path])?;
+        let object_path = Path::from_url_path(object_url.path()).map_err(StorageError::from)?;
+        storage
+            .object_store
+            .put(&object_path, PutPayload::from(Bytes::from(bytes)))
+            .await
+            .map_err(StorageError::from)?;
+        Ok(())
+    }
+
+    async fn delete_file(&self, relative_path: &str) -> Result<()> {
+        let storage = self.table.file_system_view.storage.clone();
+        let object_url = join_url_segments(&storage.base_url, &[relative_path])?;
+        let object_path = Path::from_url_path(object_url.path()).map_err(StorageError::from)?;
+        storage.object_store.delete(&object_path).await.map_err(StorageError::from)?;
+        Ok(())
+    }
+
+    fn build_commit_metadata(
+        &self,
+        file_id: &str,
+        base_file_path: &str,
+        num_rows: i64,
+        file_size: i64,
+    ) -> HoodieCommitMetadata {
+        let write_stat = HoodieWriteStat {
+            file_id: Some(file_id.to_string()),
+            path: Some(base_file_path.to_string()),
+            base_file: None,
+            log_files: None,
+            prev_commit: None,
+            num_writes: Some(num_rows),
+            num_deletes: Some(0),
+            num_update_writes: Some(0),
+            num_inserts: Some(num_rows),
+            total_write_bytes: Some(file_size),
+            total_write_errors: Some(0),
+            partition_path: Some(String::new()),
+            total_log_records: None,
+            total_log_files: None,
+            total_updated_records_compacted: None,
+            total_log_blocks: None,
+            total_corrupt_log_block: None,
+            total_rollback_blocks: None,
+            file_size_in_bytes: Some(file_size),
+            log_version: None,
+            log_offset: None,
+            prev_base_file: None,
+            min_event_time: None,
+            max_event_time: None,
+            total_log_files_compacted: None,
+            total_log_read_time_ms: None,
+            total_log_size_compacted: None,
+            temp_path: None,
+            num_updates: Some(0),
+        };
+
+        HoodieCommitMetadata {
+            version: Some(1),
+            operation_type: Some("BULK_INSERT".to_string()),
+            partition_to_write_stats: Some(HashMap::from([(String::new(), vec![write_stat])])),
+            partition_to_replace_file_ids: None,
+            compacted: Some(false),
+            extra_metadata: None,
+        }
+    }
+
+    async fn write_commit_file(
+        &self,
+        instant: &Instant,
+        timeline_dir: &str,
+        metadata: &HoodieCommitMetadata,
+    ) -> Result<()> {
+        let bytes = if self.is_layout_two() {
+            let schema = HoodieCommitMetadata::get_schema();
+            let mut writer = AvroWriter::new(&schema, Vec::new());
+            writer.append_ser(metadata)?;
+            writer.flush()?;
+            writer.into_inner()?
+        } else {
+            serde_json::to_vec(metadata)
+                .map_err(|e| CoreError::CommitMetadata(format!("Failed to serialize commit metadata: {e}")))?
+        };

Review Comment:
   The layout v2 commit-writing branch (layout detection + Avro serialization) is newly introduced but not exercised by the added tests. Adding a test case with `hoodie.table.version >= 8` and `hoodie.timeline.layout.version = 2` would cover both the v2 filename format and Avro commit metadata path.



-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(core): add append_only writes for append-only tables [hudi-rs]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #588:
URL: https://github.com/apache/hudi-rs/pull/588#issuecomment-6457385844

   ## [Codecov](https://app.codecov.io/gh/apache/hudi-rs/pull/588?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `73.85321%` with `57 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 79.67%. Comparing base ([`dd2f068`](https://app.codecov.io/gh/apache/hudi-rs/commit/dd2f0688e7a9b1e7a43ebb1fdff7d8df7e39b335?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`2c321b2`](https://app.codecov.io/gh/apache/hudi-rs/commit/2c321b220a933f22b925408efe7f8cad8e163564?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 2 commits behind head on main.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/hudi-rs/pull/588?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [crates/core/src/table/writer.rs](https://app.codecov.io/gh/apache/hudi-rs/pull/588?src=pr&el=tree&filepath=crates%2Fcore%2Fsrc%2Ftable%2Fwriter.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y3JhdGVzL2NvcmUvc3JjL3RhYmxlL3dyaXRlci5ycw==) | 72.54% | [42 Missing :warning: ](https://app.codecov.io/gh/apache/hudi-rs/pull/588?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [crates/core/src/table/mod.rs](https://app.codecov.io/gh/apache/hudi-rs/pull/588?src=pr&el=tree&filepath=crates%2Fcore%2Fsrc%2Ftable%2Fmod.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y3JhdGVzL2NvcmUvc3JjL3RhYmxlL21vZC5ycw==) | 69.23% | [12 Missing :warning: ](https://app.codecov.io/gh/apache/hudi-rs/pull/588?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   | [crates/core/tests/table\_bulk\_insert\_tests.rs](https://app.codecov.io/gh/apache/hudi-rs/pull/588?src=pr&el=tree&filepath=crates%2Fcore%2Ftests%2Ftable_bulk_insert_tests.rs&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-Y3JhdGVzL2NvcmUvdGVzdHMvdGFibGVfYnVsa19pbnNlcnRfdGVzdHMucnM=) | 88.46% | [3 Missing :warning: ](https://app.codecov.io/gh/apache/hudi-rs/pull/588?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@            Coverage Diff             @@
   ##             main     #588      +/-   ##
   ==========================================
   - Coverage   79.76%   79.67%   -0.10%     
   ==========================================
     Files         128      130       +2     
     Lines       12577    12795     +218     
   ==========================================
   + Hits        10032    10194     +162     
   - Misses       2545     2601      +56     
   ```
   </details>
   
   [:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/hudi-rs/pull/588?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   </details>


-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(core): add bulk insert for append-only tables [hudi-rs]

Posted by "morningstarxcdcode (via GitHub)" <gi...@apache.org>.
morningstarxcdcode commented on PR #588:
URL: https://github.com/apache/hudi-rs/pull/588#issuecomment-4364061390

   @xushiyan could you please review it..


-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(core): add bulk insert for append-only tables [hudi-rs]

Posted by "morningstarxcdcode (via GitHub)" <gi...@apache.org>.
morningstarxcdcode commented on code in PR #588:
URL: https://github.com/apache/hudi-rs/pull/588#discussion_r3176778129


##########
crates/core/src/table/writer.rs:
##########
@@ -0,0 +1,280 @@
+/*
+ * 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.
+ */
+
+use std::collections::HashMap;
+use std::io::Cursor;
+use std::str::FromStr;
+use std::sync::atomic::{AtomicI64, Ordering};
+
+use apache_avro::schema::AvroSchema;
+use apache_avro::Writer as AvroWriter;
+use arrow::record_batch::RecordBatch;
+use bytes::Bytes;
+use chrono::Utc;
+use object_store::PutPayload;
+use object_store::path::Path;
+use parquet::arrow::ArrowWriter;
+
+use crate::Result;
+use crate::config::table::HudiTableConfig::{RecordMergeStrategy, TableVersion, TimelineLayoutVersion, TimelinePath};
+use crate::error::CoreError;
+use crate::metadata::HUDI_METADATA_DIR;
+use crate::metadata::commit::{HoodieCommitMetadata, HoodieWriteStat};
+use crate::merge::RecordMergeStrategyValue;
+use crate::storage::error::StorageError;
+use crate::storage::util::join_url_segments;
+use crate::table::Table;
+use crate::timeline::instant::Instant;
+
+/// Result of a bulk insert write.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct BulkInsertResult {
+    pub instant: String,
+    pub base_file_path: String,
+    pub num_rows: usize,
+}
+
+/// Minimal bulk insert writer for append-only tables.
+#[derive(Clone, Debug)]
+pub struct BulkInsertWriter {
+    table: Table,
+}
+
+static LAST_EPOCH_MILLIS: AtomicI64 = AtomicI64::new(0);
+
+impl BulkInsertWriter {
+    pub fn new(table: &Table) -> Self {
+        Self { table: table.clone() }
+    }
+
+    pub async fn write(&self, batch: RecordBatch) -> Result<BulkInsertResult> {
+        self.ensure_append_only()?;
+        self.ensure_unpartitioned()?;
+
+        let request_instant = Self::current_timestamp();
+        let completion_instant = request_instant.clone();
+        let layout_two = self.is_layout_two();
+        let instant_name = if layout_two {
+            format!("{request_instant}_{completion_instant}.commit")
+        } else {
+            format!("{request_instant}.commit")
+        };
+        let instant = Instant::from_str(&instant_name)?;
+        let timeline_dir = self.timeline_dir();

Review Comment:
   ok



-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] feat(core): add append_only writes for append-only tables [hudi-rs]

Posted by "yihua (via GitHub)" <gi...@apache.org>.
yihua merged PR #588:
URL: https://github.com/apache/hudi-rs/pull/588


-- 
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: commits-unsubscribe@hudi.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org