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 0917036d [c] Expose current-state audit planning and Arrow reads
(#1391)
0917036d is described below
commit 0917036d189474cdb33ed8680b74a58cdf3441a0
Author: Socrates <[email protected]>
AuthorDate: Mon Nov 16 13:24:09 2026 +0800
[c] Expose current-state audit planning and Arrow reads (#1391)
---
bindings/c/src/audit_read.rs | 184 ++++++++++++++++++++++
bindings/c/src/lib.rs | 1 +
bindings/c/src/tests.rs | 1 +
bindings/c/src/tests/audit_read.rs | 311 +++++++++++++++++++++++++++++++++++++
docs/src/c-binding.md | 35 +++++
5 files changed, 532 insertions(+)
diff --git a/bindings/c/src/audit_read.rs b/bindings/c/src/audit_read.rs
new file mode 100644
index 00000000..135c5013
--- /dev/null
+++ b/bindings/c/src/audit_read.rs
@@ -0,0 +1,184 @@
+// 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.
+
+//! Current-state audit reads over audit-planned or externally assigned splits.
+
+use std::ffi::c_void;
+
+use arrow_array::ffi::FFI_ArrowSchema;
+use paimon::table::{AuditLogRead, AuditLogTable, Table, TableRead};
+use paimon::Plan;
+
+use crate::error::{check_non_null, paimon_error, PaimonErrorCode};
+use crate::result::{paimon_result_plan, paimon_result_record_batch_reader};
+use crate::runtime;
+use crate::types::*;
+
+/// Export the full current-state audit schema, including rowkind and the
+/// optional configured sequence number, through the Arrow C Data Interface.
+/// The output remains valid after the table is freed. Release it using its
+/// ArrowSchema release callback. Errors leave the output unchanged.
+///
+/// # Safety
+/// `table` must be a live table or null (returns error). `schema` must point
to
+/// initialized, writable, empty ArrowSchema storage or be null (returns
error).
+#[no_mangle]
+pub unsafe extern "C" fn paimon_table_export_audit_arrow_schema(
+ table: *const paimon_table,
+ schema: *mut c_void,
+) -> *mut paimon_error {
+ if let Err(error) = check_non_null(table, "table") {
+ 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 table = &*((*table).inner as *const Table);
+ let fields = match AuditLogTable::new(table.clone()).fields() {
+ Ok(fields) => fields,
+ Err(error) => return paimon_error::from_paimon(error),
+ };
+ let exported =
paimon::arrow::build_read_arrow_schema(&fields).and_then(|schema| {
+ FFI_ArrowSchema::try_from(schema.as_ref()).map_err(|error|
paimon::Error::DataInvalid {
+ message: format!("Failed to export audit schema: {error}"),
+ source: Some(Box::new(error)),
+ })
+ });
+ match exported {
+ Ok(schema) => {
+ std::ptr::write(output, schema);
+ std::ptr::null_mut()
+ }
+ Err(error) => paimon_error::from_paimon(error),
+ }
+}
+
+/// Plan a current-state audit scan using an ordinary ReadBuilder's table view,
+/// user-column projection, case sensitivity and filters. Core audit planning
+/// preserves retracts and complete merge groups; its LIMIT pruning is
disabled.
+/// Free the result with `paimon_plan_free`.
+///
+/// # Safety
+/// `builder` must be a live ReadBuilder or null (returns error).
+#[no_mangle]
+pub unsafe extern "C" fn paimon_read_builder_plan_audit(
+ builder: *const paimon_read_builder,
+) -> paimon_result_plan {
+ if let Err(error) = check_non_null(builder, "builder") {
+ return paimon_result_plan {
+ plan: std::ptr::null_mut(),
+ error,
+ };
+ }
+ let state = &*((*builder).inner as *const ReadBuilderState);
+ let planned = (|| {
+ let mut read_builder = state.table.new_read_builder();
+ read_builder.with_case_sensitive(state.case_sensitive);
+ if let Some(columns) = &state.projected_columns {
+ let columns =
columns.iter().map(String::as_str).collect::<Vec<_>>();
+ read_builder.with_projection(&columns)?;
+ }
+ if let Some(filter) = &state.filter {
+ read_builder.with_filter(filter.clone());
+ }
+ runtime().block_on(read_builder.new_audit_scan().plan())
+ })();
+ match planned {
+ Ok(plan) => paimon_result_plan {
+ plan: Box::into_raw(Box::new(paimon_plan {
+ inner: Box::into_raw(Box::new(plan)).cast(),
+ })),
+ error: std::ptr::null_mut(),
+ },
+ Err(error) => paimon_result_plan {
+ plan: std::ptr::null_mut(),
+ error: paimon_error::from_paimon(error),
+ },
+ }
+}
+
+/// Read current-state audit rows from the selected logical splits. `plan` can
+/// come from audit planning or `paimon_plan_from_split_bytes`; external
callers
+/// must preserve audit merge groups, including first-row/DV overlap
boundaries.
+/// This entry point does not interpret incremental or changelog plans.
+///
+/// The ordinary read selects user columns. Output prepends rowkind and the
+/// table-configured optional sequence column; an empty user projection reads
+/// only those system columns. Enforce final system-column filters and LIMIT in
+/// the caller. Offset/length select complete splits and saturate as for
ordinary
+/// reads. The stream owns its inputs and outlives the read and plan handles.
+///
+/// # Safety
+/// `read` and `plan` must be live handles or null (returns error).
+#[no_mangle]
+pub unsafe extern "C" fn paimon_table_read_to_audit_log_arrow(
+ read: *const paimon_table_read,
+ plan: *const paimon_plan,
+ offset: usize,
+ length: usize,
+) -> paimon_result_record_batch_reader {
+ if let Err(error) = check_non_null(read, "read") {
+ return paimon_result_record_batch_reader {
+ reader: std::ptr::null_mut(),
+ error,
+ };
+ }
+ if let Err(error) = check_non_null(plan, "plan") {
+ return paimon_result_record_batch_reader {
+ reader: std::ptr::null_mut(),
+ error,
+ };
+ }
+ let state = &*((*read).inner as *const TableReadState);
+ let plan = &*((*plan).inner as *const Plan);
+ let start = offset.min(plan.splits().len());
+ let end = offset.saturating_add(length).min(plan.splits().len());
+ let stream = (|| {
+ let all_fields = AuditLogTable::new(state.table.clone()).fields()?;
+ let system_count = all_fields.len() -
state.table.schema().fields().len();
+ let mut fields = all_fields[..system_count].to_vec();
+ for field in &state.read_type {
+ if !fields.iter().any(|selected| selected.id() == field.id()) {
+ fields.push(field.clone());
+ }
+ }
+ let mut table_read = TableRead::new(&state.table, fields,
state.data_predicates.clone());
+ if let Some(resources) = &state.resources {
+ table_read = table_read.with_resources(resources.clone());
+ }
+ AuditLogRead::new(table_read)?.to_arrow(&plan.splits()[start..end])
+ })();
+ match stream {
+ Ok(stream) => paimon_result_record_batch_reader {
+ reader: Box::into_raw(Box::new(paimon_record_batch_reader {
+ inner: Box::into_raw(Box::new(stream)).cast(),
+ })),
+ error: std::ptr::null_mut(),
+ },
+ Err(error) => paimon_result_record_batch_reader {
+ reader: std::ptr::null_mut(),
+ error: paimon_error::from_paimon(error),
+ },
+ }
+}
diff --git a/bindings/c/src/lib.rs b/bindings/c/src/lib.rs
index 387190dc..d1feeacb 100644
--- a/bindings/c/src/lib.rs
+++ b/bindings/c/src/lib.rs
@@ -19,6 +19,7 @@
// So it's type node can't meet camel case.
#![allow(non_camel_case_types)]
+mod audit_read;
mod blob_reader;
mod bucket_vector_search_split;
mod catalog;
diff --git a/bindings/c/src/tests.rs b/bindings/c/src/tests.rs
index 3497cb98..5ba11190 100644
--- a/bindings/c/src/tests.rs
+++ b/bindings/c/src/tests.rs
@@ -26,6 +26,7 @@
//! must NOT wrap C FFI calls inside another `block_on`. Use the global
//! runtime only for Rust-API setup (write_data_rust, setup_table_dirs).
+mod audit_read;
mod commit_messages;
mod table_arrow_schema;
diff --git a/bindings/c/src/tests/audit_read.rs
b/bindings/c/src/tests/audit_read.rs
new file mode 100644
index 00000000..62fbb134
--- /dev/null
+++ b/bindings/c/src/tests/audit_read.rs
@@ -0,0 +1,311 @@
+// 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::audit_read::*;
+use arrow_array::{Int64Array, Int8Array};
+
+fn audit_table(sequence: bool) -> Table {
+ let path = format!("memory:/ffi_audit_{sequence}");
+ let io = memory_file_io();
+ setup_table_dirs(&io, &path);
+ let schema = Schema::builder()
+ .column("id", DataType::Int(IntType::new()))
+ .column("name", DataType::VarChar(VarCharType::string_type()))
+ .primary_key(["id"])
+ .option("bucket", "1")
+ .option("write-only", "true")
+ .option("table-read.sequence-number.enabled", sequence.to_string())
+ .build()
+ .unwrap();
+ let table = Table::new(
+ io,
+ Identifier::new("default", "audit"),
+ path,
+ TableSchema::new(0, &schema),
+ None,
+ );
+ write_data_rust(&table, &[make_batch(vec![1, 2], vec!["old", "keep"])]);
+ let batch = make_batch(vec![1, 3], vec!["deleted", "added"]);
+ let mut fields = batch.schema().fields().to_vec();
+ fields.push(Arc::new(ArrowField::new(
+ "_VALUE_KIND",
+ ArrowDataType::Int8,
+ false,
+ )));
+ let mut columns = batch.columns().to_vec();
+ columns.push(Arc::new(Int8Array::from(vec![3, 0])));
+ write_data_rust(
+ &table,
+ &[RecordBatch::try_new(Arc::new(ArrowSchema::new(fields)),
columns).unwrap()],
+ );
+ table
+}
+
+unsafe fn batches(reader: *mut paimon_record_batch_reader) -> Vec<RecordBatch>
{
+ let mut output = Vec::new();
+ loop {
+ let next = paimon_record_batch_reader_next(reader);
+ assert!(next.error.is_null());
+ if next.batch.array.is_null() {
+ break;
+ }
+ let array = ptr::replace(
+ next.batch.array.cast::<FFI_ArrowArray>(),
+ FFI_ArrowArray::empty(),
+ );
+ let schema = ptr::replace(
+ next.batch.schema.cast::<FFI_ArrowSchema>(),
+ FFI_ArrowSchema::empty(),
+ );
+ let data = arrow_array::ffi::from_ffi(array, &schema).unwrap();
+ paimon_arrow_batch_free(next.batch);
+ output.push(RecordBatch::from(StructArray::from(data)));
+ }
+ paimon_record_batch_reader_free(reader);
+ output
+}
+
+#[test]
+fn current_audit_retains_deletes_and_owns_its_stream_and_schema() {
+ for sequence in [false, true] {
+ unsafe {
+ let table = wrap_table(audit_table(sequence));
+ assert_eq!(
+ read_rows_ffi(table),
+ vec![(2, "keep".into()), (3, "added".into())]
+ );
+ let mut schema = FFI_ArrowSchema::empty();
+ assert!(paimon_table_export_audit_arrow_schema(
+ table,
+ (&mut schema as *mut FFI_ArrowSchema).cast()
+ )
+ .is_null());
+ let duplicate = paimon_table_export_audit_arrow_schema(
+ table,
+ (&mut schema as *mut FFI_ArrowSchema).cast(),
+ );
+ assert!(!duplicate.is_null());
+ paimon_error_free(duplicate);
+ let builder = paimon_table_new_read_builder(table);
+ assert!(builder.error.is_null());
+ // A read limit must not prune away the winning tombstone's merge
group.
+ assert!(paimon_read_builder_with_limit(builder.read_builder,
1).is_null());
+ let plan = paimon_read_builder_plan_audit(builder.read_builder);
+ assert!(plan.error.is_null());
+ let read = paimon_read_builder_new_read(builder.read_builder);
+ assert!(read.error.is_null());
+ let stream = paimon_table_read_to_audit_log_arrow(read.read,
plan.plan, 0, usize::MAX);
+ assert!(stream.error.is_null());
+ paimon_table_read_free(read.read);
+ paimon_plan_free(plan.plan);
+ paimon_read_builder_free(builder.read_builder);
+ unwrap_table(table);
+
+ let expected_schema = ArrowSchema::try_from(&schema).unwrap();
+ let output = batches(stream.reader);
+ let mut rows = Vec::new();
+ for batch in output {
+ assert_eq!(batch.schema().as_ref(), &expected_schema);
+ let kinds = batch
+ .column_by_name("rowkind")
+ .unwrap()
+ .as_any()
+ .downcast_ref::<StringArray>()
+ .unwrap();
+ let ids = batch
+ .column_by_name("id")
+ .unwrap()
+ .as_any()
+ .downcast_ref::<Int32Array>()
+ .unwrap();
+ let names = batch
+ .column_by_name("name")
+ .unwrap()
+ .as_any()
+ .downcast_ref::<StringArray>()
+ .unwrap();
+ if sequence {
+ let seq = batch
+ .column_by_name("_SEQUENCE_NUMBER")
+ .unwrap()
+ .as_any()
+ .downcast_ref::<Int64Array>()
+ .unwrap();
+ assert_eq!(seq.null_count(), 0);
+ }
+ for row in 0..batch.num_rows() {
+ rows.push((
+ ids.value(row),
+ kinds.value(row).to_string(),
+ names.value(row).to_string(),
+ ));
+ }
+ }
+ rows.sort();
+ assert_eq!(
+ rows,
+ vec![
+ (1, "-D".into(), "deleted".into()),
+ (2, "+I".into(), "keep".into()),
+ (3, "+I".into(), "added".into())
+ ]
+ );
+ }
+ }
+}
+
+#[test]
+fn current_audit_executes_imported_splits_and_system_only_projection() {
+ unsafe {
+ let table = wrap_table(audit_table(false));
+ let builder = paimon_table_new_read_builder(table).read_builder;
+ let plan = paimon_read_builder_plan_audit(builder);
+ assert!(plan.error.is_null());
+ let core_plan = &*((*plan.plan).inner as *const paimon::Plan);
+ assert_eq!(core_plan.splits().len(), 1);
+ let encoded = core_plan.splits()[0].serialize().unwrap();
+ let imported = paimon_plan_from_split_bytes(encoded.as_ptr(),
encoded.len());
+ assert!(imported.error.is_null());
+ drop(encoded);
+ let empty_projection = [ptr::null()];
+ assert!(paimon_read_builder_with_projection(builder,
empty_projection.as_ptr()).is_null());
+ let read = paimon_read_builder_new_read(builder).read;
+ for (offset, length) in [(0, 0), (usize::MAX, usize::MAX)] {
+ let result = paimon_table_read_to_audit_log_arrow(read,
imported.plan, offset, length);
+ assert!(result.error.is_null());
+ assert!(batches(result.reader).is_empty());
+ }
+ let result = paimon_table_read_to_audit_log_arrow(read, imported.plan,
0, 1);
+ assert!(result.error.is_null());
+ let output = batches(result.reader);
+ assert_eq!(output.iter().map(RecordBatch::num_rows).sum::<usize>(), 3);
+ assert!(output
+ .iter()
+ .all(|batch| batch.num_columns() == 1 &&
batch.schema().field(0).name() == "rowkind"));
+ paimon_table_read_free(read);
+ paimon_plan_free(imported.plan);
+ paimon_plan_free(plan.plan);
+ paimon_read_builder_free(builder);
+ unwrap_table(table);
+ }
+}
+
+#[test]
+fn
current_audit_applies_value_filters_after_merge_and_resolves_projection_case() {
+ unsafe {
+ let table = wrap_table(audit_table(false));
+ for (name, expected_count) in [("old", 0), ("deleted", 1)] {
+ let builder = paimon_table_new_read_builder(table).read_builder;
+ assert!(paimon_read_builder_with_case_sensitive(builder,
false).is_null());
+ let column = CString::new("NAME").unwrap();
+ let projection = [column.as_ptr(), ptr::null()];
+ assert!(paimon_read_builder_with_projection(builder,
projection.as_ptr()).is_null());
+ let filter_column = CString::new("name").unwrap();
+ let datum = paimon_datum {
+ tag: 7,
+ int_val: 0,
+ double_val: 0.0,
+ str_data: name.as_ptr(),
+ str_len: name.len(),
+ int_val2: 0,
+ uint_val: 0,
+ uint_val2: 0,
+ };
+ let predicate = paimon_predicate_equal(table,
filter_column.as_ptr(), datum);
+ assert!(predicate.error.is_null());
+ assert!(paimon_read_builder_with_filter(builder,
predicate.predicate).is_null());
+ let plan = paimon_read_builder_plan_audit(builder);
+ assert!(plan.error.is_null());
+ let read = paimon_read_builder_new_read(builder);
+ assert!(read.error.is_null());
+ let stream = paimon_table_read_to_audit_log_arrow(read.read,
plan.plan, 0, usize::MAX);
+ assert!(stream.error.is_null());
+ let output = batches(stream.reader);
+ assert_eq!(
+ output.iter().map(RecordBatch::num_rows).sum::<usize>(),
+ expected_count
+ );
+ for batch in output {
+ assert_eq!(batch.num_columns(), 2);
+ let kinds = batch
+ .column(0)
+ .as_any()
+ .downcast_ref::<StringArray>()
+ .unwrap();
+ let names = batch
+ .column(1)
+ .as_any()
+ .downcast_ref::<StringArray>()
+ .unwrap();
+ for row in 0..batch.num_rows() {
+ assert_eq!(kinds.value(row), "-D");
+ assert_eq!(names.value(row), name);
+ }
+ }
+ paimon_table_read_free(read.read);
+ paimon_plan_free(plan.plan);
+ paimon_read_builder_free(builder);
+ }
+ unwrap_table(table);
+ }
+}
+
+#[test]
+fn current_audit_reports_null_arguments_and_accepts_empty_tables() {
+ unsafe {
+ let plan = paimon_read_builder_plan_audit(ptr::null());
+ assert!(!plan.error.is_null());
+ assert!(plan.plan.is_null());
+ paimon_error_free(plan.error);
+ let stream = paimon_table_read_to_audit_log_arrow(ptr::null(),
ptr::null(), 0, 1);
+ assert!(!stream.error.is_null());
+ assert!(stream.reader.is_null());
+ paimon_error_free(stream.error);
+ let mut schema = FFI_ArrowSchema::empty();
+ let error = paimon_table_export_audit_arrow_schema(
+ ptr::null(),
+ (&mut schema as *mut FFI_ArrowSchema).cast(),
+ );
+ assert!(!error.is_null());
+ assert!(schema.release.is_none());
+ paimon_error_free(error);
+
+ let table = wrap_table(Table::new(
+ memory_file_io(),
+ Identifier::new("default", "empty"),
+ "memory:/ffi_audit_empty".into(),
+ simple_table_schema(),
+ None,
+ ));
+ let builder = paimon_table_new_read_builder(table).read_builder;
+ let plan = paimon_read_builder_plan_audit(builder);
+ assert!(plan.error.is_null());
+ assert_eq!(paimon_plan_num_splits(plan.plan), 0);
+ let read = paimon_read_builder_new_read(builder).read;
+ let missing = paimon_table_read_to_audit_log_arrow(read, ptr::null(),
0, 1);
+ assert!(!missing.error.is_null());
+ paimon_error_free(missing.error);
+ let result = paimon_table_read_to_audit_log_arrow(read, plan.plan, 0,
usize::MAX);
+ assert!(result.error.is_null());
+ assert!(batches(result.reader).is_empty());
+ paimon_table_read_free(read);
+ paimon_plan_free(plan.plan);
+ paimon_read_builder_free(builder);
+ unwrap_table(table);
+ }
+}
diff --git a/docs/src/c-binding.md b/docs/src/c-binding.md
index 4b2c2dfa..6c7cf661 100644
--- a/docs/src/c-binding.md
+++ b/docs/src/c-binding.md
@@ -325,6 +325,41 @@ range is clamped to the number of available splits.
reversed: `paimon_table_write_write_arrow_batch` consumes the exported
Arrow structures, so the caller must not release them again.
+## Current-state Audit Reads
+
+Use `paimon_read_builder_plan_audit` to plan a current-state audit scan from an
+ordinary read builder. It preserves retracts and complete merge groups using
+the core audit planner. The builder's table view, user-column projection,
+case-sensitivity setting and filters are applied. Planning does not use the
+builder's limit to prune input; apply the final limit in the caller.
+
+Create a read with `paimon_read_builder_new_read`, then execute its assigned
+splits with `paimon_table_read_to_audit_log_arrow(read, plan, offset, length)`.
+The offset and length select complete logical splits, as in ordinary reads.
+The plan may also come from `paimon_plan_from_split_bytes`. Externally planned
+splits must preserve audit merge groups, including first-row merge and
+deletion-vector overlap boundaries; an ordinary scan plan that already pruned
+retract-only groups is not sufficient.
+
+Output prepends `rowkind` and, when configured by
+`table-read.sequence-number.enabled`, `_SEQUENCE_NUMBER` to the selected user
+fields. An empty user-column projection reads only these system columns.
+`paimon_table_export_audit_arrow_schema` exports the full audit schema to an
+initialized, empty `ArrowSchema`; the batch reader exports the actual projected
+schema with each batch. Release the standalone schema through its Arrow release
+callback, and release each batch with `paimon_arrow_batch_free`.
+
+The reader owns the inputs needed by its stream and may outlive the read,
+builder, table and plan handles. Use the existing record-batch reader functions
+to consume and free it. Attached resource contexts are retained by the stream.
+Apply system-column predicates in the caller; builder predicates address the
+base table's fields.
+
+These APIs read the merged current state, retaining winning delete rows. They
+do not return every historical event and do not execute incremental Delta,
+Changelog or Diff plans. Incremental planning and transport require separate
+interfaces.
+
## Projection and Predicates
Projection uses a null-terminated array of column names: