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

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

commit 607f8727dbecf7efaadbcc1f9903338d8a6f21fc
Author: Nicholas Jiang <[email protected]>
AuthorDate: Mon Nov 2 03:22:44 2026 -0800

    feat(datafusion): support CALL sys.compact procedure
    
    Expose table compaction to DataFusion SQL as a thin adapter over
    `Table::new_compact_builder()`: plan, execute every task, and commit
    the results in one COMPACT snapshot.
    
    - `table` is required. The optional `partitions` argument reuses the
      partition-alternatives syntax of `drop_global_index`; the shared
      parser helpers drop their `global_index` prefix.
    - Charge compaction reads and writes to the session memory pool.
    - Add `TableCommit::abort_compact`, which deletes the outputs of
      unsubmitted compaction results and reports every file it could not
      delete. Use it when a later task fails and log a warning on cleanup
      failure. Outputs are retained once the commit starts, since an
      uncertain commit may reference them.
    - Nothing is committed when the plan has no tasks.
    - Return one row with `tasks`, `files_removed`, `files_added` and
      `rows_written`, and log the table, task count, duration and metrics.
    - Document the procedure in the SQL guide.
    - Cover append, primary-key and data-evolution tables, partition
      filters, multi-task commits, task-failure cleanup, the session
      memory limit, and invalid arguments, and test that
      `abort_compact` reports files it could not delete.
---
 crates/integrations/datafusion/src/memory.rs       |  20 +-
 crates/integrations/datafusion/src/procedures.rs   | 178 ++++++++----
 crates/integrations/datafusion/tests/procedures.rs | 313 +++++++++++++++++++++
 crates/paimon/src/table/compact.rs                 |  18 ++
 crates/paimon/src/table/table_commit.rs            |  40 ++-
 crates/paimon/tests/append_compact_test.rs         |  74 +++++
 docs/src/sql.md                                    |  35 +++
 7 files changed, 611 insertions(+), 67 deletions(-)

diff --git a/crates/integrations/datafusion/src/memory.rs 
b/crates/integrations/datafusion/src/memory.rs
index bd16c3a2..dabbcd54 100644
--- a/crates/integrations/datafusion/src/memory.rs
+++ b/crates/integrations/datafusion/src/memory.rs
@@ -48,16 +48,22 @@ pub(crate) fn reader_resources(
 ) -> paimon::Result<ResourceContext> {
     // Register per execution, not on the reusable plan. Reader working state
     // cannot spill; downstream operators account for batches they retain.
-    let reservation = 
MemoryConsumer::new(format!("PaimonTableScan[{partition}]"))
-        .with_can_spill(false)
-        .register(context.memory_pool());
-    ResourceContext::builder()
-        .memory_pool(Arc::new(DataFusionMemoryPool { reservation }))
-        .build()
+    resources(context, format!("PaimonTableScan[{partition}]"))
 }
 
 pub(crate) fn writer_resources(context: &TaskContext) -> 
