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 e7e9a4dc feat(c): expose joint partition and bucket routing (#1507)
e7e9a4dc is described below

commit e7e9a4dca808fda5e229d8297e7b99f0a73cb961
Author: Socrates <[email protected]>
AuthorDate: Mon Nov 23 20:53:46 2026 +0800

    feat(c): expose joint partition and bucket routing (#1507)
---
 bindings/c/src/bucket_router.rs          | 114 ++++++++-
 bindings/c/src/tests.rs                  |   1 +
 bindings/c/src/tests/routing.rs          | 421 +++++++++++++++++++++++++++++++
 crates/paimon/src/table/bucket_router.rs |  81 +++++-
 docs/src/c-binding.md                    |  61 +++++
 5 files changed, 674 insertions(+), 4 deletions(-)

diff --git a/bindings/c/src/bucket_router.rs b/bindings/c/src/bucket_router.rs
index bcfcb80a..a0f5805a 100644
--- a/bindings/c/src/bucket_router.rs
+++ b/bindings/c/src/bucket_router.rs
@@ -22,9 +22,11 @@ use paimon::spec::TableSchema;
 use paimon::table::{BucketRouter, PostponeBucketPlan};
 
 use crate::error::{check_non_null, paimon_error, validate_cstr, 
PaimonErrorCode};
-use crate::result::paimon_result_bucket_router;
-use crate::types::paimon_bucket_router;
+use crate::result::{paimon_result_bucket_router, paimon_result_next_batch};
+use crate::types::{paimon_arrow_batch, paimon_bucket_router};
 use crate::write::import_record_batch;
+use arrow_array::ffi::{FFI_ArrowArray, FFI_ArrowSchema};
+use arrow_array::{Array, StructArray};
 
 fn router_error(error: *mut paimon_error) -> paimon_result_bucket_router {
     paimon_result_bucket_router {
@@ -191,11 +193,109 @@ pub unsafe extern "C" fn 
paimon_bucket_router_route_arrow(
     ptr::null_mut()
 }
 
+/// Export required routing fields into an initialized empty ArrowSchema.
+/// The result has independent ownership and must be released by its callback.
+/// Shared read-only calls are allowed. Plan mutation and free require 
exclusive
+/// access to the router, including exclusion of in-flight route/schema calls.
+///
+/// # Safety
+/// router must be live and schema must point to writable initialized empty
+/// ArrowSchema storage. Null pointers return an error.
+#[no_mangle]
+pub unsafe extern "C" fn paimon_bucket_router_export_arrow_schema(
+    router: *const paimon_bucket_router,
+    schema: *mut c_void,
+) -> *mut paimon_error {
+    if let Err(error) = check_non_null(router, "router") {
+        return error;
+    }
+    if let Err(error) = check_non_null((*router).inner, "router.inner") {
+        return error;
+    }
+    if let Err(error) = check_non_null(schema, "schema") {
+        return error;
+    }
+    let output = schema.cast::<FFI_ArrowSchema>();
+    if (*output).release.is_some() {
+        return paimon_error::new(
+            PaimonErrorCode::InvalidInput,
+            "ArrowSchema output must be empty".into(),
+        );
+    }
+    let state = &*(*router).inner.cast::<RouterState>();
+    let schema = match state.router.routing_schema() {
+        Ok(schema) => schema,
+        Err(error) => return paimon_error::from_paimon(error),
+    };
+    match FFI_ArrowSchema::try_from(schema.as_ref()) {
+        Ok(schema) => {
+            ptr::write(output, schema);
+            ptr::null_mut()
+        }
+        Err(error) => paimon_error::new(PaimonErrorCode::InvalidInput, 
error.to_string()),
+    }
+}
+
+/// Return a row-aligned Arrow batch with partition_key (LargeBinary) and
+/// bucket_id (Int32), using fixed-bucket routing. Release the output 
containers
+/// with paimon_arrow_batch_free, including after moving their Arrow contents.
+/// Output can outlive the router. Empty input returns an owned empty batch.
+///
+/// Once pointer validation succeeds, both input Arrow structs are consumed,
+/// including on routing/import errors. Before import, validation errors leave
+/// input ownership with the caller. No input references survive this call.
+/// Calls may share a router concurrently with independent input/output 
storage.
+/// Plan mutation and free require exclusive access. Temporary allocations and
+/// output scale with batch rows and key sizes and use the normal Rust 
allocator.
+///
+/// # Safety
+/// router must be live. array and schema must point to valid initialized Arrow
+/// C Data structs with a Struct root. Null pointers return an error.
+#[no_mangle]
+pub unsafe extern "C" fn paimon_bucket_router_route_with_partitions_arrow(
+    router: *const paimon_bucket_router,
+    array: *mut c_void,
+    schema: *mut c_void,
+) -> paimon_result_next_batch {
+    let route = || -> Result<paimon_arrow_batch, *mut paimon_error> {
+        check_non_null(router, "router")?;
+        check_non_null((*router).inner, "router.inner")?;
+        check_non_null(array, "array")?;
+        check_non_null(schema, "schema")?;
+        let batch = import_record_batch(array, schema)?;
+        let state = &*(*router).inner.cast::<RouterState>();
+        let output = state
+            .router
+            .route_with_partitions(&batch)
+            .map_err(paimon_error::from_paimon)?;
+        let ffi_schema = FFI_ArrowSchema::try_from(output.schema().as_ref())
+            .map_err(|error| paimon_error::new(PaimonErrorCode::InvalidInput, 
error.to_string()))?;
+        let ffi_array = 
FFI_ArrowArray::new(&StructArray::from(output).to_data());
+        Ok(paimon_arrow_batch {
+            array: Box::into_raw(Box::new(ffi_array)).cast(),
+            schema: Box::into_raw(Box::new(ffi_schema)).cast(),
+        })
+    };
+    match route() {
+        Ok(batch) => paimon_result_next_batch {
+            batch,
+            error: ptr::null_mut(),
+        },
+        Err(error) => paimon_result_next_batch {
+            batch: paimon_arrow_batch {
+                array: ptr::null_mut(),
+                schema: ptr::null_mut(),
+            },
+            error,
+        },
+    }
+}
+
 /// Free a bucket router handle.
 ///
 /// # Safety
 /// Only call with a handle returned from 
`paimon_bucket_router_new_from_schema_json`
-/// once, or pass null.
+/// once, or pass null. Exclude all in-flight router calls before freeing.
 #[no_mangle]
 pub unsafe extern "C" fn paimon_bucket_router_free(router: *mut 
paimon_bucket_router) {
     if !router.is_null() {
@@ -223,3 +323,11 @@ const _: unsafe extern "C" fn(
     usize,
 ) -> *mut paimon_error = paimon_bucket_router_route_arrow;
 const _: unsafe extern "C" fn(*mut paimon_bucket_router) = 
paimon_bucket_router_free;
+
+const _: unsafe extern "C" fn(*const paimon_bucket_router, *mut c_void) -> 
*mut paimon_error =
+    paimon_bucket_router_export_arrow_schema;
+const _: unsafe extern "C" fn(
+    *const paimon_bucket_router,
+    *mut c_void,
+    *mut c_void,
+) -> paimon_result_next_batch = 
paimon_bucket_router_route_with_partitions_arrow;
diff --git a/bindings/c/src/tests.rs b/bindings/c/src/tests.rs
index 5d4d1b68..2686ecce 100644
--- a/bindings/c/src/tests.rs
+++ b/bindings/c/src/tests.rs
@@ -29,6 +29,7 @@
 mod audit_read;
 mod commit_messages;
 mod read_type;
+mod routing;
 mod table_arrow_schema;
 
 use std::collections::HashMap;
diff --git a/bindings/c/src/tests/routing.rs b/bindings/c/src/tests/routing.rs
new file mode 100644
index 00000000..ceeaff1a
--- /dev/null
+++ b/bindings/c/src/tests/routing.rs
@@ -0,0 +1,421 @@
+// 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 super::*;
+use crate::bucket_router::*;
+use arrow_array::{ArrayRef, Int64Array, LargeBinaryArray, RecordBatchOptions};
+use paimon::spec::{BigIntType, DecimalType, TimestampType};
+
+fn schema(data_type: DataType, function: &str, partitioned: bool) -> 
TableSchema {
+    let mut builder = Schema::builder()
+        .column("pt", DataType::VarChar(VarCharType::string_type()))
+        .column("id", data_type)
+        .option("bucket", "100")
+        .option("bucket-key", "id")
+        .option("bucket-function.type", function)
+        .option("write-only", "true");
+    if partitioned {
+        builder = builder.partition_keys(["pt"]);
+    }
+    TableSchema::new(0, &builder.build().unwrap())
+}
+
+fn batch(columns: Vec<(&str, ArrayRef)>) -> RecordBatch {
+    RecordBatch::try_from_iter(columns).unwrap()
+}
+
+unsafe fn router(schema: &TableSchema) -> *mut paimon_bucket_router {
+    let json = CString::new(serde_json::to_string(schema).unwrap()).unwrap();
+    let result = paimon_bucket_router_new_from_schema_json(json.as_ptr());
+    assert!(result.error.is_null());
+    result.router
+}
+
+unsafe fn route(
+    handle: *const paimon_bucket_router,
+    input: RecordBatch,
+) -> crate::result::paimon_result_next_batch {
+    let (mut array, mut schema) = export_batch_to_ffi(input);
+    let output = paimon_bucket_router_route_with_partitions_arrow(
+        handle,
+        (&mut **array as *mut FFI_ArrowArray).cast(),
+        (&mut **schema as *mut FFI_ArrowSchema).cast(),
+    );
+    assert!(array.is_released());
+    assert!(schema.release.is_none());
+    output
+}
+
+unsafe fn import(output: crate::result::paimon_result_next_batch) -> 
RecordBatch {
+    assert!(output.error.is_null());
+    let batch = crate::write::import_record_batch(output.batch.array, 
output.batch.schema).unwrap();
+    paimon_arrow_batch_free(output.batch);
+    batch
+}
+
+#[test]
+fn joint_routing_java_goldens_and_output_lifetime() {
+    let cases: Vec<(DataType, ArrayRef, Vec<i32>)> = vec![
+        (
+            DataType::Int(IntType::new()),
+            Arc::new(Int32Array::from(vec![i32::MIN, -3, 0, 5, i32::MAX])),
+            vec![19, 15, 99, 96, 21],
+        ),
+        (
+            DataType::VarChar(VarCharType::string_type()),
+            Arc::new(StringArray::from(vec![
+                None,
+                Some(""),
+                Some("hello"),
+                Some("abcdefghijk"),
+                Some("你好"),
+            ])),
+            vec![44, 19, 46, 23, 58],
+        ),
+        (
+            DataType::Decimal(DecimalType::new(20, 2).unwrap()),
+            Arc::new(
+                arrow_array::Decimal128Array::from(vec![
+                    None,
+                    Some(12340),
+                    Some(-9999999),
+                    Some(0),
+                ])
+                .with_precision_and_scale(20, 2)
+                .unwrap(),
+            ),
+            vec![60, 60, 44, 85],
+        ),
+        (
+            DataType::Timestamp(TimestampType::new(9).unwrap()),
+            Arc::new(arrow_array::TimestampNanosecondArray::from(vec![
+                -1_000_001,
+                -1,
+                0,
+                1,
+                1_000_001,
+                i64::MAX,
+            ])),
+            vec![38, 85, 54, 32, 55, 39],
+        ),
+    ];
+    // Same Java BinaryRow fixtures as the core bucket-router suite.
+    for (data_type, values, expected) in cases {
+        unsafe {
+            let handle = router(&schema(data_type, "default", false));
+            let input = batch(vec![("id", values)]);
+            let output = route(handle, input.clone());
+            let again = import(route(handle, input));
+            paimon_bucket_router_free(handle);
+            let output = import(output);
+            assert_eq!(&output, &again);
+            assert_eq!(
+                output
+                    .column(1)
+                    .as_any()
+                    .downcast_ref::<Int32Array>()
+                    .unwrap()
+                    .values(),
+                &expected
+            );
+            let keys = output
+                .column(0)
+                .as_any()
+                .downcast_ref::<LargeBinaryArray>()
+                .unwrap();
+            assert!(keys.iter().all(|key| key == keys.iter().next().unwrap()));
+        }
+    }
+    for (function, expected) in [
+        ("mod", vec![0, 92, 97, 0, 7]),
+        ("hive", vec![0, 0, 2, 0, 0]),
+    ] {
+        unsafe {
+            let handle = router(&schema(
+                DataType::BigInt(BigIntType::new()),
+                function,
+                false,
+            ));
+            let input = batch(vec![(
+                "id",
+                Arc::new(Int64Array::from(vec![
+                    None,
+                    Some(i64::MIN),
+                    Some(-3),
+                    Some(0),
+                    Some(i64::MAX),
+                ])),
+            )]);
+            let output = import(route(handle, input));
+            // Explicit expectations use 100 buckets. Java MOD uses 
floorMod(value, count).
+            assert_eq!(
+                output
+                    .column(1)
+                    .as_any()
+                    .downcast_ref::<Int32Array>()
+                    .unwrap()
+                    .values(),
+                &expected
+            );
+            paimon_bucket_router_free(handle);
+        }
+    }
+}
+
+#[test]
+fn joint_routing_matches_writer_partition_and_bucket_metadata() {
+    let schema = schema(DataType::Int(IntType::new()), "default", true);
+    let input = batch(vec![
+        ("id", Arc::new(Int32Array::from(vec![5, 0, -3]))),
+        ("pt", Arc::new(StringArray::from(vec!["a", "b", "a"]))),
+    ]);
+    let result = unsafe {
+        let handle = router(&schema);
+        let output = import(route(handle, input.clone()));
+        let missing = route(handle, input.project(&[0]).unwrap());
+        assert!(!missing.error.is_null());
+        paimon_error_free(missing.error);
+        paimon_bucket_router_free(handle);
+        output
+    };
+    let keys = result
+        .column(0)
+        .as_any()
+        .downcast_ref::<LargeBinaryArray>()
+        .unwrap();
+    assert_eq!(keys.value(0), keys.value(2));
+    assert_ne!(keys.value(0), keys.value(1));
+    let buckets = result
+        .column(1)
+        .as_any()
+        .downcast_ref::<Int32Array>()
+        .unwrap();
+    assert_eq!(buckets.values(), &[96, 99, 15]);
+    crate::runtime().block_on(async {
+        let io = memory_file_io();
+        let path = "memory:/joint_routing_writer";
+        io.mkdirs(&format!("{path}/schema")).await.unwrap();
+        io.mkdirs(&format!("{path}/snapshot")).await.unwrap();
+        let table = Table::new(
+            io.clone(),
+            Identifier::new("db", "route"),
+            path.into(),
+            schema,
+            None,
+        );
+        let mut writer = table.new_write_builder().new_write().unwrap();
+        writer
+            .write_arrow_batch(&input.project(&[1, 0]).unwrap())
+            .await
+            .unwrap();
+        let messages = writer.prepare_commit().await.unwrap();
+        let mut actual = messages
+            .iter()
+            .map(|message| {
+                assert_eq!(
+                    message
+                        .new_files
+                        .iter()
+                        .map(|file| file.row_count)
+                        .sum::<i64>(),
+                    1
+                );
+                (message.partition.clone(), message.bucket)
+            })
+            .collect::<Vec<_>>();
+        let mut expected = (0..3)
+            .map(|row| (keys.value(row).to_vec(), buckets.value(row)))
+            .collect::<Vec<_>>();
+        actual.sort();
+        expected.sort();
+        assert_eq!(actual, expected);
+    });
+}
+
+#[test]
+fn joint_routing_errors_consume_imported_inputs_and_return_empty_output() {
+    unsafe {
+        let handle = router(&schema(DataType::Int(IntType::new()), "default", 
false));
+        for input in [
+            batch(vec![("wrong", Arc::new(Int32Array::from(vec![5])))]),
+            batch(vec![("id", Arc::new(StringArray::from(vec!["bad"])))]),
+            batch(vec![
+                ("id", Arc::new(Int32Array::from(vec![5]))),
+                ("id", Arc::new(Int32Array::from(vec![5]))),
+            ]),
+        ] {
+            let output = route(handle, input);
+            assert!(!output.error.is_null());
+            assert!(output.batch.array.is_null() && 
output.batch.schema.is_null());
+            paimon_error_free(output.error);
+        }
+        let (mut array, mut schema) =
+            export_batch_to_ffi(batch(vec![("id", 
Arc::new(Int32Array::from(vec![5])))]));
+        let output = paimon_bucket_router_route_with_partitions_arrow(
+            ptr::null(),
+            (&mut **array as *mut FFI_ArrowArray).cast(),
+            (&mut **schema as *mut FFI_ArrowSchema).cast(),
+        );
+        assert!(!array.is_released() && schema.release.is_some());
+        paimon_error_free(output.error);
+        drop(FFI_ArrowArray::from_raw(
+            (&mut **array) as *mut FFI_ArrowArray,
+        ));
+        drop(FFI_ArrowSchema::from_raw(
+            (&mut **schema) as *mut FFI_ArrowSchema,
+        ));
+        paimon_bucket_router_free(handle);
+    }
+}
+
+#[test]
+fn joint_routing_schema_export_and_zero_column_batches() {
+    let definition = TableSchema::new(0, &Schema::builder().option("bucket", 
"1").build().unwrap());
+    unsafe {
+        let handle = router(&definition);
+        let mut schema = FFI_ArrowSchema::empty();
+        assert!(paimon_bucket_router_export_arrow_schema(
+            handle,
+            (&mut schema as *mut FFI_ArrowSchema).cast()
+        )
+        .is_null());
+        let live = paimon_bucket_router_export_arrow_schema(
+            handle,
+            (&mut schema as *mut FFI_ArrowSchema).cast(),
+        );
+        assert!(!live.is_null());
+        paimon_error_free(live);
+        assert_eq!(ArrowSchema::try_from(&schema).unwrap().fields().len(), 0);
+        schema.release.unwrap()(&mut schema);
+        for rows in [0, 7] {
+            let input = RecordBatch::try_new_with_options(
+                Arc::new(ArrowSchema::empty()),
+                vec![],
+                &RecordBatchOptions::new().with_row_count(Some(rows)),
+            )
+            .unwrap();
+            let output = import(route(handle, input));
+            assert_eq!(output.num_rows(), rows);
+            assert_eq!(
+                output
+                    .column(1)
+                    .as_any()
+                    .downcast_ref::<Int32Array>()
+                    .unwrap()
+                    .values(),
+                &vec![0; rows]
+            );
+        }
+        paimon_bucket_router_free(handle);
+        paimon_bucket_router_free(ptr::null_mut());
+    }
+}
+
+#[test]
+fn joint_routing_rejects_null_keys_and_postpone_and_exports_union() {
+    unsafe {
+        let definition = schema(
+            DataType::Int(IntType::with_nullable(false)),
+            "default",
+            true,
+        );
+        let handle = router(&definition);
+        let mut exported = FFI_ArrowSchema::empty();
+        assert!(paimon_bucket_router_export_arrow_schema(
+            handle,
+            (&mut exported as *mut FFI_ArrowSchema).cast()
+        )
+        .is_null());
+        let names = ArrowSchema::try_from(&exported)
+            .unwrap()
+            .fields()
+            .iter()
+            .map(|field| field.name().clone())
+            .collect::<Vec<_>>();
+        assert_eq!(names, vec!["pt", "id"]);
+        let input = batch(vec![
+            ("pt", Arc::new(StringArray::from(vec!["a"]))),
+            ("id", Arc::new(Int32Array::from(vec![None]))),
+        ]);
+        let failed = route(handle, input);
+        assert!(!failed.error.is_null());
+        paimon_error_free(failed.error);
+        paimon_bucket_router_free(handle);
+        assert_eq!(ArrowSchema::try_from(&exported).unwrap().fields().len(), 
2);
+        exported.release.unwrap()(&mut exported);
+        let definition = TableSchema::new(
+            0,
+            &Schema::builder()
+                .column("id", DataType::Int(IntType::new()))
+                .primary_key(["id"])
+                .option("bucket", "-2")
+                .build()
+                .unwrap(),
+        );
+        let handle = router(&definition);
+        let failed = route(
+            handle,
+            batch(vec![("id", Arc::new(Int32Array::from(vec![5])))]),
+        );
+        assert_eq!((*failed.error).code, PaimonErrorCode::Unsupported as i32);
+        paimon_error_free(failed.error);
+        paimon_bucket_router_free(handle);
+    }
+}
+
+#[test]
+fn joint_routing_import_failure_consumes_structs_and_calls_can_share_router() {
+    unsafe {
+        let handle = router(&schema(DataType::Int(IntType::new()), "default", 
false));
+        let data = Int32Array::from(vec![5]).to_data();
+        let mut array = FFI_ArrowArray::new(&data);
+        let mut schema = FFI_ArrowSchema::try_from(data.data_type()).unwrap();
+        let failed = paimon_bucket_router_route_with_partitions_arrow(
+            handle,
+            (&mut array as *mut FFI_ArrowArray).cast(),
+            (&mut schema as *mut FFI_ArrowSchema).cast(),
+        );
+        assert!(array.is_released() && schema.release.is_none());
+        assert!(!failed.error.is_null());
+        assert!(failed.batch.array.is_null() && failed.batch.schema.is_null());
+        paimon_error_free(failed.error);
+        let address = handle as usize;
+        std::thread::scope(|scope| {
+            let jobs = (0..4)
+                .map(|_| {
+                    scope.spawn(move || {
+                        let input = batch(vec![("id", 
Arc::new(Int32Array::from(vec![5])))]);
+                        let output = import(route(address as *const 
paimon_bucket_router, input));
+                        assert_eq!(
+                            output
+                                .column(1)
+                                .as_any()
+                                .downcast_ref::<Int32Array>()
+                                .unwrap()
+                                .value(0),
+                            96
+                        );
+                    })
+                })
+                .collect::<Vec<_>>();
+            for job in jobs {
+                job.join().unwrap();
+            }
+        });
+        paimon_bucket_router_free(handle);
+    }
+}
diff --git a/crates/paimon/src/table/bucket_router.rs 
b/crates/paimon/src/table/bucket_router.rs
index 61215cff..117b02f2 100644
--- a/crates/paimon/src/table/bucket_router.rs
+++ b/crates/paimon/src/table/bucket_router.rs
@@ -28,9 +28,11 @@ use crate::spec::{
 };
 use crate::table::PostponeBucketPlan;
 use crate::Result;
-use arrow_array::{Int32Array, RecordBatch, RecordBatchOptions};
+use arrow_array::{Array, Int32Array, LargeBinaryArray, RecordBatch, 
RecordBatchOptions};
 use arrow_schema::SchemaRef;
+use arrow_schema::{DataType as ArrowDataType, Field, Schema};
 use std::collections::{HashMap, HashSet};
+use std::sync::Arc;
 
 /// Compute the bucket of every input row without opening files or authorizing 
a table.
 ///
@@ -53,6 +55,7 @@ enum BucketRouterInner {
 
 #[derive(Debug, Clone)]
 struct FixedBucketRouter {
+    partition_fields: Vec<DataField>,
     bucket_fields: Vec<DataField>,
     bucket_indices: Vec<usize>,
     arrow_schema: SchemaRef,
@@ -86,7 +89,20 @@ impl FixedBucketRouter {
             .collect::<Result<Vec<_>>>()?;
         let bucket_function = 
CoreOptions::new(schema.options()).bucket_function_type()?;
         validate_bucket_function(bucket_function, &bucket_fields)?;
+        let partition_fields = schema
+            .partition_keys()
+            .iter()
+            .map(|name| {
+                schema
+                    .fields()
+                    .iter()
+                    .find(|field| field.name() == name)
+                    .cloned()
+                    .ok_or_else(|| data_invalid(format!("Unknown partition 
column '{name}'")))
+            })
+            .collect::<Result<Vec<_>>>()?;
         Ok(Self {
+            partition_fields,
             arrow_schema: 
crate::arrow::build_target_arrow_schema(&bucket_fields)?,
             bucket_indices: (0..bucket_fields.len()).collect(),
             bucket_fields,
@@ -256,6 +272,69 @@ impl BucketRouter {
         }
     }
 
+    /// Required fields for joint partition and bucket routing, with the core
+    /// write types and field IDs. Payload fields may be omitted from inputs.
+    pub fn routing_schema(&self) -> Result<SchemaRef> {
+        match &self.inner {
+            BucketRouterInner::Fixed(router) => {
+                let mut fields = router.partition_fields.clone();
+                for field in &router.bucket_fields {
+                    if !fields
+                        .iter()
+                        .any(|existing| existing.name() == field.name())
+                    {
+                        fields.push(field.clone());
+                    }
+                }
+                crate::arrow::build_target_arrow_schema(&fields)
+            }
+            BucketRouterInner::Postpone(router) => 
Ok(router.arrow_schema.clone()),
+        }
+    }
+
+    /// Route fixed-bucket inputs to non-null `partition_key` (LargeBinary) and
+    /// `bucket_id` (Int32) columns in input row order.
+    ///
+    /// Partition bytes use the writer's binary-row partition encoding. Compare
+    /// them only within one frozen schema and SDK implementation during an
+    /// execution. Their cross-version persisted representation is unspecified.
+    /// Inputs must include partition and bucket fields. Normalization follows
+    /// the core write-array conversion and does not evaluate missing defaults.
+    /// Postpone joint routing requires a separate plan-aware API.
+    pub fn route_with_partitions(&self, batch: &RecordBatch) -> 
Result<RecordBatch> {
+        let BucketRouterInner::Fixed(router) = &self.inner else {
+            return Err(crate::Error::Unsupported {
+                message: "Joint routing currently requires fixed 
buckets".into(),
+            });
+        };
+        for field in self.routing_schema()?.fields() {
+            if let Some(column) = batch.column_by_name(field.name()) {
+                if !field.is_nullable() && column.null_count() != 0 {
+                    return Err(data_invalid(format!(
+                        "Routing column '{}' is NOT NULL",
+                        field.name()
+                    )));
+                }
+            }
+        }
+        let schema = 
crate::arrow::build_target_arrow_schema(&router.partition_fields)?;
+        let partitions = project_routing_input(batch, 
&router.partition_fields, &schema)?;
+        let indices = (0..router.partition_fields.len()).collect::<Vec<_>>();
+        let keys = batch_to_serialized_bytes(&partitions, &indices, 
&router.partition_fields)?;
+        let buckets = router.route(batch)?;
+        RecordBatch::try_new(
+            Arc::new(Schema::new(vec![
+                Field::new("partition_key", ArrowDataType::LargeBinary, false),
+                Field::new("bucket_id", ArrowDataType::Int32, false),
+            ])),
+            vec![
+                Arc::new(LargeBinaryArray::from_iter_values(keys)),
+                Arc::new(buckets),
+            ],
+        )
+        .map_err(|error| data_invalid(error.to_string()))
+    }
+
     /// Return non-null Int32 bucket IDs in input row order.
     pub fn route(&self, batch: &RecordBatch) -> Result<Int32Array> {
         match &self.inner {
diff --git a/docs/src/c-binding.md b/docs/src/c-binding.md
index 2ca3b4aa..5a0356c6 100644
--- a/docs/src/c-binding.md
+++ b/docs/src/c-binding.md
@@ -1041,3 +1041,64 @@ message.
 Every opaque handle returned by the C API has a matching free function. Free
 resources in reverse construction order. Pointer-based free functions accept
 null, which makes cleanup paths straightforward.
+
+## Schema-only Partition and Bucket Routing
+
+Create a reusable router with `paimon_bucket_router_new_from_schema_json` from 
a
+frozen complete `TableSchema` JSON. Construction and routing use schema 
metadata
+and Arrow inputs without accessing a catalog or storage. Existing
+`paimon_bucket_router_route_arrow` returns bucket IDs into caller storage.
+
+For fixed-bucket tables, `paimon_bucket_router_route_with_partitions_arrow`
+returns an owned Arrow batch with non-null `partition_key` (LargeBinary) and
+`bucket_id` (Int32) columns, in the original input row order. Use the pair to
+group rows during an execution, then assign writer channels in the embedding
+engine. The key uses the core writer's binary-row partition encoding. All rows
+of an unpartitioned table share one key. Key bytes are scoped to the frozen
+schema and SDK implementation used by that execution.
+
+`paimon_bucket_router_export_arrow_schema` exports the required partition and
+bucket fields into initialized empty caller-owned ArrowSchema storage. It uses
+the core write type mapping and field IDs. Release the schema with its 
callback.
+Inputs may project out payload columns and reorder required columns. Missing
+or duplicate names, incompatible types and NULL values in required NOT NULL
+fields return errors. The router uses core Arrow layout normalization.
+Consumers must supply the same logical values to routing and writing, including
+CHAR padding, defaults, timezone conversion and decimal/timestamp precision.
+The router requires all routing keys to be present.
+
+```c
+paimon_result_bucket_router router =
+    paimon_bucket_router_new_from_schema_json(frozen_schema_json);
+CHECK_RESULT(router);
+/* Use the exported input schema to prepare an Arrow Struct batch. */
+paimon_result_next_batch routes =
+    paimon_bucket_router_route_with_partitions_arrow(router.router, array, 
schema);
+CHECK_RESULT(routes);
+/* Import routes.batch through the Arrow C Data Interface. Group by both
+   columns and complete the consumer's reads before releasing its buffers. */
+paimon_arrow_batch_free(routes.batch);
+paimon_bucket_router_free(router.router);
+```
+
+Before Arrow import, null-pointer/handle validation errors leave input 
ownership
+with the caller. Once import begins, both input structs are moved to released
+values, including on import or routing errors. The router retains no batch
+references after the synchronous call. Errors return null output containers.
+An empty input returns a valid owned zero-row output, and zero-field inputs
+preserve their row count when the schema has no routing keys. Output data and
+exported schemas can outlive the router. After moving output into a consumer,
+call `paimon_arrow_batch_free` to release the library-owned container structs.
+
+Read-only routing and schema exports may share a router concurrently with
+independent input/output storage. Plan replacement and free require exclusive
+access and completion of all in-flight calls. Reconstruct independent routers
+from the same JSON when separate ownership is preferable. Temporary 
projections,
+normalization, partition encoding, bucket IDs and output buffers use ordinary
+Rust allocation. Their memory cost grows with batch row count and routing-key
+bytes, so callers should bound batch sizes.
+
+The joint result currently supports fixed buckets. Existing bucket-only
+postpone APIs use their shared bucket-count plan. A plan-aware joint C contract
+and its corresponding write/commit integration are follow-up work. Stateful
+dynamic-bucket coordination requires a separate API.

Reply via email to