paimon::Result<ResourceContext> {
-    let reservation = MemoryConsumer::new("PaimonTableWrite")
+    resources(context, "PaimonTableWrite")
+}
+
+pub(crate) fn compact_resources(context: &TaskContext) -> 
paimon::Result<ResourceContext> {
+    resources(context, "PaimonTableCompact")
+}
+
+fn resources(
+    context: &TaskContext,
+    consumer: impl Into<String>,
+) -> paimon::Result<ResourceContext> {
+    let reservation = MemoryConsumer::new(consumer)
         .with_can_spill(false)
         .register(context.memory_pool());
     ResourceContext::builder()
diff --git a/crates/integrations/datafusion/src/procedures.rs 
b/crates/integrations/datafusion/src/procedures.rs
index d7f0b2da..50f3848f 100644
--- a/crates/integrations/datafusion/src/procedures.rs
+++ b/crates/integrations/datafusion/src/procedures.rs
@@ -33,6 +33,7 @@
 //! - `CALL sys.create_global_index(table => '...', index_column => '...', 
index_type => 'bitmap')`
 //! - `CALL sys.create_global_index(table => '...', index_column => '...', 
index_type => 'ivf-pq')`
 //! - `CALL sys.drop_global_index(table => '...', index_column => '...', 
index_type => 'btree')` (also 'bitmap', 'multivalue', 'fm', or a vindex type 
such as 'diskann')
+//! - `CALL sys.compact(table => '...'[, partitions => '...'])`
 //!
 //! REST management procedures (REST catalogs only, mirroring Java's
 //! `RESTCatalog.permissionManagement()` / `policyManagement()`):
@@ -45,12 +46,17 @@
 //!
 //! The `index_type` argument of the three global index procedures is
 //! case-insensitive and surrounding whitespace is ignored.
-//! `drop_global_index` accepts partition alternatives such as
+//! `drop_global_index` and `compact` accept partition alternatives such as
 //! `partitions => 'dt=2026-10-10,hr=1;dt=2026-10-11,hr=2'`; omitted keys are 
unrestricted.
-//! Explicit empty or invalid partition specifications fail before deleting 
any index.
+//! Explicit empty or invalid partition specifications fail before the table 
is changed.
 //! Timezone-less LTZ partition values use local time for non-legacy names and 
UTC for
 //! legacy names. Ambiguous or nonexistent local times require an explicit 
offset.
 //!
+//! `compact` returns one row of `tasks`, `files_removed`, `files_added` and 
`rows_written`,
+//! and makes no commit when no compaction task is planned. All tasks share 
one commit.
+//! When a later task fails, outputs of finished tasks are deleted 
best-effort; once the
+//! commit starts they are retained because an uncertain commit may reference 
them.
+//!
 //! `column_names` and `excluded_column_names` are comma-separated lists, not 
SQL arrays:
 //! `column_names => 'id, region'`. Java's Spark procedures take 
`ARRAY<STRING>` there, but a
 //! DataFusion CALL argument is always a scalar, so this crate uses the same 
comma convention as
@@ -59,7 +65,7 @@
 use std::collections::HashMap;
 use std::sync::Arc;
 
-use datafusion::arrow::array::{ArrayRef, StringArray};
+use datafusion::arrow::array::{ArrayRef, Int64Array, StringArray};
 use datafusion::arrow::datatypes::{DataType as ArrowDataType, Field, Schema};
 use datafusion::arrow::record_batch::RecordBatch;
 use datafusion::common::ScalarValue;
@@ -76,11 +82,12 @@ use paimon::api::{
 use paimon::catalog::{Catalog, Identifier, RESTCatalog};
 use paimon::spec::{CoreOptions, DataType, Datum, Predicate, PredicateBuilder, 
Snapshot};
 use paimon::table::{
-    normalize_global_index_type, BranchManager, ConsumerManager, 
SnapshotManager, Table,
-    TagManager, SUPPORTED_GLOBAL_INDEX_TYPES_FOR_DROP,
+    normalize_global_index_type, BranchManager, CompactMetrics, 
ConsumerManager, SnapshotManager,
+    Table, TagManager, SUPPORTED_GLOBAL_INDEX_TYPES_FOR_DROP,
 };
 
 use crate::error::to_datafusion_error;
+use crate::memory::compact_resources;
 
 /// Default `index_type` for the global index procedures when the argument is
 /// omitted, matching Java's `CreateGlobalIndexProcedure`.
@@ -224,6 +231,7 @@ fn declared_parameters(proc_name: &str) -> Option<&'static 
[&'static str]> {
             "partitions",
             "dry_run",
         ],
+        "compact" => &["table", "partitions"],
         "grant_permission" => &[
             "resource_type",
             "access",
@@ -347,6 +355,7 @@ pub async fn execute_procedure(
         "delete_branch" => proc_delete_branch(ctx, catalog, catalog_name, 
&args).await,
         "create_global_index" => proc_create_global_index(ctx, catalog, 
catalog_name, &args).await,
         "drop_global_index" => proc_drop_global_index(ctx, catalog, 
catalog_name, &args).await,
+        "compact" => proc_compact(ctx, catalog, catalog_name, &args).await,
         "grant_permission" => proc_grant_permission(ctx, catalog, 
catalog_name, &args).await,
         "revoke_permission" => proc_revoke_permission(ctx, catalog, 
catalog_name, &args).await,
         "list_permissions" => proc_list_permissions(ctx, catalog, 
catalog_name, &args).await,
@@ -1200,7 +1209,7 @@ async fn proc_drop_global_index(
     builder.with_dry_run(dry_run);
     if let Some(partitions) = args.get("partitions") {
         builder
-            .with_partition_filter(parse_global_index_partitions(&table, 
partitions)?)
+            .with_partition_filter(parse_partitions(&table, partitions)?)
             .map_err(to_datafusion_error)?;
     }
     let dropped = builder.execute().await.map_err(to_datafusion_error)?;
@@ -1216,12 +1225,84 @@ async fn proc_drop_global_index(
     ok_result(ctx)
 }
 
+async fn proc_compact(
+    ctx: &SessionContext,
+    catalog: &Arc<dyn Catalog>,
+    catalog_name: &str,
+    args: &HashMap<String, String>,
+) -> DFResult<DataFrame> {
+    let table = get_table(catalog, catalog_name, args).await?;
+    let started = std::time::Instant::now();
+    let resources = 
compact_resources(&ctx.task_ctx()).map_err(to_datafusion_error)?;
+    let mut builder = table.new_compact_builder().with_resources(resources);
+    if let Some(partitions) = args.get("partitions") {
+        builder = builder
+            .with_partition_filter(parse_partitions(&table, partitions)?)
+            .map_err(to_datafusion_error)?;
+    }
+    let plan = builder
+        .new_planner()
+        .map_err(to_datafusion_error)?
+        .plan()
+        .await
+        .map_err(to_datafusion_error)?;
+    let metrics = if plan.tasks().is_empty() {
+        CompactMetrics::default()
+    } else {
+        let executor = builder.new_executor().map_err(to_datafusion_error)?;
+        let commit = builder.new_commit().map_err(to_datafusion_error)?;
+        let mut results = Vec::with_capacity(plan.tasks().len());
+        for task in plan.tasks() {
+            match executor.execute(task).await {
+                Ok(result) => results.push(result),
+                Err(error) => {
+                    // Nothing has been submitted yet, so earlier outputs are 
unreferenced.
+                    if let Err(abort_error) = 
commit.abort_compact(&results).await {
+                        log::warn!(
+                            "Failed to delete unsubmitted compaction files of 
table {}: {abort_error}",
+                            table.identifier().full_name(),
+                        );
+                    }
+                    return Err(to_datafusion_error(error));
+                }
+            }
+        }
+        commit
+            .commit_compact(results)
+            .await
+            .map_err(to_datafusion_error)?
+    };
+    log::info!(
+        "Compacted table {} with {} task(s) in {:?}: {metrics:?}",
+        table.identifier().full_name(),
+        plan.tasks().len(),
+        started.elapsed(),
+    );
+
+    let schema = Arc::new(Schema::new(vec![
+        Field::new("tasks", ArrowDataType::Int64, false),
+        Field::new("files_removed", ArrowDataType::Int64, false),
+        Field::new("files_added", ArrowDataType::Int64, false),
+        Field::new("rows_written", ArrowDataType::Int64, false),
+    ]));
+    let columns: Vec<ArrayRef> = [
+        plan.tasks().len() as i64,
+        metrics.files_removed as i64,
+        metrics.files_added as i64,
+        metrics.rows_written as i64,
+    ]
+    .into_iter()
+    .map(|value| Arc::new(Int64Array::from(vec![value])) as ArrayRef)
+    .collect();
+    ctx.read_batch(RecordBatch::try_new(schema, columns)?)
+}
+
 /// Semicolon-separated alternatives, each containing comma-separated 
key=value constraints.
-fn parse_global_index_partitions(table: &Table, partitions: &str) -> 
DFResult<Predicate> {
+fn parse_partitions(table: &Table, partitions: &str) -> DFResult<Predicate> {
     let partition_fields = table.schema().partition_fields();
     if partition_fields.is_empty() {
         return Err(DataFusionError::Plan(
-            "Cannot filter global index partitions on an unpartitioned 
table".to_string(),
+            "Cannot filter partitions on an unpartitioned table".to_string(),
         ));
     }
     let pb = PredicateBuilder::new(table.schema().fields());
@@ -1258,7 +1339,7 @@ fn parse_global_index_partitions(table: &Table, 
partitions: &str) -> DFResult<Pr
             let predicate = if value == options.partition_default_name() {
                 pb.is_null(key)
             } else {
-                let datum = parse_global_index_partition_value(
+                let datum = parse_partition_value(
                     value,
                     field.data_type(),
                     options.legacy_partition_name(),
@@ -1278,7 +1359,7 @@ fn parse_global_index_partitions(table: &Table, 
partitions: &str) -> DFResult<Pr
     Ok(Predicate::or(alternatives))
 }
 
-fn parse_global_index_partition_value(
+fn parse_partition_value(
     value: &str,
     data_type: &DataType,
     legacy_partition_name: bool,
@@ -1340,19 +1421,16 @@ fn parse_global_index_partition_value(
             })
         }
         DataType::Timestamp(typ) => {
-            parse_global_index_partition_timestamp(value, data_type, 
typ.precision(), false)
+            parse_partition_timestamp(value, data_type, typ.precision(), false)
+        }
+        DataType::LocalZonedTimestamp(typ) => {
+            parse_partition_timestamp(value, data_type, typ.precision(), 
!legacy_partition_name)
         }
-        DataType::LocalZonedTimestamp(typ) => 
parse_global_index_partition_timestamp(
-            value,
-            data_type,
-            typ.precision(),
-            !legacy_partition_name,
-        ),
         _ => paimon::table::parse_format_partition_value(value, data_type),
     }
 }
 
-fn parse_global_index_partition_timestamp(
+fn parse_partition_timestamp(
     value: &str,
     data_type: &DataType,
     precision: u32,
@@ -1876,51 +1954,39 @@ mod tests {
     use paimon::spec::CommitKind;
 
     #[test]
-    fn test_global_index_partition_values_are_typed_and_strict() {
+    fn test_partition_values_are_typed_and_strict() {
         use paimon::spec::{
             CharType, DateType, DecimalType, FloatType, IntType, TimeType, 
TimestampType,
             VarCharType,
         };
         assert_eq!(
-            parse_global_index_partition_value("01", 
&DataType::Int(IntType::new()), true),
+            parse_partition_value("01", &DataType::Int(IntType::new()), true),
             Some(Datum::Int(1))
         );
         for text in ["1.5", "2147483648", "bad"] {
-            assert!(
-                parse_global_index_partition_value(text, 
&DataType::Int(IntType::new()), true)
-                    .is_none()
-            );
+            assert!(parse_partition_value(text, 
&DataType::Int(IntType::new()), true).is_none());
         }
-        assert!(parse_global_index_partition_value(
-            "2026-02-30",
-            &DataType::Date(DateType::new()),
-            true
-        )
-        .is_none());
+        assert!(
+            parse_partition_value("2026-02-30", 
&DataType::Date(DateType::new()), true).is_none()
+        );
         assert_eq!(
-            parse_global_index_partition_value(
-                "1970-01-02",
-                &DataType::Date(DateType::new()),
-                true
-            ),
+            parse_partition_value("1970-01-02", 
&DataType::Date(DateType::new()), true),
             Some(Datum::Date(1))
         );
         assert_eq!(
-            parse_global_index_partition_value(
+            parse_partition_value(
                 "a=b",
                 &DataType::VarChar(VarCharType::new(3).unwrap()),
                 true,
             ),
             Some(Datum::String("a=b".into()))
         );
-        assert!(parse_global_index_partition_value(
-            "abcd",
-            &DataType::Char(CharType::new(3).unwrap()),
-            true,
-        )
-        .is_none());
+        assert!(
+            parse_partition_value("abcd", 
&DataType::Char(CharType::new(3).unwrap()), true)
+                .is_none()
+        );
         assert_eq!(
-            parse_global_index_partition_value(
+            parse_partition_value(
                 "12:00:00.123",
                 &DataType::Time(TimeType::new(3).unwrap()),
                 true,
@@ -1930,7 +1996,7 @@ mod tests {
         let decimal = DataType::Decimal(DecimalType::new(4, 2).unwrap());
         for (text, unscaled) in [("1.235", 124), ("-1.235", -124), ("1.235e1", 
1235)] {
             assert_eq!(
-                parse_global_index_partition_value(text, &decimal, true),
+                parse_partition_value(text, &decimal, true),
                 Some(Datum::Decimal {
                     unscaled,
                     precision: 4,
@@ -1939,25 +2005,25 @@ mod tests {
             );
         }
         for text in ["99.995", "bad", "1_2.34"] {
-            assert!(parse_global_index_partition_value(text, &decimal, 
true).is_none());
+            assert!(parse_partition_value(text, &decimal, true).is_none());
         }
         let timestamp = DataType::Timestamp(TimestampType::new(1).unwrap());
         assert_eq!(
-            parse_global_index_partition_value("1970-01-01 00:00:00.199", 
&timestamp, true),
+            parse_partition_value("1970-01-01 00:00:00.199", &timestamp, true),
             Some(Datum::Timestamp {
                 millis: 199,
                 nanos: 0
             })
         );
-        assert!(parse_global_index_partition_value("123", &timestamp, 
true).is_none());
-        assert!(parse_global_index_partition_value("bad", &timestamp, 
true).is_none());
+        assert!(parse_partition_value("123", &timestamp, true).is_none());
+        assert!(parse_partition_value("bad", &timestamp, true).is_none());
         let float = DataType::Float(FloatType::new());
         assert_eq!(
-            parse_global_index_partition_value("1.1", &float, true),
+            parse_partition_value("1.1", &float, true),
             Some(Datum::Float(1.1))
         );
         for text in ["1e100", "1e-100", "1.234567891"] {
-            assert!(parse_global_index_partition_value(text, &float, 
true).is_none());
+            assert!(parse_partition_value(text, &float, true).is_none());
         }
     }
 
@@ -1983,17 +2049,15 @@ mod tests {
                         Datum::Timestamp { millis, nanos }
                     };
                     assert_eq!(
-                        parse_global_index_partition_value(text, &data_type, 
true),
+                        parse_partition_value(text, &data_type, true),
                         Some(expected),
                         "{data_type:?}: {text}"
                     );
                 }
-                assert!(parse_global_index_partition_value(
-                    "1970-01-01T00:00:00.1234567891Z",
-                    &data_type,
-                    true,
-                )
-                .is_none());
+                assert!(
+                    parse_partition_value("1970-01-01T00:00:00.1234567891Z", 
&data_type, true)
+                        .is_none()
+                );
             }
         }
     }
diff --git a/crates/integrations/datafusion/tests/procedures.rs 
b/crates/integrations/datafusion/tests/procedures.rs
index 22cf94e0..1ef0a807 100644
--- a/crates/integrations/datafusion/tests/procedures.rs
+++ b/crates/integrations/datafusion/tests/procedures.rs
@@ -22,11 +22,14 @@ use common::{
     setup_sql_context, string_value,
 };
 use datafusion::arrow::array::{Array, Int64Array, StringArray};
+use datafusion::execution::memory_pool::GreedyMemoryPool;
+use datafusion::execution::runtime_env::RuntimeEnvBuilder;
 use paimon::catalog::Identifier;
 use paimon::table::BranchManager;
 use paimon::Catalog;
 use std::collections::BTreeMap;
 use std::path::{Path, PathBuf};
+use std::sync::Arc;
 
 async fn setup_table_with_snapshots() -> (tempfile::TempDir, 
paimon_datafusion::SQLContext) {
     let (tmp, sql_context) = setup_sql_context().await;
@@ -3041,3 +3044,313 @@ async fn test_rollback_cleans_newer_tags() {
     let count = row_count(&sql_context, "SELECT * FROM 
paimon.test_db.`t1$tags`").await;
     assert_eq!(count, 0);
 }
+
+async fn compact_counts(
+    sql_context: &paimon_datafusion::SQLContext,
+    sql: &str,
+) -> (i64, i64, i64, i64) {
+    let batches = sql_context.sql(sql).await.unwrap().collect().await.unwrap();
+    assert_eq!(batches.len(), 1);
+    assert_eq!(batches[0].num_rows(), 1);
+    let value = |name: &str| {
+        batches[0]
+            .column_by_name(name)
+            .unwrap()
+            .as_any()
+            .downcast_ref::<Int64Array>()
+            .unwrap()
+            .value(0)
+    };
+    (
+        value("tasks"),
+        value("files_removed"),
+        value("files_added"),
+        value("rows_written"),
+    )
+}
+
+async fn latest_commit_kind(sql_context: &paimon_datafusion::SQLContext, 
table: &str) -> String {
+    let batches = sql_context
+        .sql(&format!(
+            "SELECT commit_kind FROM paimon.test_db.`{table}$snapshots` ORDER 
BY snapshot_id DESC LIMIT 1"
+        ))
+        .await
+        .unwrap()
+        .collect()
+        .await
+        .unwrap();
+    string_value(batches[0].column(0).as_ref(), 0).to_string()
+}
+
+#[tokio::test]
+async fn test_compact_append_table() {
+    let (_tmp, sql_context) = setup_sql_context().await;
+    exec(
+        &sql_context,
+        "CREATE TABLE paimon.test_db.t (id INT, name VARCHAR(100)) WITH (\
+            'write-only' = 'true',\
+            'compaction.min.file-num' = '2'\
+         )",
+    )
+    .await;
+    for (id, name) in [(1, "a"), (2, "b"), (3, "c")] {
+        exec(
+            &sql_context,
+            &format!("INSERT INTO paimon.test_db.t VALUES ({id}, '{name}')"),
+        )
+        .await;
+    }
+    let files = "SELECT * FROM paimon.test_db.`t$files`";
+    assert_eq!(row_count(&sql_context, files).await, 3);
+
+    let (tasks, removed, added, rows) =
+        compact_counts(&sql_context, "CALL sys.compact(table => 
'test_db.t')").await;
+    assert_eq!((tasks, removed, added, rows), (1, 3, 1, 3));
+    assert_eq!(row_count(&sql_context, files).await, 1);
+    assert_eq!(latest_commit_kind(&sql_context, "t").await, "COMPACT");
+    assert_eq!(
+        collect_id_name(&sql_context, "SELECT id, name FROM 
paimon.test_db.t").await,
+        vec![(1, "a".into()), (2, "b".into()), (3, "c".into())]
+    );
+
+    let snapshots = "SELECT * FROM paimon.test_db.`t$snapshots`";
+    let before = row_count(&sql_context, snapshots).await;
+    let (tasks, removed, added, rows) =
+        compact_counts(&sql_context, "CALL sys.compact(table => 
'test_db.t')").await;
+    assert_eq!((tasks, removed, added, rows), (0, 0, 0, 0));
+    assert_eq!(row_count(&sql_context, snapshots).await, before);
+}
+
+#[tokio::test]
+async fn test_compact_primary_key_table_merges_updates() {
+    let (_tmp, sql_context) = setup_table_with_snapshots().await;
+    exec(
+        &sql_context,
+        "INSERT INTO paimon.test_db.t1 VALUES (1, 'alice2')",
+    )
+    .await;
+    let files = "SELECT * FROM paimon.test_db.`t1$files`";
+    assert_eq!(row_count(&sql_context, files).await, 4);
+
+    let (tasks, removed, added, rows) =
+        compact_counts(&sql_context, "CALL sys.compact(table => 
'test_db.t1')").await;
+    assert_eq!((tasks, removed, added, rows), (1, 4, 1, 3));
+    assert_eq!(row_count(&sql_context, files).await, 1);
+    assert_eq!(latest_commit_kind(&sql_context, "t1").await, "COMPACT");
+    assert_eq!(
+        collect_id_name(&sql_context, "SELECT id, name FROM 
paimon.test_db.t1").await,
+        vec![
+            (1, "alice2".into()),
+            (2, "bob".into()),
+            (3, "charlie".into())
+        ]
+    );
+}
+
+#[tokio::test]
+async fn test_compact_partitions_preserve_other_partitions() {
+    let (_tmp, sql_context) = setup_sql_context().await;
+    for (table, primary_key, options, kept_in_a) in [
+        (
+            "append_t",
+            "",
+            "'write-only' = 'true', 'compaction.min.file-num' = '2'",
+            0,
+        ),
+        ("pk_t", ", PRIMARY KEY (id, dt)", "'bucket' = '1'", 1),
+    ] {
+        exec(
+            &sql_context,
+            &format!(
+                "CREATE TABLE paimon.test_db.{table} (id INT, name 
VARCHAR(100), dt VARCHAR(10)\
+                 {primary_key}) PARTITIONED BY (dt) WITH ({options})"
+            ),
+        )
+        .await;
+        for dt in ["a", "b"] {
+            for id in [1, 2] {
+                exec(
+                    &sql_context,
+                    &format!("INSERT INTO paimon.test_db.{table} VALUES ({id}, 
'n{id}', '{dt}')"),
+                )
+                .await;
+            }
+        }
+        let files_in = |dt: &str| {
+            format!("SELECT * FROM paimon.test_db.`{table}$files` WHERE 
partition = '{{{dt}}}'")
+        };
+        assert_eq!(row_count(&sql_context, &files_in("a")).await, 2);
+        assert_eq!(row_count(&sql_context, &files_in("b")).await, 2);
+
+        let (tasks, removed, added, _) = compact_counts(
+            &sql_context,
+            &format!("CALL sys.compact(table => 'test_db.{table}', partitions 
=> 'dt=a')"),
+        )
+        .await;
+        assert_eq!((tasks, removed, added), (1, 2, 1), "{table}");
+        assert_eq!(row_count(&sql_context, &files_in("a")).await, 1);
+        assert_eq!(row_count(&sql_context, &files_in("b")).await, 2);
+
+        exec(
+            &sql_context,
+            &format!("INSERT INTO paimon.test_db.{table} VALUES (3, 'n3', 
'a')"),
+        )
+        .await;
+        let snapshots = format!("SELECT * FROM 
paimon.test_db.`{table}$snapshots`");
+        let before = row_count(&sql_context, &snapshots).await;
+        let (tasks, removed, added, _) = compact_counts(
+            &sql_context,
+            &format!("CALL sys.compact(table => 'test_db.{table}', partitions 
=> 'dt=a;dt=b')"),
+        )
+        .await;
+        assert_eq!((tasks, removed, added), (2, 4 - kept_in_a, 2), "{table}");
+        assert_eq!(row_count(&sql_context, &snapshots).await, before + 1);
+        assert_eq!(
+            row_count(&sql_context, &files_in("a")).await,
+            1 + kept_in_a as usize
+        );
+        assert_eq!(row_count(&sql_context, &files_in("b")).await, 1);
+    }
+}
+
+#[tokio::test]
+async fn test_compact_task_failure_deletes_unsubmitted_files() {
+    let (tmp, sql_context) = setup_sql_context().await;
+    exec(
+        &sql_context,
+        "CREATE TABLE paimon.test_db.t (id INT, dt VARCHAR(10)) PARTITIONED BY 
(dt) WITH (\
+            'write-only' = 'true',\
+            'compaction.min.file-num' = '2'\
+         )",
+    )
+    .await;
+    for dt in ["a", "b"] {
+        for id in [1, 2] {
+            exec(
+                &sql_context,
+                &format!("INSERT INTO paimon.test_db.t VALUES ({id}, '{dt}')"),
+            )
+            .await;
+        }
+    }
+    let bucket = |dt: &str| 
tmp.path().join(format!("test_db.db/t/dt={dt}/bucket-0"));
+    let corrupted = std::fs::read_dir(bucket("b"))
+        .unwrap()
+        .next()
+        .unwrap()
+        .unwrap()
+        .path();
+    std::fs::write(corrupted, b"corrupted").unwrap();
+    let snapshots = "SELECT * FROM paimon.test_db.`t$snapshots`";
+    let before = row_count(&sql_context, snapshots).await;
+
+    let result = match sql_context
+        .sql("CALL sys.compact(table => 'test_db.t')")
+        .await
+    {
+        Ok(df) => df.collect().await.map(|_| ()),
+        Err(error) => Err(error),
+    };
+    assert!(result.is_err());
+    assert_eq!(row_count(&sql_context, snapshots).await, before);
+    assert_eq!(std::fs::read_dir(bucket("a")).unwrap().count(), 2);
+}
+
+#[tokio::test]
+async fn test_compact_honors_session_memory_limit() {
+    let (_tmp, catalog) = create_test_env();
+    let sql_context = create_sql_context(catalog.clone()).await;
+    exec(&sql_context, "CREATE SCHEMA paimon.test_db").await;
+    exec(
+        &sql_context,
+        "CREATE TABLE paimon.test_db.t (id INT) WITH (\
+            'write-only' = 'true',\
+            'compaction.min.file-num' = '2'\
+         )",
+    )
+    .await;
+    for id in [1, 2] {
+        exec(
+            &sql_context,
+            &format!("INSERT INTO paimon.test_db.t VALUES ({id})"),
+        )
+        .await;
+    }
+    let runtime_env = RuntimeEnvBuilder::new()
+        .with_memory_pool(Arc::new(GreedyMemoryPool::new(1)))
+        .build_arc()
+        .unwrap();
+    let mut limited = paimon_datafusion::SQLContext::builder()
+        .with_runtime_env(runtime_env)
+        .build();
+    limited.register_catalog("paimon", catalog).await.unwrap();
+    let snapshots = "SELECT * FROM paimon.test_db.`t$snapshots`";
+    let before = row_count(&sql_context, snapshots).await;
+
+    assert_sql_error(
+        &limited,
+        "CALL sys.compact(table => 'test_db.t')",
+        "Resources exhausted",
+    )
+    .await;
+    assert_eq!(row_count(&sql_context, snapshots).await, before);
+}
+
+#[tokio::test]
+async fn test_compact_data_evolution_table_keeps_deletions() {
+    let (_tmp, sql_context) = setup_sql_context().await;
+    exec(
+        &sql_context,
+        "CREATE TABLE paimon.test_db.t (id INT NOT NULL, name VARCHAR(100)) 
WITH (\
+            'row-tracking.enabled' = 'true',\
+            'data-evolution.enabled' = 'true',\
+            'deletion-vectors.enabled' = 'true',\
+            'write-only' = 'true',\
+            'compaction.min.file-num' = '2'\
+         )",
+    )
+    .await;
+    for (id, name) in [(1, "a"), (2, "b"), (3, "c")] {
+        exec(
+            &sql_context,
+            &format!("INSERT INTO paimon.test_db.t (id, name) VALUES ({id}, 
'{name}')"),
+        )
+        .await;
+    }
+    exec(&sql_context, "DELETE FROM paimon.test_db.t WHERE id = 2").await;
+
+    let (tasks, removed, added, rows) =
+        compact_counts(&sql_context, "CALL sys.compact(table => 
'test_db.t')").await;
+    assert_eq!((tasks, removed, added, rows), (1, 3, 1, 3));
+    assert_eq!(latest_commit_kind(&sql_context, "t").await, "COMPACT");
+    assert_eq!(
+        collect_id_name(&sql_context, "SELECT id, name FROM 
paimon.test_db.t").await,
+        vec![(1, "a".into()), (3, "c".into())]
+    );
+}
+
+#[tokio::test]
+async fn test_compact_rejects_invalid_arguments() {
+    let (_tmp, sql_context) = setup_table_with_snapshots().await;
+    let snapshots = "SELECT * FROM paimon.test_db.`t1$snapshots`";
+    let before = row_count(&sql_context, snapshots).await;
+    assert_sql_error(
+        &sql_context,
+        "CALL sys.compact(table => 'test_db.t1', partitions => 'id=1')",
+        "Cannot filter partitions on an unpartitioned table",
+    )
+    .await;
+    assert_sql_error(
+        &sql_context,
+        "CALL sys.compact(table => 'test_db.t1', order_by => 'id')",
+        "Argument order_by is unknown. Expected one of [table, partitions].",
+    )
+    .await;
+    assert_sql_error(
+        &sql_context,
+        "CALL sys.compact()",
+        "Missing required argument: 'table'",
+    )
+    .await;
+    assert_eq!(row_count(&sql_context, snapshots).await, before);
+}
diff --git a/crates/paimon/src/table/compact.rs 
b/crates/paimon/src/table/compact.rs
index 20728db4..17f4ce5e 100644
--- a/crates/paimon/src/table/compact.rs
+++ b/crates/paimon/src/table/compact.rs
@@ -408,6 +408,24 @@ impl CompactResult {
         &self.changelog_files
     }
 
+    /// Files created by this result; retired index entries still belong to 
the table.
+    pub(super) fn abort_message(&self) -> super::CommitMessage {
+        let mut message = super::CommitMessage::new(
+            self.task.partition.clone(),
+            self.task.bucket,
+            self.files.clone(),
+        );
+        message.new_changelog_files = self.changelog_files.clone();
+        message.new_index_files = self
+            .index_entries
+            .iter()
+            .flatten()
+            .filter(|entry| matches!(entry.kind, FileKind::Add))
+            .map(|entry| entry.index_file.clone())
+            .collect();
+        message
+    }
+
     pub fn metrics(&self) -> CompactMetrics {
         CompactMetrics {
             files_removed: self.task.files.len(),
diff --git a/crates/paimon/src/table/table_commit.rs 
b/crates/paimon/src/table/table_commit.rs
index bc1f4935..7203462c 100644
--- a/crates/paimon/src/table/table_commit.rs
+++ b/crates/paimon/src/table/table_commit.rs
@@ -501,6 +501,28 @@ impl TableCommit {
         Ok(prepared.metrics)
     }
 
+    /// Delete files prepared by compaction results that were never submitted.
+    /// Every file is attempted; the error names each file left behind.
+    /// Never call it after `commit_compact` starts: an uncertain commit may
+    /// already reference them.
+    pub async fn abort_compact(&self, results: &[super::CompactResult]) -> 
Result<()> {
+        let messages: Vec<_> = results
+            .iter()
+            .map(super::CompactResult::abort_message)
+            .collect();
+        let failed = self.delete_new_files(&messages).await?;
+        if failed.is_empty() {
+            return Ok(());
+        }
+        Err(crate::Error::UnexpectedError {
+            message: format!(
+                "Failed to delete files of unsubmitted compaction results: {}",
+                failed.join(", ")
+            ),
+            source: None,
+        })
+    }
+
     /// Commit new files with a caller-provided commit identifier.
     ///
     /// Identifiers must increase monotonically for a given `commit_user`.
@@ -1078,6 +1100,13 @@ impl TableCommit {
                 .abort(commit_messages)
                 .await;
         }
+        self.delete_new_files(commit_messages).await?;
+        Ok(())
+    }
+
+    /// Delete new files of known-uncommitted messages, continuing past 
failures.
+    /// Returns each path that could not be deleted with its error.
+    async fn delete_new_files(&self, commit_messages: &[CommitMessage]) -> 
Result<Vec<String>> {
         CoreOptions::new(self.table.schema().options())
             .ensure_type_paimon_served(&self.table.identifier().full_name())?;
         super::write_builder::ensure_table_write_allowed(&self.table)?;
@@ -1086,6 +1115,7 @@ impl TableCommit {
         let index_file_in_data_file_dir =
             
CoreOptions::new(self.table.schema().options()).index_file_in_data_file_dir();
 
+        let mut failed = Vec::new();
         for message in commit_messages {
             let bucket_path = self.bucket_path(&message.partition, 
message.bucket)?;
             for file in message
@@ -1096,7 +1126,9 @@ impl TableCommit {
                 .chain(message.compact_changelog_files.iter())
             {
                 for path in file.collect_files(&bucket_path) {
-                    let _ = self.table.file_io().delete_file(&path).await;
+                    if let Err(error) = 
self.table.file_io().delete_file(&path).await {
+                        failed.push(format!("{path}: {error}"));
+                    }
                 }
             }
             // An index file must be deleted where it was written: at its 
external
@@ -1121,10 +1153,12 @@ impl TableCommit {
                     index_file_in_data_file_dir,
                     file,
                 );
-                let _ = self.table.file_io().delete_file(&path).await;
+                if let Err(error) = 
self.table.file_io().delete_file(&path).await {
+                    failed.push(format!("{path}: {error}"));
+                }
             }
         }
-        Ok(())
+        Ok(failed)
     }
 
     fn bucket_path(&self, partition: &[u8], bucket: i32) -> Result<String> {
diff --git a/crates/paimon/tests/append_compact_test.rs 
b/crates/paimon/tests/append_compact_test.rs
index adbab730..69fcde32 100644
--- a/crates/paimon/tests/append_compact_test.rs
+++ b/crates/paimon/tests/append_compact_test.rs
@@ -26,11 +26,14 @@ use common::incremental_helpers::{
     write_batch,
 };
 use futures::TryStreamExt;
+use paimon::catalog::Identifier;
+use paimon::io::{FileIOBuilder, FileIOProvider};
 use paimon::spec::{
     CommitKind, DataType, Datum, IntType, PredicateBuilder, Schema, 
TableSchema, VarCharType,
 };
 use paimon::table::{CompactPlan, CompactResult, IncrementalScanMode, Table};
 use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
 
 fn schema(options: &[(&str, &str)]) -> TableSchema {
     let mut builder = Schema::builder()
@@ -691,6 +694,77 @@ async fn 
compact_execution_failure_cleans_only_its_unsubmitted_output() {
     );
 }
 
+#[derive(Debug)]
+struct FailFileProvider {
+    operator: opendal::Operator,
+    failing_file: Mutex<Option<String>>,
+}
+
+#[async_trait::async_trait]
+impl FileIOProvider for FailFileProvider {
+    async fn create(&self, path: &str) -> paimon::Result<(opendal::Operator, 
String)> {
+        if let Some(name) = self.failing_file.lock().unwrap().as_deref() {
+            if path.ends_with(name) {
+                return Err(paimon::Error::IoUnsupported {
+                    message: format!("cannot access {name}"),
+                });
+            }
+        }
+        Ok((
+            self.operator.clone(),
+            path.trim_start_matches("memory:/").into(),
+        ))
+    }
+}
+
+#[tokio::test]
+async fn abort_compact_attempts_every_output_and_reports_files_left_behind() {
+    let provider = Arc::new(FailFileProvider {
+        operator: 
opendal::Operator::from_config(opendal::services::MemoryConfig::default())
+            .unwrap(),
+        failing_file: Mutex::new(None),
+    });
+    let io = FileIOBuilder::new("unused")
+        .with_provider(provider.clone())
+        .build()
+        .unwrap();
+    let path = "memory:/compact/abort";
+    let table = Table::new(
+        io.clone(),
+        Identifier::new("default", "abort_compact"),
+        path.into(),
+        schema(&[("write-only", "true")]),
+        None,
+    );
+    setup_dirs(&io, path).await;
+    persist_table_schema(&io, path, table.schema()).await;
+    append_files(&table, 2).await;
+    let builder = table.new_compact_builder();
+    let plan = builder.new_planner().unwrap().plan().await.unwrap();
+    let executor = builder.new_executor().unwrap();
+    let results = vec![
+        executor.execute(&plan.tasks()[0]).await.unwrap(),
+        executor.execute(&plan.tasks()[0]).await.unwrap(),
+    ];
+    let source = table.new_read_builder().new_scan().plan().await.unwrap();
+    let bucket = source.splits()[0].bucket_path().to_string();
+    let outputs: Vec<_> = results
+        .iter()
+        .map(|result| format!("{bucket}/{}", result.files()[0].file_name))
+        .collect();
+    *provider.failing_file.lock().unwrap() = 
Some(results[0].files()[0].file_name.clone());
+
+    let commit = builder.new_commit().unwrap();
+    let error = commit.abort_compact(&results).await.unwrap_err();
+    assert!(error.to_string().contains(&results[0].files()[0].file_name));
+    *provider.failing_file.lock().unwrap() = None;
+    assert!(io.exists(&outputs[0]).await.unwrap());
+    assert!(!io.exists(&outputs[1]).await.unwrap());
+
+    commit.abort_compact(&results).await.unwrap();
+    assert!(!io.exists(&outputs[0]).await.unwrap());
+}
+
 #[tokio::test]
 async fn compact_obeys_the_executor_memory_budget_without_changing_the_table() 
{
     let table = table(schema(&[])).await;
diff --git a/docs/src/sql.md b/docs/src/sql.md
index aa1f382e..bee22a12 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -1795,6 +1795,41 @@ The preview uses the latest snapshot at the time of the 
call; concurrent changes
 can affect the number of files matched by a later drop. Reads retain the usual
 local-cache behavior. Partition filtering is not supported by this procedure.
 
+### compact
+
+Compact an append, primary-key or data-evolution table:
+
+```sql
+CALL sys.compact(table => 'paimon.my_db.my_table');
+```
+
+Set `partitions` to compact only matching partitions. Alternatives are 
separated
+by `;` and the constraints of each alternative by `,`; omitted partition keys 
are
+unrestricted. It is rejected on unpartitioned tables.
+
+```sql
+CALL sys.compact(
+  table => 'paimon.my_db.my_table',
+  partitions => 'dt=2026-10-10,hr=1;dt=2026-10-11,hr=2'
+);
+```
+
+The result is one row with `tasks`, `files_removed`, `files_added` and
+`rows_written`. `files_removed` counts files replaced in the new snapshot; 
they are
+kept for time travel until snapshot expiration. `rows_written` counts physical 
rows
+in the new files, which may include deleted rows retained by the table format. 
When
+no compaction task is planned, nothing is committed and every column is `0`. 
All
+tasks are committed in one snapshot; if a task fails, files written by earlier 
tasks
+are deleted on a best-effort basis and a warning names any file left behind.
+Compaction memory is charged to the session memory pool.
+
+Primary-key tables follow the incremental compaction strategy of Paimon core, 
so
+existing higher-level files may be kept instead of rewritten.
+
+On primary-key tables, compaction with the `lookup` changelog producer, the
+`first-row` merge engine or deletion vectors requires `local-cache.enabled = 
true`
+on the catalog.
+
 ### grant_permission
 
 Grant an access to a principal on a REST catalog. Only the REST catalog 
supports

Reply via email to