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

roryqi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git


The following commit(s) were added to refs/heads/main by this push:
     new f990da79fe [#14784] feat(tms): Report S0/S1 metrics for four Iceberg 
maintenance types (#14785)
f990da79fe is described below

commit f990da79fe20b497f5174dc8addc0594fd4dbf5a
Author: MaSai <[email protected]>
AuthorDate: Tue Nov 10 09:41:47 2026 +0800

    [#14784] feat(tms): Report S0/S1 metrics for four Iceberg maintenance types 
(#14785)
    
    ### What changes were proposed in this pull request?
    
    Complete before (S0) / after (S1) metrics for the four TMS built-in
    Iceberg maintenance jobs, and fix shared flow gaps used by the
    maintenance dashboard — including the in-job **manifest rewrite trigger
    gate**.
    
    - Report **S1 after-metrics** after a successful procedure (previously
    only S0 then `finish`).
    - Apply **snapshot drift skip** only to **compaction** and **manifest
    rewrite**; expiry and orphan cleanup proceed past HEAD drift.
    - **Compaction** S0/S1 share the same schema: `custom-data-file-mse`,
    `custom-delete-file-number`, `custom-avg-file-size`,
    `custom-total-file-size`, `custom-file-number`.
    - **Manifest rewrite**: S0 = `custom-manifest-number` /
    `custom-avg-manifest-size`; S1 = `custom-rewritten-manifest-number`.
    - **Manifest in-job trigger**: `MaintenanceTriggerGate` evaluates
    `trigger-expr` (no longer always maintain). Default expression matches
    optimizer thresholds; added to `IcebergRewriteManifestsContent.rules()`.
    - **Snapshot expiry**: S0 = `custom-snapshot-number` only; S1 =
    `custom-expired-snapshot-number` / `custom-expired-file-size` via set
    difference. In-job gate still always maintain.
    - **Orphan cleanup**: **no** before-metrics call; S1 reports
    `custom-removed-file-number` and `custom-removed-file-size` (dry-run
    list → FileIO sizes → optional real delete).
    - `metricsJson` no longer includes `maintenanceType` / `snapshotId`.
    - Keep four Iceberg maintenance job templates (and
    `iceberg-maintenance-task`) at **v1**.
    - Sink S0/S1 helpers onto the four Iceberg job classes (CLI stays
    procedure-only).
    
    ### Why are the changes needed?
    
    The maintenance dashboard needs consistent before/after metrics per
    operation type, correct skip semantics for drift and trigger-expr, and
    orphan reclaimed-bytes reporting. See #14784.
    
    Fixes #14784
    
    ### Does this PR introduce _any_ user-facing change?
    
    No public REST API change. TMS action metrics payloads and in-job skip
    behavior for built-in Iceberg maintenance jobs change as described
    above. Built-in Iceberg maintenance job templates stay at `v1`.
    
    ### How was this patch tested?
    
    - [x] `./gradlew :api:test --tests
    org.apache.gravitino.policy.TestIcebergRewriteManifestsContent
    :maintenance:jobs:test --tests
    org.apache.gravitino.maintenance.jobs.iceberg.TestIcebergMaintenanceJob
    --tests
    org.apache.gravitino.maintenance.jobs.iceberg.TestMaintenanceTriggerGate
    --tests
    
org.apache.gravitino.maintenance.jobs.iceberg.TestIcebergRemoveOrphanFilesJobWithSpark
    -PskipITs`
    - [ ] Smoke a TMS compaction / manifest / expire / orphan action and
    confirm S0/S1 rows match the schemas above
    - [ ] Confirm manifest actions **skip** when S0 is below thresholds
    - [ ] Confirm orphan actions create no empty before-metrics row and
    report non-zero bytes when orphans have size
    - [ ] Confirm expiry/orphan are not skipped solely due to HEAD drift
    
    Made with [Cursor](https://cursor.com)
    
    ---------
    
    Co-authored-by: Cursor <[email protected]>
---
 .../policy/IcebergDataCompactionContent.java       |   6 +
 .../policy/IcebergOrphanFileRemovalContent.java    |   4 +
 .../policy/IcebergRewriteManifestsContent.java     |  25 ++
 .../policy/IcebergSnapshotExpirationContent.java   |   6 +
 .../policy/TestIcebergRewriteManifestsContent.java |   6 +
 .../jobs/iceberg/IcebergExpireSnapshotsJob.java    | 230 ++++++++++-
 .../maintenance/jobs/iceberg/IcebergJobUtils.java  |  66 +++-
 .../jobs/iceberg/IcebergMaintenanceAction.java     |  84 ++++
 .../jobs/iceberg/IcebergMaintenanceJob.java        | 430 +++++++++------------
 .../jobs/iceberg/IcebergRemoveOrphanFilesJob.java  | 354 ++++++++++++-----
 .../jobs/iceberg/IcebergRewriteDataFilesJob.java   | 191 +++++++--
 .../jobs/iceberg/IcebergRewriteManifestsJob.java   | 163 ++++++--
 .../jobs/iceberg/MaintenanceTriggerGate.java       |  17 +-
 .../jobs/iceberg/RemoteLocationValidator.java      |   5 +-
 .../jobs/iceberg/TableSnapshotMetrics.java         |  73 ++++
 .../iceberg/TestIcebergExpireSnapshotsJob.java     |  40 +-
 .../jobs/iceberg/TestIcebergMaintenanceJob.java    |  24 +-
 .../iceberg/TestIcebergRemoveOrphanFilesJob.java   |  17 +-
 .../TestIcebergRemoveOrphanFilesJobWithSpark.java  | 110 +++---
 .../iceberg/TestIcebergRewriteDataFilesJob.java    | 191 +--------
 .../iceberg/TestIcebergRewriteManifestsJob.java    |  18 +-
 .../TestIcebergRewriteManifestsJobWithSpark.java   |  15 +-
 .../jobs/iceberg/TestMaintenanceTriggerGate.java   |  84 +++-
 .../scheduler/job/MaintenanceJobConfBuilder.java   |   9 +
 .../job/TestMaintenanceJobConfBuilder.java         |  23 ++
 25 files changed, 1505 insertions(+), 686 deletions(-)

diff --git 
a/api/src/main/java/org/apache/gravitino/policy/IcebergDataCompactionContent.java
 
b/api/src/main/java/org/apache/gravitino/policy/IcebergDataCompactionContent.java
index 902700bb62..61aeccf7f2 100644
--- 
a/api/src/main/java/org/apache/gravitino/policy/IcebergDataCompactionContent.java
+++ 
b/api/src/main/java/org/apache/gravitino/policy/IcebergDataCompactionContent.java
@@ -76,6 +76,12 @@ public class IcebergDataCompactionContent extends 
AbstractExecutablePolicyConten
   public static final String DATA_FILE_MSE_METRIC = "custom-data-file-mse";
   /** Metric name for delete file number. */
   public static final String DELETE_FILE_NUMBER_METRIC = 
"custom-delete-file-number";
+  /** TMS S0/S1 metric: average data file size in bytes. */
+  public static final String AVG_FILE_SIZE_METRIC = "custom-avg-file-size";
+  /** TMS S0/S1 metric: total data+delete file size in bytes. */
+  public static final String TOTAL_FILE_SIZE_METRIC = "custom-total-file-size";
+  /** TMS S0/S1 metric: total file count. */
+  public static final String FILE_NUMBER_METRIC = "custom-file-number";
   /** Default minimum threshold for data file MSE metric, equals (128 MiB * 
0.15)^2. */
   public static final long DEFAULT_MIN_DATA_FILE_MSE = 405323966463344L;
   /** Default minimum threshold for delete file number metric. */
diff --git 
a/api/src/main/java/org/apache/gravitino/policy/IcebergOrphanFileRemovalContent.java
 
b/api/src/main/java/org/apache/gravitino/policy/IcebergOrphanFileRemovalContent.java
index 6cb1b87b7b..ddfbfcc5ec 100644
--- 
a/api/src/main/java/org/apache/gravitino/policy/IcebergOrphanFileRemovalContent.java
+++ 
b/api/src/main/java/org/apache/gravitino/policy/IcebergOrphanFileRemovalContent.java
@@ -59,6 +59,10 @@ public class IcebergOrphanFileRemovalContent extends 
AbstractExecutablePolicyCon
   public static final long DEFAULT_OLDER_THAN_DAYS = 3;
   /** Default execution mode. */
   public static final boolean DEFAULT_DRY_RUN = false;
+  /** TMS S1 metric: orphan files removed (or found in dry-run). */
+  public static final String REMOVED_FILE_NUMBER_METRIC = 
"custom-removed-file-number";
+  /** TMS S1 metric: bytes of orphan files removed. */
+  public static final String REMOVED_FILE_SIZE_METRIC = 
"custom-removed-file-size";
 
   private final long olderThanDays;
   @Nullable private final String location;
diff --git 
a/api/src/main/java/org/apache/gravitino/policy/IcebergRewriteManifestsContent.java
 
b/api/src/main/java/org/apache/gravitino/policy/IcebergRewriteManifestsContent.java
index 395b94007e..a5aa1959f0 100644
--- 
a/api/src/main/java/org/apache/gravitino/policy/IcebergRewriteManifestsContent.java
+++ 
b/api/src/main/java/org/apache/gravitino/policy/IcebergRewriteManifestsContent.java
@@ -56,11 +56,35 @@ public class IcebergRewriteManifestsContent extends 
AbstractExecutablePolicyCont
       "avg_manifest_size_threshold_bytes";
   /** Default exclusive average size threshold in bytes. */
   public static final long DEFAULT_AVG_MANIFEST_SIZE_THRESHOLD_BYTES = 
8388608L;
+  /** S0 metric: total manifest count (TMS / in-job gate). */
+  public static final String MANIFEST_NUMBER_METRIC = "custom-manifest-number";
+  /** S0 metric: average manifest size in bytes (TMS / in-job gate). */
+  public static final String AVG_MANIFEST_SIZE_METRIC = 
"custom-avg-manifest-size";
+  /** S1 metric: manifests rewritten by the procedure. */
+  public static final String REWRITTEN_MANIFEST_NUMBER_METRIC = 
"custom-rewritten-manifest-number";
   /** Rule key for the requested partition spec ID; omission selects Iceberg's 
current default. */
   public static final String SPEC_ID = "spec_id";
   /** Rule key for caching option, or null for the Iceberg default. */
   public static final String USE_CACHING = "use_caching";
 
+  /**
+   * Default in-job / enqueue trigger: same thresholds as {@code 
ManifestRewriteStrategyHandler}
+   * (critical count, or warning count with small avg size).
+   */
+  private static final String TRIGGER_EXPR =
+      MANIFEST_NUMBER_METRIC
+          + " >= "
+          + MANIFEST_COUNT_CRITICAL
+          + " || ("
+          + MANIFEST_NUMBER_METRIC
+          + " >= "
+          + MANIFEST_COUNT_WARNING
+          + " && "
+          + AVG_MANIFEST_SIZE_METRIC
+          + " < "
+          + AVG_MANIFEST_SIZE_THRESHOLD_BYTES
+          + ")";
+
   private final Long manifestCountCritical;
   private final Long manifestCountWarning;
   private final Long avgManifestSizeThresholdBytes;
@@ -173,6 +197,7 @@ public class IcebergRewriteManifestsContent extends 
AbstractExecutablePolicyCont
     rules.put(MANIFEST_COUNT_CRITICAL, manifestCountCritical);
     rules.put(MANIFEST_COUNT_WARNING, manifestCountWarning);
     rules.put(AVG_MANIFEST_SIZE_THRESHOLD_BYTES, 
avgManifestSizeThresholdBytes);
+    rules.put(TRIGGER_EXPR_KEY, TRIGGER_EXPR);
     if (specId != null) {
       rules.put(SPEC_ID, specId);
     }
diff --git 
a/api/src/main/java/org/apache/gravitino/policy/IcebergSnapshotExpirationContent.java
 
b/api/src/main/java/org/apache/gravitino/policy/IcebergSnapshotExpirationContent.java
index d2cc6fd5ed..4b0c524538 100644
--- 
a/api/src/main/java/org/apache/gravitino/policy/IcebergSnapshotExpirationContent.java
+++ 
b/api/src/main/java/org/apache/gravitino/policy/IcebergSnapshotExpirationContent.java
@@ -65,6 +65,12 @@ public class IcebergSnapshotExpirationContent extends 
AbstractExecutablePolicyCo
   public static final long DEFAULT_RETAIN_LAST = 1;
   /** Default stream-results flag. */
   public static final boolean DEFAULT_STREAM_RESULTS = false;
+  /** TMS S0 metric: snapshot number before expire. */
+  public static final String SNAPSHOT_NUMBER_METRIC = "custom-snapshot-number";
+  /** TMS S1 metric: snapshots present in S0 but absent after expire. */
+  public static final String EXPIRED_SNAPSHOT_NUMBER_METRIC = 
"custom-expired-snapshot-number";
+  /** TMS S1 metric: content-file bytes present in S0 but absent after expire. 
*/
+  public static final String EXPIRED_FILE_SIZE_METRIC = 
"custom-expired-file-size";
 
   private final long olderThanDays;
   private final long retainLast;
diff --git 
a/api/src/test/java/org/apache/gravitino/policy/TestIcebergRewriteManifestsContent.java
 
b/api/src/test/java/org/apache/gravitino/policy/TestIcebergRewriteManifestsContent.java
index cd014c0fdf..23a256a934 100644
--- 
a/api/src/test/java/org/apache/gravitino/policy/TestIcebergRewriteManifestsContent.java
+++ 
b/api/src/test/java/org/apache/gravitino/policy/TestIcebergRewriteManifestsContent.java
@@ -31,6 +31,12 @@ class TestIcebergRewriteManifestsContent {
     Assertions.assertEquals(8388608L, content.avgManifestSizeThresholdBytes());
     Assertions.assertNull(content.specId());
     Assertions.assertNull(content.useCaching());
+    Assertions.assertTrue(
+        content
+            .rules()
+            .get(IcebergRewriteManifestsContent.TRIGGER_EXPR_KEY)
+            .toString()
+            .contains(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC));
     Assertions.assertEquals(content, PolicyContents.icebergRewriteManifests());
     Assertions.assertEquals(
         content.hashCode(), 
PolicyContents.icebergRewriteManifests().hashCode());
diff --git 
a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.java
 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.java
index cba61e0f95..914c19bcb3 100644
--- 
a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.java
+++ 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.java
@@ -18,16 +18,25 @@
  */
 package org.apache.gravitino.maintenance.jobs.iceberg;
 
+import com.google.common.annotations.VisibleForTesting;
 import java.util.Arrays;
 import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
+import javax.annotation.Nullable;
 import org.apache.gravitino.job.JobTemplateProvider;
 import org.apache.gravitino.job.SparkJobTemplate;
 import org.apache.gravitino.maintenance.jobs.BuiltInJob;
 import 
org.apache.gravitino.maintenance.optimizer.common.util.IcebergSparkConfigUtils;
+import org.apache.gravitino.policy.IcebergSnapshotExpirationContent;
+import org.apache.iceberg.Snapshot;
 import org.apache.spark.sql.Row;
 import org.apache.spark.sql.SparkSession;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Built-in job for expiring old snapshots from Iceberg tables.
@@ -35,11 +44,16 @@ import org.apache.spark.sql.SparkSession;
  * <p>This job leverages Iceberg's ExpireSnapshots procedure to remove 
snapshot metadata and
  * associated data files that are no longer needed, preventing unbounded 
metadata growth.
  */
-public class IcebergExpireSnapshotsJob implements BuiltInJob {
+public class IcebergExpireSnapshotsJob implements BuiltInJob, 
IcebergMaintenanceAction {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(IcebergExpireSnapshotsJob.class);
 
   private static final String NAME =
       JobTemplateProvider.BUILTIN_NAME_PREFIX + "iceberg-expire-snapshots";
-  private static final String VERSION = "v3";
+  private static final String VERSION = "v1";
+
+  /** Full table inventory captured before expire; used to compute S1 
set-diff. */
+  @Nullable private PreExpireData preExpireData;
 
   @Override
   public SparkJobTemplate jobTemplate() {
@@ -150,18 +164,10 @@ public class IcebergExpireSnapshotsJob implements 
BuiltInJob {
     IcebergJobUtils.requireIcebergSparkRuntimeOrExit(spark);
 
     try {
-      // Build the procedure call SQL
-      String sql =
-          buildProcedureCall(catalogName, tableIdentifier, olderThan, 
retainLast, streamResults);
-
-      System.out.println("Executing Iceberg expire_snapshots procedure: " + 
sql);
-
-      // Execute the procedure
-      Row[] results = (Row[]) spark.sql(sql).collect();
-
-      // Print results
-      if (results.length > 0) {
-        Row result = results[0];
+      List<Row> results =
+          execute(spark, catalogName, tableIdentifier, olderThan, retainLast, 
streamResults);
+      if (!results.isEmpty()) {
+        Row result = results.get(0);
         System.out.printf(
             "Expire Snapshots Results:%n"
                 + "  Deleted data files: %d%n"
@@ -180,6 +186,78 @@ public class IcebergExpireSnapshotsJob implements 
BuiltInJob {
     }
   }
 
+  /**
+   * Runs {@code expire_snapshots} on an existing Spark session. Shared by CLI 
{@link #main} and TMS
+   * {@link #executeAndCollectAfter}.
+   *
+   * @return procedure result rows
+   */
+  static List<Row> execute(
+      SparkSession spark,
+      String catalogName,
+      String tableIdentifier,
+      @Nullable String olderThan,
+      @Nullable String retainLast,
+      boolean streamResults) {
+    validateRetainLast(retainLast);
+    String sql =
+        buildProcedureCall(catalogName, tableIdentifier, olderThan, 
retainLast, streamResults);
+    LOG.info("Executing Iceberg expire_snapshots: {}", sql);
+    return spark.sql(sql).collectAsList();
+  }
+
+  @Override
+  public boolean hasBeforeMetrics() {
+    return true;
+  }
+
+  @Override
+  public TableSnapshotMetrics collectBeforeMetrics(
+      SparkSession spark, String catalogName, String tableIdentifier) {
+    long snapshotId = IcebergJobUtils.requireCurrentSnapshotId(spark, 
catalogName, tableIdentifier);
+    preExpireData = collectTableData(spark, catalogName, tableIdentifier);
+    Map<String, Object> payload = 
expireBeforeMetrics(preExpireData.snapshotCount());
+    return TableSnapshotMetrics.of(snapshotId, payload);
+  }
+
+  @Override
+  public boolean shouldCheckSnapshotDrift() {
+    return false;
+  }
+
+  @Override
+  public TableSnapshotMetrics executeAndCollectAfter(
+      SparkSession spark,
+      String catalogName,
+      String tableIdentifier,
+      Map<String, String> argsByName,
+      @Nullable TableSnapshotMetrics before) {
+    List<Row> results =
+        execute(
+            spark,
+            catalogName,
+            tableIdentifier,
+            
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("older-than")),
+            
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("retain-last")),
+            parseStreamResults(
+                
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("stream-results"))));
+    if (!results.isEmpty()) {
+      LOG.info(
+          "Expire snapshots deleted data/manifest/manifest-list files: 
{}/{}/{}",
+          results.get(0).getLong(0),
+          results.get(0).getLong(1),
+          results.get(0).getLong(2));
+    }
+    PreExpireData after = collectTableData(spark, catalogName, 
tableIdentifier);
+    PreExpireData beforeData = preExpireData == null ? after : preExpireData;
+    preExpireData = null;
+    return TableSnapshotMetrics.of(
+        IcebergJobUtils.currentSnapshotIdOrEmpty(spark, catalogName, 
tableIdentifier),
+        expireAfterMetrics(
+            snapshotsCleared(beforeData.snapshotIds(), after.snapshotIds()),
+            bytesReclaimed(beforeData.fileSizesByPath(), 
after.fileSizesByPath())));
+  }
+
   /**
    * Build the SQL CALL statement for the expire_snapshots procedure.
    *
@@ -333,4 +411,128 @@ public class IcebergExpireSnapshotsJob implements 
BuiltInJob {
   private static Map<String, String> buildSparkConfigs() {
     return IcebergSparkConfigUtils.buildTemplateSparkConfigs();
   }
+
+  // -------------------------------------------------------------------------
+  // TMS metrics helpers (not used by CLI {@link #main})
+  // -------------------------------------------------------------------------
+
+  /**
+   * Full table inventory before expire (all snapshot ids and reachable 
files). Used with a
+   * post-expire capture to compute S1 set-diff. Concurrent commits only add 
ids/paths to the after
+   * set; cleared/expired count ids/paths that disappeared. File sizes stay in 
memory for S1 and are
+   * not reported in S0 metrics.
+   */
+  @VisibleForTesting
+  static final class PreExpireData {
+    private final Set<Long> snapshotIds;
+    private final Map<String, Long> fileSizesByPath;
+
+    PreExpireData(Set<Long> snapshotIds, Map<String, Long> fileSizesByPath) {
+      this.snapshotIds = Collections.unmodifiableSet(new 
HashSet<>(snapshotIds));
+      this.fileSizesByPath = Collections.unmodifiableMap(new 
HashMap<>(fileSizesByPath));
+    }
+
+    Set<Long> snapshotIds() {
+      return snapshotIds;
+    }
+
+    Map<String, Long> fileSizesByPath() {
+      return fileSizesByPath;
+    }
+
+    long snapshotCount() {
+      return snapshotIds.size();
+    }
+  }
+
+  @VisibleForTesting
+  static Map<String, Object> expireBeforeMetrics(long snapshotNumber) {
+    Map<String, Object> metrics = new HashMap<>();
+    metrics.put(IcebergSnapshotExpirationContent.SNAPSHOT_NUMBER_METRIC, 
snapshotNumber);
+    return metrics;
+  }
+
+  @VisibleForTesting
+  static Map<String, Object> expireAfterMetrics(long expiredSnapshotNumber, 
long expiredFileSize) {
+    Map<String, Object> metrics = new HashMap<>();
+    metrics.put(
+        IcebergSnapshotExpirationContent.EXPIRED_SNAPSHOT_NUMBER_METRIC, 
expiredSnapshotNumber);
+    metrics.put(IcebergSnapshotExpirationContent.EXPIRED_FILE_SIZE_METRIC, 
expiredFileSize);
+    return metrics;
+  }
+
+  @VisibleForTesting
+  static long snapshotsCleared(Set<Long> beforeSnapshotIds, Set<Long> 
afterSnapshotIds) {
+    long cleared = 0L;
+    for (Long snapshotId : beforeSnapshotIds) {
+      if (!afterSnapshotIds.contains(snapshotId)) {
+        cleared++;
+      }
+    }
+    return cleared;
+  }
+
+  @VisibleForTesting
+  static long bytesReclaimed(Map<String, Long> beforeFileSizes, Map<String, 
Long> afterFileSizes) {
+    long bytes = 0L;
+    for (Map.Entry<String, Long> entry : beforeFileSizes.entrySet()) {
+      if (!afterFileSizes.containsKey(entry.getKey())) {
+        bytes += entry.getValue() == null ? 0L : entry.getValue();
+      }
+    }
+    return bytes;
+  }
+
+  /**
+   * Collects full table data (snapshot ids + reachable files) for TMS 
set-diff. CLI entry points
+   * never call this.
+   *
+   * <p>Uses {@code all_files} metadata SQL (same style as compaction's {@code 
files} SQL) plus
+   * Iceberg snapshot ids.
+   */
+  @VisibleForTesting
+  static PreExpireData collectTableData(
+      SparkSession spark, String catalogName, String tableIdentifier) {
+    Set<Long> snapshotIds = new HashSet<>();
+    for (Snapshot snapshot :
+        IcebergJobUtils.loadIcebergTable(spark, catalogName, 
tableIdentifier).snapshots()) {
+      snapshotIds.add(snapshot.snapshotId());
+    }
+    String sql = buildReachableContentFilesSql(catalogName, tableIdentifier);
+    List<Row> rows = spark.sql(sql).collectAsList();
+    Map<String, Long> fileSizesByPath = new HashMap<>(rows.size());
+    for (Row row : rows) {
+      String path = row.getAs("file-path");
+      if (path == null || path.isEmpty()) {
+        continue;
+      }
+      Number size = row.getAs("file-size");
+      fileSizesByPath.put(path, size == null ? 0L : size.longValue());
+    }
+    return new PreExpireData(snapshotIds, fileSizesByPath);
+  }
+
+  /**
+   * Distinct content files still referenced by any tracked snapshot. {@code 
GROUP BY file_path}
+   * avoids double-counting files that appear in multiple snapshots.
+   */
+  @VisibleForTesting
+  static String buildReachableContentFilesSql(String catalogName, String 
tableIdentifier) {
+    String[] levels = tableIdentifier.split("\\.");
+    if (levels.length != 2) {
+      throw new IllegalArgumentException(
+          "table_identifier must use schema.table format, but got: " + 
tableIdentifier);
+    }
+    String metadataTable =
+        IcebergJobUtils.escapeSqlIdentifier(catalogName)
+            + "."
+            + IcebergJobUtils.escapeSqlIdentifier(levels[0])
+            + "."
+            + IcebergJobUtils.escapeSqlIdentifier(levels[1])
+            + "."
+            + IcebergJobUtils.escapeSqlIdentifier("all_files");
+    return "SELECT file_path AS `file-path`, MAX(file_size_in_bytes) AS 
`file-size` FROM "
+        + metadataTable
+        + " GROUP BY file_path";
+  }
 }
diff --git 
a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergJobUtils.java
 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergJobUtils.java
index 0ac789d174..3236de0c55 100644
--- 
a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergJobUtils.java
+++ 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergJobUtils.java
@@ -29,6 +29,9 @@ import java.util.regex.Pattern;
 import javax.annotation.Nullable;
 import org.apache.commons.lang3.StringUtils;
 import 
org.apache.gravitino.maintenance.optimizer.common.util.IcebergSparkConfigUtils;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.spark.Spark3Util;
 import org.apache.spark.SparkConf;
 import org.apache.spark.sql.SparkSession;
 import org.slf4j.Logger;
@@ -37,8 +40,8 @@ import org.slf4j.LoggerFactory;
 /**
  * Shared utility methods for Iceberg maintenance jobs.
  *
- * <p>Provides SQL escaping, argument parsing, Spark configuration utilities, 
and classpath checks
- * used by built-in Iceberg Spark jobs.
+ * <p>Provides SQL escaping, argument parsing, Spark configuration utilities, 
table/snapshot
+ * helpers, and classpath checks used by built-in Iceberg Spark jobs.
  */
 public final class IcebergJobUtils {
 
@@ -292,6 +295,65 @@ public final class IcebergJobUtils {
     }
   }
 
+  /**
+   * Loads an Iceberg table via Spark.
+   *
+   * <p>Catches checked {@link Exception} (not only Spark {@code 
NoSuchTableException}) so the
+   * Gravitino server can load callers without Spark catalyst on the classpath.
+   *
+   * @param spark active Spark session
+   * @param catalogName Iceberg catalog name
+   * @param tableIdentifier fully qualified table name
+   * @return loaded Iceberg table
+   */
+  public static Table loadIcebergTable(
+      SparkSession spark, String catalogName, String tableIdentifier) {
+    try {
+      // Force CatalogManager to load the named catalog first. 
Spark3Util.catalogAndIdentifier
+      // swallows load failures and falls back to the session catalog 
(spark_catalog), which then
+      // fails with REQUIRES_SINGLE_PART_NAMESPACE and hides the real 
REST/config error.
+      spark.sessionState().catalogManager().catalog(catalogName);
+      return Spark3Util.loadIcebergTable(
+          spark, String.format("%s.%s", catalogName, tableIdentifier));
+    } catch (RuntimeException e) {
+      throw e;
+    } catch (Exception e) {
+      throw new IllegalStateException(
+          "Failed to load Iceberg table for " + catalogName + "." + 
tableIdentifier, e);
+    }
+  }
+
+  /**
+   * @param spark active Spark session
+   * @param catalogName Iceberg catalog name
+   * @param tableIdentifier fully qualified table name
+   * @return current snapshot id
+   * @throws IllegalStateException when the table has no current snapshot
+   */
+  public static long requireCurrentSnapshotId(
+      SparkSession spark, String catalogName, String tableIdentifier) {
+    Snapshot snapshot = loadIcebergTable(spark, catalogName, 
tableIdentifier).currentSnapshot();
+    if (snapshot == null) {
+      throw new IllegalStateException(
+          "Iceberg table has no current snapshot: " + catalogName + "." + 
tableIdentifier);
+    }
+    return snapshot.snapshotId();
+  }
+
+  /**
+   * After expiry/orphan, HEAD may briefly be empty; report {@code -1} in that 
case.
+   *
+   * @param spark active Spark session
+   * @param catalogName Iceberg catalog name
+   * @param tableIdentifier fully qualified table name
+   * @return current snapshot id, or {@code -1} when HEAD is empty
+   */
+  public static long currentSnapshotIdOrEmpty(
+      SparkSession spark, String catalogName, String tableIdentifier) {
+    Snapshot snapshot = loadIcebergTable(spark, catalogName, 
tableIdentifier).currentSnapshot();
+    return snapshot == null ? -1L : snapshot.snapshotId();
+  }
+
   /** Visible for unit tests that assert the missing-class error message. */
   static void requireClassForTest(String className, String description) {
     requireClass(className, description);
diff --git 
a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceAction.java
 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceAction.java
new file mode 100644
index 0000000000..f5363426b0
--- /dev/null
+++ 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceAction.java
@@ -0,0 +1,84 @@
+/*
+ * 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.
+ */
+package org.apache.gravitino.maintenance.jobs.iceberg;
+
+import java.util.Map;
+import javax.annotation.Nullable;
+import org.apache.spark.sql.SparkSession;
+
+/**
+ * TMS maintenance contract implemented by the four Iceberg built-in jobs.
+ *
+ * <p>CLI entry points keep their typed {@code execute} / {@code main} APIs. 
This interface is the
+ * shared orchestration surface used by {@link IcebergMaintenanceJob}.
+ *
+ * <p>Methods are declared in pipeline order: gate → collect S0 → drift check 
→ execute + S1.
+ */
+public interface IcebergMaintenanceAction {
+
+  /**
+   * Whether this action has an S0 before-metrics step. Orphan cleanup returns 
{@code false}.
+   *
+   * @return {@code true} when {@link #collectBeforeMetrics} should run
+   */
+  boolean hasBeforeMetrics();
+
+  /**
+   * Collects S0 before-metrics. Must not be called when {@link 
#hasBeforeMetrics()} is {@code
+   * false}.
+   *
+   * @param spark active Spark session
+   * @param catalogName Iceberg catalog name
+   * @param tableIdentifier fully qualified table name
+   * @return before-metrics sample
+   */
+  TableSnapshotMetrics collectBeforeMetrics(
+      SparkSession spark, String catalogName, String tableIdentifier);
+
+  /**
+   * Whether a changed HEAD snapshot after S0 should skip the procedure. 
Compaction and manifest
+   * rewrite return {@code true}; expiry and orphan cleanup return {@code 
false}.
+   *
+   * @return {@code true} when snapshot drift should skip execution
+   */
+  boolean shouldCheckSnapshotDrift();
+
+  /**
+   * Runs the Iceberg procedure and returns S1 after-metrics.
+   *
+   * <p>Kept as one method because S1 sources differ by type (table inventory, 
procedure rows, or
+   * in-procedure counters); splitting would need an extra outcome carrier.
+   *
+   * @param spark active Spark session
+   * @param catalogName Iceberg catalog name
+   * @param tableIdentifier fully qualified table name
+   * @param argsByName unresolved job arguments (placeholders already present 
as raw values)
+   * @param before S0 sample when {@link #hasBeforeMetrics()} is {@code true}; 
otherwise {@code
+   *     null}
+   * @return after-metrics sample
+   * @throws Exception if the procedure fails
+   */
+  TableSnapshotMetrics executeAndCollectAfter(
+      SparkSession spark,
+      String catalogName,
+      String tableIdentifier,
+      Map<String, String> argsByName,
+      @Nullable TableSnapshotMetrics before)
+      throws Exception;
+}
diff --git 
a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceJob.java
 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceJob.java
index 0f1d2752a0..5b31d4d997 100644
--- 
a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceJob.java
+++ 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceJob.java
@@ -20,10 +20,12 @@ package org.apache.gravitino.maintenance.jobs.iceberg;
 
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.core.type.TypeReference;
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.ImmutableList;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
+import java.util.EnumMap;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
@@ -40,21 +42,22 @@ import 
org.apache.gravitino.maintenance.dto.requests.MaintenanceActionMetricsReq
 import org.apache.gravitino.maintenance.jobs.BuiltInJob;
 import org.apache.gravitino.maintenance.jobs.MaintenanceActionHttpClient;
 import 
org.apache.gravitino.maintenance.optimizer.common.util.IcebergSparkConfigUtils;
-import org.apache.gravitino.policy.IcebergDataCompactionContent;
-import org.apache.iceberg.Snapshot;
-import org.apache.iceberg.Table;
-import org.apache.iceberg.spark.Spark3Util;
-import org.apache.spark.sql.Row;
 import org.apache.spark.sql.SparkSession;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * TMS Spark job: sample before-metrics → gate → run Iceberg procedure → close 
soft slot.
+ * TMS Spark job: collect before-metrics → gate → execute procedure → report 
after-metrics → finish
+ * the maintenance action.
  *
  * <p>Started only from the built-in template (cron or commit-chain). {@code 
maintenance_types} is
  * one type or a comma-separated chain; {@code policy_ids} / {@code 
action_ids} align 1:1 with those
- * types. Soft-slot HTTP callbacks use {@code action_ids}.
+ * types. {@code action_ids} identify the TMS actions this job must finish 
when done.
+ *
+ * <p>{@code metricsJson} carries only metric fields (no {@code 
maintenanceType} / {@code
+ * snapshotId}; those live on the action/policy and {@code 
table_snapshot_metrics.snapshot_id}).
+ * Snapshot drift skips only compaction and manifest rewrite. Orphan cleanup 
reports after-metrics
+ * only.
  */
 public class IcebergMaintenanceJob implements BuiltInJob {
 
@@ -76,7 +79,7 @@ public class IcebergMaintenanceJob implements BuiltInJob {
   /** JobConf: policy ids parallel to {@link #MAINTENANCE_TYPES_KEY}. */
   public static final String POLICY_IDS_KEY = "policy_ids";
 
-  /** JobConf: soft-slot action ids parallel to {@link #POLICY_IDS_KEY}. */
+  /** JobConf: TMS action ids parallel to {@link #POLICY_IDS_KEY}. */
   public static final String ACTION_IDS_KEY = "action_ids";
 
   /** Values accepted in {@code maintenance_types}. */
@@ -99,6 +102,13 @@ public class IcebergMaintenanceJob implements BuiltInJob {
       return wireName;
     }
 
+    /**
+     * @return the built-in job that implements this maintenance type
+     */
+    public IcebergMaintenanceAction action() {
+      return ACTIONS.get(this);
+    }
+
     /**
      * @param raw one segment from {@code maintenance_types}
      * @return parsed type
@@ -121,11 +131,23 @@ public class IcebergMaintenanceJob implements BuiltInJob {
     }
   }
 
+  private static final Map<MaintenanceType, IcebergMaintenanceAction> ACTIONS 
= createActions();
+
+  private static Map<MaintenanceType, IcebergMaintenanceAction> 
createActions() {
+    Map<MaintenanceType, IcebergMaintenanceAction> actions = new 
EnumMap<>(MaintenanceType.class);
+    actions.put(MaintenanceType.REWRITE_DATA_FILES, new 
IcebergRewriteDataFilesJob());
+    actions.put(MaintenanceType.REWRITE_MANIFESTS, new 
IcebergRewriteManifestsJob());
+    actions.put(MaintenanceType.EXPIRE_SNAPSHOTS, new 
IcebergExpireSnapshotsJob());
+    actions.put(MaintenanceType.REMOVE_ORPHAN_FILES, new 
IcebergRemoveOrphanFilesJob());
+    return Collections.unmodifiableMap(actions);
+  }
+
   @Override
   public SparkJobTemplate jobTemplate() {
     return SparkJobTemplate.builder()
         .withName(NAME)
-        .withComment("TMS Iceberg maintenance (before-metrics gate, procedure, 
finish soft slot)")
+        .withComment(
+            "TMS Iceberg maintenance (before metrics, gate, procedure, after 
metrics, finish)")
         .withExecutable(resolveExecutable(IcebergMaintenanceJob.class))
         .withClassName(IcebergMaintenanceJob.class.getName())
         .withArguments(templateArguments())
@@ -181,60 +203,30 @@ public class IcebergMaintenanceJob implements BuiltInJob {
     String sparkConfJson =
         
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("spark-conf"));
     if (sparkConfJson != null && !sparkConfJson.isEmpty()) {
-      
IcebergJobUtils.parseCustomSparkConfigs(sparkConfJson).forEach(sparkBuilder::config);
+      Map<String, String> sparkConfigs =
+          new 
HashMap<>(IcebergJobUtils.parseCustomSparkConfigs(sparkConfJson));
+      ensureIcebergCatalogImpl(sparkConfigs);
+      sparkConfigs.forEach(sparkBuilder::config);
     }
 
     try (SparkSession spark = sparkBuilder.getOrCreate()) {
       IcebergJobUtils.requireIcebergSparkRuntimeOrExit(spark);
       try (MaintenanceActionHttpClient client =
           MaintenanceActionHttpClient.fromUpdaterOptions(updaterOptions)) {
-        // Close every soft slot even if a later type/table never runs.
-        Set<String> closedSlots = new HashSet<>();
+        // TMS opens one action per (table, policy) before this job runs; 
finish each when done.
+        Set<String> finishedTablePolicyKeys = new HashSet<>();
         try {
           for (TargetTable table : tables) {
             for (int i = 0; i < types.size(); i++) {
               MaintenanceType type = types.get(i);
               long policyId = policyIds.get(i);
               long actionId = actionIds.get(i);
-              String slot = table.tableId + ":" + policyId;
+              String tablePolicyKey = table.tableId + ":" + policyId;
               try {
-                BeforeSample before =
-                    sampleBefore(spark, table.catalogName, 
table.tableIdentifier, type);
-                if (!tryReportBeforeMetrics(client, actionId, table.tableId, 
policyId, before)) {
-                  LOG.info(
-                      "TMS type {} stopped for action_id {} table {} policy 
{}: before-metrics"
-                          + " failed (abandoned or unbound)",
-                      type.wireName,
-                      actionId,
-                      table.tableId,
-                      policyId);
-                  continue;
-                }
-                if (before.snapshotId != before.headSnapshotId) {
-                  LOG.info(
-                      "TMS type {} skipped for action_id {} table {} policy 
{}: snapshot drifted"
-                          + " (sampled={} head={})",
-                      type.wireName,
-                      actionId,
-                      table.tableId,
-                      policyId,
-                      before.snapshotId,
-                      before.headSnapshotId);
-                  continue;
-                }
-                if (!MaintenanceTriggerGate.shouldMaintain(type, argsByName, 
before.metricsJson)) {
-                  LOG.info(
-                      "TMS type {} skipped for action_id {} table {} policy 
{}: trigger-expr skip",
-                      type.wireName,
-                      actionId,
-                      table.tableId,
-                      policyId);
-                  continue;
-                }
-                runProcedure(spark, type, table.catalogName, 
table.tableIdentifier, argsByName);
+                runMaintenanceForType(spark, client, type, table, policyId, 
actionId, argsByName);
               } finally {
-                closeSoftSlot(client, actionId, table.tableId, policyId);
-                closedSlots.add(slot);
+                finishMaintenanceAction(client, actionId, table.tableId, 
policyId);
+                finishedTablePolicyKeys.add(tablePolicyKey);
               }
             }
           }
@@ -246,9 +238,9 @@ public class IcebergMaintenanceJob implements BuiltInJob {
           for (TargetTable table : tables) {
             for (int i = 0; i < policyIds.size(); i++) {
               long policyId = policyIds.get(i);
-              long actionId = actionIds.get(i);
-              if (!closedSlots.contains(table.tableId + ":" + policyId)) {
-                closeSoftSlot(client, actionId, table.tableId, policyId);
+              String tablePolicyKey = table.tableId + ":" + policyId;
+              if (!finishedTablePolicyKeys.contains(tablePolicyKey)) {
+                finishMaintenanceAction(client, actionIds.get(i), 
table.tableId, policyId);
               }
             }
           }
@@ -257,6 +249,73 @@ public class IcebergMaintenanceJob implements BuiltInJob {
     }
   }
 
+  /**
+   * Shared S0 → gate → procedure → S1 pipeline. Types without S0 (orphan 
cleanup) skip the before
+   * half and still report after-metrics.
+   */
+  private static void runMaintenanceForType(
+      SparkSession spark,
+      MaintenanceActionHttpClient client,
+      MaintenanceType type,
+      TargetTable table,
+      long policyId,
+      long actionId,
+      Map<String, String> argsByName)
+      throws Exception {
+    IcebergMaintenanceAction action = type.action();
+    TableSnapshotMetrics before = null;
+    if (action.hasBeforeMetrics()) {
+      before = action.collectBeforeMetrics(spark, table.catalogName, 
table.tableIdentifier);
+      if (!reportBeforeMetricsOrStop(client, actionId, table.tableId, 
policyId, before)) {
+        LOG.info(
+            "TMS type {} stopped for action_id {} table {} policy {}: 
before-metrics failed"
+                + " (abandoned or unbound)",
+            type.wireName,
+            actionId,
+            table.tableId,
+            policyId);
+        return;
+      }
+      long headSnapshotId =
+          IcebergJobUtils.requireCurrentSnapshotId(spark, table.catalogName, 
table.tableIdentifier);
+      if (action.shouldCheckSnapshotDrift() && before.snapshotId() != 
headSnapshotId) {
+        LOG.info(
+            "TMS type {} skipped for action_id {} table {} policy {}: snapshot 
drifted"
+                + " (sampled={} head={})",
+            type.wireName,
+            actionId,
+            table.tableId,
+            policyId,
+            before.snapshotId(),
+            headSnapshotId);
+        return;
+      }
+      if (!MaintenanceTriggerGate.shouldMaintain(type, argsByName, 
before.metricsJson())) {
+        LOG.info(
+            "TMS type {} skipped for action_id {} table {} policy {}: 
trigger-expr skip",
+            type.wireName,
+            actionId,
+            table.tableId,
+            policyId);
+        return;
+      }
+    }
+
+    TableSnapshotMetrics after =
+        action.executeAndCollectAfter(
+            spark, table.catalogName, table.tableIdentifier, argsByName, 
before);
+    reportAfterMetrics(client, actionId, table.tableId, policyId, after);
+  }
+
+  /**
+   * Snapshot drift skip applies only to compaction and manifest rewrite 
(inventory-sensitive).
+   * Expiry and orphan cleanup always proceed past HEAD drift.
+   */
+  @VisibleForTesting
+  static boolean shouldCheckSnapshotDrift(MaintenanceType type) {
+    return type.action().shouldCheckSnapshotDrift();
+  }
+
   private static List<TargetTable> parseTables(@Nullable String tablesJson) {
     if (tablesJson == null || tablesJson.trim().isEmpty()) {
       throw new IllegalArgumentException(
@@ -351,186 +410,7 @@ public class IcebergMaintenanceJob implements BuiltInJob {
     return ids;
   }
 
-  private static void runProcedure(
-      SparkSession spark,
-      MaintenanceType type,
-      String catalogName,
-      String tableIdentifier,
-      Map<String, String> argsByName)
-      throws Exception {
-    switch (type) {
-      case REWRITE_DATA_FILES:
-        {
-          String strategy = 
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("strategy"));
-          if (strategy == null || strategy.isEmpty()) {
-            strategy = "binpack";
-          }
-          String sql =
-              IcebergRewriteDataFilesJob.buildProcedureCall(
-                  catalogName,
-                  tableIdentifier,
-                  strategy,
-                  
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("sort-order")),
-                  
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("where")),
-                  
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("options")));
-          LOG.info("Executing TMS rewrite_data_files: {}", sql);
-          spark.sql(sql).collect();
-          break;
-        }
-      case REWRITE_MANIFESTS:
-        {
-          IcebergRewriteManifestsJob.validateUseCaching(
-              
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("use-caching")));
-          IcebergRewriteManifestsJob.validateSpecId(
-              
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("spec-id")));
-          String sql =
-              IcebergRewriteManifestsJob.buildProcedureCall(
-                  catalogName,
-                  tableIdentifier,
-                  
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("use-caching")),
-                  
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("spec-id")));
-          LOG.info("Executing TMS rewrite_manifests: {}", sql);
-          spark.sql(sql).collect();
-          break;
-        }
-      case EXPIRE_SNAPSHOTS:
-        {
-          String retainLast =
-              
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("retain-last"));
-          IcebergExpireSnapshotsJob.validateRetainLast(retainLast);
-          boolean streamResults =
-              IcebergExpireSnapshotsJob.parseStreamResults(
-                  
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("stream-results")));
-          String sql =
-              IcebergExpireSnapshotsJob.buildProcedureCall(
-                  catalogName,
-                  tableIdentifier,
-                  
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("older-than")),
-                  retainLast,
-                  streamResults);
-          LOG.info("Executing TMS expire_snapshots: {}", sql);
-          Row[] results = (Row[]) spark.sql(sql).collect();
-          if (results.length > 0) {
-            LOG.info(
-                "Expire snapshots deleted data/manifest/manifest-list files: 
{}/{}/{}",
-                results[0].getLong(0),
-                results[0].getLong(1),
-                results[0].getLong(2));
-          }
-          break;
-        }
-      case REMOVE_ORPHAN_FILES:
-        {
-          Map<String, String> orphanOpts = new HashMap<>();
-          orphanOpts.put("catalog", catalogName);
-          orphanOpts.put("table", tableIdentifier);
-          putIfPresent(orphanOpts, "older-than", argsByName.get("older-than"));
-          putIfPresent(orphanOpts, "location", argsByName.get("location"));
-          putIfPresent(orphanOpts, "dry-run", argsByName.get("dry-run"));
-          IcebergRemoveOrphanFilesJob.execute(spark, orphanOpts);
-          break;
-        }
-      default:
-        throw new IllegalStateException("Unhandled maintenance type: " + type);
-    }
-  }
-
-  /**
-   * Samples snapshot + metrics for the before-metrics gate. Re-reads HEAD 
after metrics so drift
-   * can be detected.
-   */
-  private static BeforeSample sampleBefore(
-      SparkSession spark, String catalogName, String tableIdentifier, 
MaintenanceType type) {
-    long snapshotId = currentSnapshotId(spark, catalogName, tableIdentifier);
-    Map<String, Object> payload = new HashMap<>();
-    payload.put("maintenanceType", type.wireName());
-    payload.put("snapshotId", snapshotId);
-    if (type == MaintenanceType.REWRITE_DATA_FILES) {
-      payload.putAll(collectCompactionMetrics(spark, catalogName, 
tableIdentifier));
-    }
-    long headSnapshotId = currentSnapshotId(spark, catalogName, 
tableIdentifier);
-    try {
-      return new BeforeSample(
-          snapshotId, headSnapshotId, 
JsonUtils.anyFieldMapper().writeValueAsString(payload));
-    } catch (JsonProcessingException e) {
-      throw new IllegalStateException("Failed to serialize metrics JSON", e);
-    }
-  }
-
-  /**
-   * Compaction metrics from the Iceberg files metadata table (same formulas 
as {@link
-   * IcebergUpdateStatsAndMetricsJob}). Partitioned tables use max partition 
MSE and sum of delete
-   * files so any hot partition can trip {@code trigger-expr}.
-   */
-  private static Map<String, Object> collectCompactionMetrics(
-      SparkSession spark, String catalogName, String tableIdentifier) {
-    boolean partitioned =
-        IcebergUpdateStatsAndMetricsJob.isPartitionedTable(spark, catalogName, 
tableIdentifier);
-    if (partitioned) {
-      String sql =
-          IcebergUpdateStatsAndMetricsJob.buildPartitionStatsSql(catalogName, 
tableIdentifier);
-      Row[] rows = (Row[]) spark.sql(sql).collect();
-      Map<String, Object> metrics = new HashMap<>();
-      double maxMse = 0D;
-      long deleteFiles = 0L;
-      for (Row row : rows) {
-        maxMse = Math.max(maxMse, numberAsDouble(row, "data-file-mse"));
-        deleteFiles += numberAsLong(row, "delete-file-number");
-      }
-      metrics.put(IcebergDataCompactionContent.DATA_FILE_MSE_METRIC, maxMse);
-      metrics.put(IcebergDataCompactionContent.DELETE_FILE_NUMBER_METRIC, 
deleteFiles);
-      return metrics;
-    }
-
-    String sql = 
IcebergUpdateStatsAndMetricsJob.buildTableStatsSql(catalogName, 
tableIdentifier);
-    Row[] rows = (Row[]) spark.sql(sql).collect();
-    Map<String, Object> metrics = new HashMap<>();
-    if (rows.length == 0) {
-      metrics.put(IcebergDataCompactionContent.DATA_FILE_MSE_METRIC, 0D);
-      metrics.put(IcebergDataCompactionContent.DELETE_FILE_NUMBER_METRIC, 0L);
-      return metrics;
-    }
-    Row row = rows[0];
-    metrics.put(
-        IcebergDataCompactionContent.DATA_FILE_MSE_METRIC, numberAsDouble(row, 
"data-file-mse"));
-    metrics.put(
-        IcebergDataCompactionContent.DELETE_FILE_NUMBER_METRIC,
-        numberAsLong(row, "delete-file-number"));
-    return metrics;
-  }
-
-  private static double numberAsDouble(Row row, String field) {
-    Number number = row.getAs(field);
-    return number == null ? 0D : number.doubleValue();
-  }
-
-  private static long numberAsLong(Row row, String field) {
-    Number number = row.getAs(field);
-    return number == null ? 0L : number.longValue();
-  }
-
-  private static long currentSnapshotId(
-      SparkSession spark, String catalogName, String tableIdentifier) {
-    // Catch Exception (not Spark NoSuchTableException) so the Gravitino 
server can load this class
-    // without Spark catalyst on the classpath.
-    try {
-      Table table =
-          Spark3Util.loadIcebergTable(spark, String.format("%s.%s", 
catalogName, tableIdentifier));
-      Snapshot snapshot = table.currentSnapshot();
-      if (snapshot == null) {
-        throw new IllegalStateException(
-            "Iceberg table has no current snapshot: " + catalogName + "." + 
tableIdentifier);
-      }
-      return snapshot.snapshotId();
-    } catch (RuntimeException e) {
-      throw e;
-    } catch (Exception e) {
-      throw new IllegalStateException(
-          "Failed to load Iceberg snapshot for " + catalogName + "." + 
tableIdentifier, e);
-    }
-  }
-
-  private static void closeSoftSlot(
+  private static void finishMaintenanceAction(
       MaintenanceActionHttpClient client, long actionId, long tableId, long 
policyId) {
     try {
       client.finish(actionId, new MaintenanceActionFinishRequest(tableId, 
policyId));
@@ -545,23 +425,23 @@ public class IcebergMaintenanceJob implements BuiltInJob {
   }
 
   /**
-   * Reports before-metrics. Failure means the soft slot is abandoned/unbound 
— do not run the
+   * Reports before-metrics. Failure means the TMS action is abandoned/unbound 
— do not run the
    * procedure.
    */
-  private static boolean tryReportBeforeMetrics(
+  private static boolean reportBeforeMetricsOrStop(
       MaintenanceActionHttpClient client,
       long actionId,
       long tableId,
       long policyId,
-      BeforeSample sample) {
-    if (sample.metricsJson == null || sample.metricsJson.trim().isEmpty()) {
+      TableSnapshotMetrics sample) {
+    if (sample.metricsJson() == null || sample.metricsJson().trim().isEmpty()) 
{
       return false;
     }
     try {
       client.reportBeforeMetrics(
           actionId,
           new MaintenanceActionMetricsRequest(
-              tableId, policyId, sample.snapshotId, sample.metricsJson));
+              tableId, policyId, sample.snapshotId(), sample.metricsJson()));
       return true;
     } catch (Exception e) {
       LOG.warn(
@@ -569,12 +449,42 @@ public class IcebergMaintenanceJob implements BuiltInJob {
           actionId,
           tableId,
           policyId,
-          sample.snapshotId,
+          sample.snapshotId(),
           e.toString());
       return false;
     }
   }
 
+  private static void reportAfterMetrics(
+      MaintenanceActionHttpClient client,
+      long actionId,
+      long tableId,
+      long policyId,
+      TableSnapshotMetrics sample) {
+    if (sample.metricsJson() == null || sample.metricsJson().trim().isEmpty()) 
{
+      LOG.warn(
+          "TMS after metrics skipped for action_id {} table {} policy {}: 
empty metrics JSON",
+          actionId,
+          tableId,
+          policyId);
+      return;
+    }
+    try {
+      client.reportAfterMetrics(
+          actionId,
+          new MaintenanceActionMetricsRequest(
+              tableId, policyId, sample.snapshotId(), sample.metricsJson()));
+    } catch (Exception e) {
+      LOG.warn(
+          "TMS after metrics failed for action_id {} table {} policy {} 
snapshot {}: {}",
+          actionId,
+          tableId,
+          policyId,
+          sample.snapshotId(),
+          e.toString());
+    }
+  }
+
   private static Map<String, String> parseUpdaterOptions(@Nullable String 
json) {
     if (json == null || json.trim().isEmpty()) {
       return Collections.emptyMap();
@@ -588,11 +498,34 @@ public class IcebergMaintenanceJob implements BuiltInJob {
     }
   }
 
-  private static void putIfPresent(Map<String, String> target, String key, 
@Nullable String raw) {
-    String value = IcebergJobUtils.nullIfUnresolvedPlaceholder(raw);
-    if (value != null && !value.isEmpty()) {
-      target.put(key, value);
+  /**
+   * Ensures {@code spark.sql.catalog.<name>} points at Iceberg {@code 
SparkCatalog} whenever nested
+   * catalog connection keys are present. Needed because TMS schedule {@code 
spark_conf} may only
+   * carry {@code .type}/{@code .uri}/{@code .warehouse}.
+   */
+  private static void ensureIcebergCatalogImpl(Map<String, String> 
sparkConfigs) {
+    String prefix = "spark.sql.catalog.";
+    Set<String> catalogs = new HashSet<>();
+    for (String key : sparkConfigs.keySet()) {
+      if (!key.startsWith(prefix)) {
+        continue;
+      }
+      String rest = key.substring(prefix.length());
+      int dot = rest.indexOf('.');
+      if (dot <= 0) {
+        continue;
+      }
+      String prop = rest.substring(dot + 1);
+      if ("type".equals(prop) || "uri".equals(prop) || 
"warehouse".equals(prop)) {
+        catalogs.add(rest.substring(0, dot));
+      }
+    }
+    for (String catalog : catalogs) {
+      sparkConfigs.putIfAbsent(prefix + catalog, 
"org.apache.iceberg.spark.SparkCatalog");
+      sparkConfigs.putIfAbsent("spark.sql.defaultCatalog", catalog);
     }
+    sparkConfigs.putIfAbsent(
+        "spark.sql.extensions", 
IcebergSparkConfigUtils.ICEBERG_SPARK_EXTENSIONS);
   }
 
   private static List<String> templateArguments() {
@@ -647,17 +580,4 @@ public class IcebergMaintenanceJob implements BuiltInJob {
       this.tableIdentifier = tableIdentifier;
     }
   }
-
-  /** Before-metrics sample: snapshot at sample time, HEAD after metrics, and 
metrics JSON. */
-  private static final class BeforeSample {
-    private final long snapshotId;
-    private final long headSnapshotId;
-    private final String metricsJson;
-
-    private BeforeSample(long snapshotId, long headSnapshotId, String 
metricsJson) {
-      this.snapshotId = snapshotId;
-      this.headSnapshotId = headSnapshotId;
-      this.metricsJson = metricsJson;
-    }
-  }
 }
diff --git 
a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java
 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java
index 3c2e7f4e5d..0ad464cbcb 100644
--- 
a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java
+++ 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java
@@ -21,15 +21,18 @@ package org.apache.gravitino.maintenance.jobs.iceberg;
 import static 
org.apache.gravitino.maintenance.optimizer.common.util.OrphanFileLocationUtils.normalizeLocation;
 import static org.apache.spark.sql.functions.lit;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Preconditions;
 import java.io.IOException;
 import java.net.URI;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
-import java.util.Iterator;
+import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.stream.Stream;
@@ -39,20 +42,52 @@ import org.apache.gravitino.job.SparkJobTemplate;
 import org.apache.gravitino.maintenance.jobs.BuiltInJob;
 import 
org.apache.gravitino.maintenance.optimizer.common.util.IcebergSparkConfigUtils;
 import 
org.apache.gravitino.maintenance.optimizer.common.util.OrphanFileLocationUtils;
+import org.apache.gravitino.policy.IcebergOrphanFileRemovalContent;
 import org.apache.iceberg.Table;
-import org.apache.iceberg.spark.Spark3Util;
-import org.apache.spark.sql.AnalysisException;
 import org.apache.spark.sql.Row;
 import org.apache.spark.sql.SparkSession;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-/** Removes unreferenced Iceberg files after validating the requested scan 
location. */
-public class IcebergRemoveOrphanFilesJob implements BuiltInJob {
+/**
+ * Built-in job for removing unreferenced Iceberg files after validating the 
requested scan
+ * location.
+ */
+public class IcebergRemoveOrphanFilesJob implements BuiltInJob, 
IcebergMaintenanceAction {
+
   private static final Logger LOG = 
LoggerFactory.getLogger(IcebergRemoveOrphanFilesJob.class);
   private static final String NAME =
       JobTemplateProvider.BUILTIN_NAME_PREFIX + "iceberg-remove-orphan-files";
-  private static final String VERSION = "v3";
+  private static final String VERSION = "v1";
+
+  /**
+   * Outcome of orphan cleanup with byte measurement.
+   *
+   * <p>Only produced by {@link #executeWithMetrics}; CLI {@link #execute} 
does not collect bytes.
+   */
+  public static final class OrphanCleanupResult {
+    private final long filesRemoved;
+    private final long bytesReclaimed;
+
+    OrphanCleanupResult(long filesRemoved, long bytesReclaimed) {
+      this.filesRemoved = filesRemoved;
+      this.bytesReclaimed = bytesReclaimed;
+    }
+
+    /**
+     * @return orphan files found (dry-run) or removed
+     */
+    public long filesRemoved() {
+      return filesRemoved;
+    }
+
+    /**
+     * @return sum of file sizes measured before delete; {@code 0} when every 
size lookup failed
+     */
+    public long bytesReclaimed() {
+      return bytesReclaimed;
+    }
+  }
 
   @Override
   public SparkJobTemplate jobTemplate() {
@@ -73,8 +108,7 @@ public class IcebergRemoveOrphanFilesJob implements 
BuiltInJob {
    *
    * <p>Required: {@code --catalog name --table db.table}. Optional: {@code 
--older-than 'yyyy-MM-dd
    * HH:mm:ss'}, {@code --location path}, {@code --dry-run true|false}, and 
{@code --spark-conf
-   * json}. The cutoff defaults to three days ago and dry-run defaults to 
false. Iceberg's minimum
-   * retention interval is preserved. A custom location must be within the 
table.
+   * json}.
    *
    * @param args named command-line arguments
    */
@@ -86,52 +120,165 @@ public class IcebergRemoveOrphanFilesJob implements 
BuiltInJob {
   }
 
   static int run(String[] args) {
-    return Runner.run(args);
-  }
+    try {
+      Map<String, String> argMap =
+          IcebergJobUtils.parseArguments(
+              args,
+              new HashSet<>(
+                  Arrays.asList(
+                      "catalog", "table", "older-than", "location", "dry-run", 
"spark-conf")),
+              new HashSet<>(Arrays.asList("catalog", "table")));
+      boolean dryRun = parseDryRun(argMap.get("dry-run"));
+      Map<String, String> configs =
+          IcebergJobUtils.parseCustomSparkConfigs(argMap.get("spark-conf"));
+      SparkSession.Builder builder =
+          SparkSession.builder().appName("Gravitino Built-in Iceberg Remove 
Orphan Files");
+      configs.forEach(builder::config);
 
-  static long execute(SparkSession spark, Map<String, String> options)
-      throws IOException, AnalysisException {
-    String catalog = requireOption(options, "catalog");
-    String identifier = requireOption(options, "table");
-    boolean dryRun = parseDryRun(options.get("dry-run"));
-    // Backslash escapes in string literals must retain Spark's default 
interpretation.
-    Preconditions.checkArgument(
-        
!Boolean.parseBoolean(spark.conf().get("spark.sql.parser.escapedStringLiterals",
 "false")),
-        "spark.sql.parser.escapedStringLiterals must be false");
-    Table table =
-        Spark3Util.loadIcebergTable(
-            spark, IcebergJobUtils.escapeSqlIdentifier(catalog) + "." + 
identifier);
-    String location = options.get("location");
-    // Direct callers may pass an empty template value without CLI argument 
parsing.
-    if (location == null || 
location.codePoints().allMatch(Character::isWhitespace)) {
-      location = table.location();
+      try (SparkSession spark = builder.getOrCreate()) {
+        IcebergJobUtils.requireIcebergSparkRuntime();
+        List<Row> results =
+            execute(
+                spark,
+                argMap.get("catalog"),
+                argMap.get("table"),
+                
IcebergJobUtils.nullIfUnresolvedPlaceholder(argMap.get("older-than")),
+                
IcebergJobUtils.nullIfUnresolvedPlaceholder(argMap.get("location")),
+                dryRun);
+        LOG.info(
+            "Orphan file cleanup completed: {} files {}, table {}.{}",
+            results.size(),
+            dryRun ? "found (dry-run)" : "removed",
+            argMap.get("catalog"),
+            argMap.get("table"));
+      }
+      return 0;
+    } catch (Exception e) {
+      LOG.error("Error executing remove orphan files job", e);
+      printUsage();
+      return 1;
     }
-    validateLocation(table.location(), location);
-    validateLocalLocation(table.location(), location);
-    validateRemoteLocation(spark, table.location(), location);
-    String sql =
-        buildProcedureCall(
-            catalog,
-            identifier,
-            options.get("older-than"),
-            normalizeLocation(location).toString(),
-            dryRun);
-    Iterator<Row> results = spark.sql(sql).toLocalIterator();
-    long count = 0;
-    while (results.hasNext()) {
-      Row row = results.next();
+  }
+
+  /**
+   * Runs {@code remove_orphan_files} on an existing Spark session. Shared by 
CLI {@link #main} and
+   * tests. Does not measure reclaimed bytes.
+   *
+   * @return procedure result rows (one path per row)
+   */
+  static List<Row> execute(
+      SparkSession spark,
+      String catalogName,
+      String tableIdentifier,
+      @Nullable String olderThan,
+      @Nullable String location,
+      boolean dryRun)
+      throws IOException {
+    requireEscapedStringLiteralsDisabled(spark);
+    String normalizedLocation =
+        resolveAndValidateLocation(spark, catalogName, tableIdentifier, 
location);
+    return callRemoveOrphanFiles(
+        spark, catalogName, tableIdentifier, olderThan, normalizedLocation, 
dryRun);
+  }
+
+  /**
+   * TMS path: dry-run list → FileIO sizes → optional real delete. CLI uses 
{@link #execute} instead
+   * (single procedure call, no byte measurement).
+   */
+  static OrphanCleanupResult executeWithMetrics(
+      SparkSession spark,
+      String catalogName,
+      String tableIdentifier,
+      @Nullable String olderThan,
+      @Nullable String location,
+      boolean dryRun)
+      throws IOException {
+    requireEscapedStringLiteralsDisabled(spark);
+    Table table = IcebergJobUtils.loadIcebergTable(spark, catalogName, 
tableIdentifier);
+    String normalizedLocation = resolveAndValidateLocation(spark, table, 
location);
+    List<Row> listed =
+        callRemoveOrphanFiles(
+            spark, catalogName, tableIdentifier, olderThan, 
normalizedLocation, true);
+    List<String> orphanPaths = new ArrayList<>(listed.size());
+    long bytes = 0L;
+    for (Row row : listed) {
+      String orphanPath = row.getString(0);
+      orphanPaths.add(orphanPath);
       if (dryRun) {
-        LOG.info("Orphan file (dry-run): {}", row.getString(0));
+        LOG.info("Orphan file (dry-run): {}", orphanPath);
       }
-      count++;
+      bytes += sizeOf(table, orphanPath);
+    }
+    if (!dryRun && !orphanPaths.isEmpty()) {
+      callRemoveOrphanFiles(
+          spark, catalogName, tableIdentifier, olderThan, normalizedLocation, 
false);
     }
     LOG.info(
-        "Orphan file cleanup completed: {} files {}, table {}.{}",
-        count,
+        "Orphan file cleanup completed: {} files {}, {} bytes, table {}.{}",
+        orphanPaths.size(),
         dryRun ? "found (dry-run)" : "removed",
-        catalog,
-        identifier);
-    return count;
+        bytes,
+        catalogName,
+        tableIdentifier);
+    return new OrphanCleanupResult(orphanPaths.size(), bytes);
+  }
+
+  private static List<Row> callRemoveOrphanFiles(
+      SparkSession spark,
+      String catalogName,
+      String tableIdentifier,
+      @Nullable String olderThan,
+      String normalizedLocation,
+      boolean dryRun) {
+    String sql =
+        buildProcedureCall(catalogName, tableIdentifier, olderThan, 
normalizedLocation, dryRun);
+    LOG.info("Executing Iceberg remove_orphan_files: {}", sql);
+    return spark.sql(sql).collectAsList();
+  }
+
+  @Override
+  public boolean hasBeforeMetrics() {
+    return false;
+  }
+
+  @Override
+  public TableSnapshotMetrics collectBeforeMetrics(
+      SparkSession spark, String catalogName, String tableIdentifier) {
+    throw new IllegalStateException("Orphan cleanup must not sample 
before-metrics");
+  }
+
+  @Override
+  public boolean shouldCheckSnapshotDrift() {
+    return false;
+  }
+
+  @Override
+  public TableSnapshotMetrics executeAndCollectAfter(
+      SparkSession spark,
+      String catalogName,
+      String tableIdentifier,
+      Map<String, String> argsByName,
+      @Nullable TableSnapshotMetrics before)
+      throws Exception {
+    OrphanCleanupResult orphan =
+        executeWithMetrics(
+            spark,
+            catalogName,
+            tableIdentifier,
+            
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("older-than")),
+            
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("location")),
+            
parseDryRun(IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("dry-run"))));
+    return TableSnapshotMetrics.of(
+        IcebergJobUtils.currentSnapshotIdOrEmpty(spark, catalogName, 
tableIdentifier),
+        orphanAfterMetrics(orphan.filesRemoved(), orphan.bytesReclaimed()));
+  }
+
+  @VisibleForTesting
+  static Map<String, Object> orphanAfterMetrics(long removedFileNumber, long 
removedFileSize) {
+    Map<String, Object> metrics = new HashMap<>();
+    metrics.put(IcebergOrphanFileRemovalContent.REMOVED_FILE_NUMBER_METRIC, 
removedFileNumber);
+    metrics.put(IcebergOrphanFileRemovalContent.REMOVED_FILE_SIZE_METRIC, 
removedFileSize);
+    return metrics;
   }
 
   static String buildProcedureCall(
@@ -162,35 +309,44 @@ public class IcebergRemoveOrphanFilesJob implements 
BuiltInJob {
     return "true".equals(value);
   }
 
-  static void validateLocation(String tableLocation, String location) {
-    OrphanFileLocationUtils.validateLocation(tableLocation, location);
+  /**
+   * Best-effort size for one orphan path via the table {@link 
org.apache.iceberg.io.FileIO}.
+   * Missing or unreadable files contribute {@code 0}.
+   */
+  @VisibleForTesting
+  static long sizeOf(Table table, String location) {
+    try {
+      return table.io().newInputFile(location).getLength();
+    } catch (RuntimeException e) {
+      LOG.warn("Failed to measure orphan file size for {}: {}", location, 
e.toString());
+      return 0L;
+    }
   }
 
-  private static List<String> buildArguments() {
-    return Arrays.asList(
-        "--catalog",
-        "{{catalog_name}}",
-        "--table",
-        "{{table_identifier}}",
-        "--older-than",
-        "{{older_than:-}}",
-        "--location",
-        "{{location:-}}",
-        "--dry-run",
-        "{{dry_run:-false}}",
-        "--spark-conf",
-        "{{spark_conf:-}}");
+  private static void requireEscapedStringLiteralsDisabled(SparkSession spark) 
{
+    // Backslash escapes in string literals must retain Spark's default 
interpretation.
+    Preconditions.checkArgument(
+        
!Boolean.parseBoolean(spark.conf().get("spark.sql.parser.escapedStringLiterals",
 "false")),
+        "spark.sql.parser.escapedStringLiterals must be false");
   }
 
-  private static Map<String, String> buildSparkConfigs() {
-    return IcebergSparkConfigUtils.buildTemplateSparkConfigs();
+  private static String resolveAndValidateLocation(
+      SparkSession spark, String catalogName, String tableIdentifier, 
@Nullable String location)
+      throws IOException {
+    Table table = IcebergJobUtils.loadIcebergTable(spark, catalogName, 
tableIdentifier);
+    return resolveAndValidateLocation(spark, table, location);
   }
 
-  private static void printUsage() {
-    LOG.error(
-        "Usage: IcebergRemoveOrphanFilesJob --catalog <name> --table 
<db.table> "
-            + "[--older-than 'yyyy-MM-dd HH:mm:ss'] [--location <path>] "
-            + "[--dry-run true|false] [--spark-conf <json>]");
+  private static String resolveAndValidateLocation(
+      SparkSession spark, Table table, @Nullable String location) throws 
IOException {
+    // Direct callers may pass an empty template value without CLI argument 
parsing.
+    if (location == null || 
location.codePoints().allMatch(Character::isWhitespace)) {
+      location = table.location();
+    }
+    OrphanFileLocationUtils.validateLocation(table.location(), location);
+    validateLocalLocation(table.location(), location);
+    validateRemoteLocation(spark, table.location(), location);
+    return normalizeLocation(location).toString();
   }
 
   private static void validateLocalLocation(String tableLocation, String 
location)
@@ -227,44 +383,30 @@ public class IcebergRemoveOrphanFilesJob implements 
BuiltInJob {
         spark.sparkContext().hadoopConfiguration(), tableLocation, location);
   }
 
-  private static String requireOption(Map<String, String> options, String key) 
{
-    String value = options.get(key);
-    Preconditions.checkArgument(value != null && !value.trim().isEmpty(), 
"--%s is required", key);
-    return value;
+  private static List<String> buildArguments() {
+    return Arrays.asList(
+        "--catalog",
+        "{{catalog_name}}",
+        "--table",
+        "{{table_identifier}}",
+        "--older-than",
+        "{{older_than:-}}",
+        "--location",
+        "{{location:-}}",
+        "--dry-run",
+        "{{dry_run:-false}}",
+        "--spark-conf",
+        "{{spark_conf:-}}");
   }
 
-  // Defer verification of Spark-specific exception handlers until job 
execution. The server
-  // loads this job's template without Spark or Iceberg on its classpath.
-  private static final class Runner {
-    private static int run(String[] args) {
-      Map<String, String> options = IcebergJobUtils.parseArguments(args);
-      SparkSession.Builder builder =
-          SparkSession.builder().appName("Gravitino Built-in Iceberg Remove 
Orphan Files");
-      try {
-        requireOption(options, "catalog");
-        requireOption(options, "table");
-        parseDryRun(options.get("dry-run"));
-        
IcebergJobUtils.parseCustomSparkConfigs(options.get("spark-conf")).forEach(builder::config);
-      } catch (IllegalArgumentException e) {
-        LOG.error("Invalid remove orphan files job arguments: {}", 
e.getMessage());
-        printUsage();
-        return 1;
-      }
+  private static Map<String, String> buildSparkConfigs() {
+    return IcebergSparkConfigUtils.buildTemplateSparkConfigs();
+  }
 
-      SparkSession spark = null;
-      try {
-        spark = builder.getOrCreate();
-        IcebergJobUtils.requireIcebergSparkRuntime();
-        execute(spark, options);
-        return 0;
-      } catch (IOException | AnalysisException | RuntimeException e) {
-        LOG.error("Error executing remove orphan files job", e);
-        return 1;
-      } finally {
-        if (spark != null) {
-          spark.stop();
-        }
-      }
-    }
+  private static void printUsage() {
+    LOG.error(
+        "Usage: IcebergRemoveOrphanFilesJob --catalog <name> --table 
<db.table> "
+            + "[--older-than 'yyyy-MM-dd HH:mm:ss'] [--location <path>] "
+            + "[--dry-run true|false] [--spark-conf <json>]");
   }
 }
diff --git 
a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java
 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java
index e923f8b6e5..8dd8474be6 100644
--- 
a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java
+++ 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java
@@ -18,16 +18,22 @@
  */
 package org.apache.gravitino.maintenance.jobs.iceberg;
 
+import com.google.common.annotations.VisibleForTesting;
 import java.util.Arrays;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import javax.annotation.Nullable;
 import org.apache.gravitino.job.JobTemplateProvider;
 import org.apache.gravitino.job.SparkJobTemplate;
 import org.apache.gravitino.maintenance.jobs.BuiltInJob;
 import 
org.apache.gravitino.maintenance.optimizer.common.util.IcebergSparkConfigUtils;
+import org.apache.gravitino.policy.IcebergDataCompactionContent;
 import org.apache.spark.sql.Row;
 import org.apache.spark.sql.SparkSession;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Built-in job for rewriting Iceberg table data files.
@@ -35,11 +41,13 @@ import org.apache.spark.sql.SparkSession;
  * <p>This job leverages Iceberg's RewriteDataFilesProcedure to optimize data 
file layout through
  * binpack or sort strategies. Z-order is a type of sort order, not a strategy.
  */
-public class IcebergRewriteDataFilesJob implements BuiltInJob {
+public class IcebergRewriteDataFilesJob implements BuiltInJob, 
IcebergMaintenanceAction {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(IcebergRewriteDataFilesJob.class);
 
   private static final String NAME =
       JobTemplateProvider.BUILTIN_NAME_PREFIX + "iceberg-rewrite-data-files";
-  private static final String VERSION = "v3";
+  private static final String VERSION = "v1";
 
   // Valid strategy values for Iceberg rewrite_data_files procedure
   private static final String STRATEGY_BINPACK = "binpack";
@@ -159,19 +167,11 @@ public class IcebergRewriteDataFilesJob implements 
BuiltInJob {
     IcebergJobUtils.requireIcebergSparkRuntimeOrExit(spark);
 
     try {
-      // Build the procedure call SQL
-      String sql =
-          buildProcedureCall(
-              catalogName, tableIdentifier, strategy, sortOrder, whereClause, 
optionsJson);
-
-      System.out.println("Executing Iceberg rewrite_data_files procedure: " + 
sql);
-
-      // Execute the procedure
-      Row[] results = (Row[]) spark.sql(sql).collect();
-
-      // Print results
-      if (results.length > 0) {
-        Row result = results[0];
+      List<Row> results =
+          execute(
+              spark, catalogName, tableIdentifier, strategy, sortOrder, 
whereClause, optionsJson);
+      if (!results.isEmpty()) {
+        Row result = results.get(0);
         // Iceberg 1.6.1 returns 4 columns, newer versions may return 5
         if (result.size() >= 5) {
           System.out.printf(
@@ -196,7 +196,6 @@ public class IcebergRewriteDataFilesJob implements 
BuiltInJob {
               result.getInt(0), result.getInt(1), result.getLong(2), 
result.getInt(3));
         }
       }
-
       System.out.println("Rewrite data files job completed successfully");
     } catch (Exception e) {
       System.err.println("Error executing rewrite data files job: " + 
e.getMessage());
@@ -271,21 +270,6 @@ public class IcebergRewriteDataFilesJob implements 
BuiltInJob {
     return sql.toString();
   }
 
-  /** Delegates to {@link IcebergJobUtils#escapeSqlString(String)}. */
-  static String escapeSqlString(String value) {
-    return IcebergJobUtils.escapeSqlString(value);
-  }
-
-  /** Delegates to {@link IcebergJobUtils#escapeSqlIdentifier(String)}. */
-  static String escapeSqlIdentifier(String identifier) {
-    return IcebergJobUtils.escapeSqlIdentifier(identifier);
-  }
-
-  /** Delegates to {@link IcebergJobUtils#parseArguments(String[])}. */
-  static Map<String, String> parseArguments(String[] args) {
-    return IcebergJobUtils.parseArguments(args);
-  }
-
   /**
    * Validate the strategy parameter value.
    *
@@ -309,11 +293,6 @@ public class IcebergRewriteDataFilesJob implements 
BuiltInJob {
     }
   }
 
-  /** Delegates to {@link IcebergJobUtils#parseCustomSparkConfigs(String)}. */
-  static Map<String, String> parseCustomSparkConfigs(String sparkConfJson) {
-    return IcebergJobUtils.parseCustomSparkConfigs(sparkConfJson);
-  }
-
   /** Print usage information. */
   private static void printUsage() {
     System.err.println(
@@ -398,4 +377,144 @@ public class IcebergRewriteDataFilesJob implements 
BuiltInJob {
   private static Map<String, String> buildSparkConfigs() {
     return IcebergSparkConfigUtils.buildTemplateSparkConfigs();
   }
+
+  /**
+   * Runs {@code rewrite_data_files} on an existing Spark session. Shared by 
CLI {@link #main} and
+   * TMS {@link #executeAndCollectAfter}.
+   *
+   * @return procedure result rows
+   */
+  static List<Row> execute(
+      SparkSession spark,
+      String catalogName,
+      String tableIdentifier,
+      @Nullable String strategy,
+      @Nullable String sortOrder,
+      @Nullable String whereClause,
+      @Nullable String optionsJson) {
+    validateStrategy(strategy);
+    String sql =
+        buildProcedureCall(
+            catalogName, tableIdentifier, strategy, sortOrder, whereClause, 
optionsJson);
+    LOG.info("Executing Iceberg rewrite_data_files: {}", sql);
+    return spark.sql(sql).collectAsList();
+  }
+
+  @Override
+  public boolean hasBeforeMetrics() {
+    return true;
+  }
+
+  @Override
+  public TableSnapshotMetrics collectBeforeMetrics(
+      SparkSession spark, String catalogName, String tableIdentifier) {
+    long snapshotId = IcebergJobUtils.requireCurrentSnapshotId(spark, 
catalogName, tableIdentifier);
+    Map<String, Object> payload = collectCompactionMetrics(spark, catalogName, 
tableIdentifier);
+    return TableSnapshotMetrics.of(snapshotId, payload);
+  }
+
+  @Override
+  public boolean shouldCheckSnapshotDrift() {
+    return true;
+  }
+
+  @Override
+  public TableSnapshotMetrics executeAndCollectAfter(
+      SparkSession spark,
+      String catalogName,
+      String tableIdentifier,
+      Map<String, String> argsByName,
+      @Nullable TableSnapshotMetrics before) {
+    execute(
+        spark,
+        catalogName,
+        tableIdentifier,
+        
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("strategy")),
+        
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("sort-order")),
+        IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("where")),
+        
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("options")));
+    return TableSnapshotMetrics.of(
+        IcebergJobUtils.requireCurrentSnapshotId(spark, catalogName, 
tableIdentifier),
+        collectCompactionMetrics(spark, catalogName, tableIdentifier));
+  }
+
+  // -------------------------------------------------------------------------
+  // TMS metrics helpers (not used by CLI {@link #main})
+  // -------------------------------------------------------------------------
+
+  /**
+   * Collects compaction inventory metrics for TMS before/after reporting. 
Uses the same {@code
+   * files} metadata SQL as {@link IcebergUpdateStatsAndMetricsJob}. CLI entry 
points never call
+   * this.
+   */
+  @VisibleForTesting
+  static Map<String, Object> collectCompactionMetrics(
+      SparkSession spark, String catalogName, String tableIdentifier) {
+    boolean partitioned =
+        IcebergUpdateStatsAndMetricsJob.isPartitionedTable(spark, catalogName, 
tableIdentifier);
+    if (partitioned) {
+      String sql =
+          IcebergUpdateStatsAndMetricsJob.buildPartitionStatsSql(catalogName, 
tableIdentifier);
+      Row[] rows = (Row[]) spark.sql(sql).collect();
+      return aggregatePartitionCompactionMetrics(rows);
+    }
+
+    String sql = 
IcebergUpdateStatsAndMetricsJob.buildTableStatsSql(catalogName, 
tableIdentifier);
+    Row[] rows = (Row[]) spark.sql(sql).collect();
+    if (rows.length == 0) {
+      return compactionMetrics(0D, 0L, 0D, 0L, 0L);
+    }
+    Row row = rows[0];
+    return compactionMetrics(
+        numberAsDouble(row, "data-file-mse"),
+        numberAsLong(row, "delete-file-number"),
+        numberAsDouble(row, "avg-file-size"),
+        numberAsLong(row, "total-file-size"),
+        numberAsLong(row, "file-number"));
+  }
+
+  @VisibleForTesting
+  static Map<String, Object> aggregatePartitionCompactionMetrics(Row[] rows) {
+    double maxMse = 0D;
+    long deleteFiles = 0L;
+    long fileNumber = 0L;
+    long totalFileSize = 0L;
+    double weightedAvgNumerator = 0D;
+    for (Row row : rows) {
+      maxMse = Math.max(maxMse, numberAsDouble(row, "data-file-mse"));
+      deleteFiles += numberAsLong(row, "delete-file-number");
+      long partitionFiles = numberAsLong(row, "file-number");
+      fileNumber += partitionFiles;
+      totalFileSize += numberAsLong(row, "total-file-size");
+      weightedAvgNumerator += numberAsDouble(row, "avg-file-size") * 
partitionFiles;
+    }
+    double avgFileSize = fileNumber == 0L ? 0D : weightedAvgNumerator / 
fileNumber;
+    return compactionMetrics(maxMse, deleteFiles, avgFileSize, totalFileSize, 
fileNumber);
+  }
+
+  @VisibleForTesting
+  static Map<String, Object> compactionMetrics(
+      double dataFileMse,
+      long deleteFileNumber,
+      double avgFileSize,
+      long totalFileSize,
+      long fileNumber) {
+    Map<String, Object> metrics = new HashMap<>();
+    metrics.put(IcebergDataCompactionContent.DATA_FILE_MSE_METRIC, 
dataFileMse);
+    metrics.put(IcebergDataCompactionContent.DELETE_FILE_NUMBER_METRIC, 
deleteFileNumber);
+    metrics.put(IcebergDataCompactionContent.AVG_FILE_SIZE_METRIC, 
avgFileSize);
+    metrics.put(IcebergDataCompactionContent.TOTAL_FILE_SIZE_METRIC, 
totalFileSize);
+    metrics.put(IcebergDataCompactionContent.FILE_NUMBER_METRIC, fileNumber);
+    return metrics;
+  }
+
+  private static double numberAsDouble(Row row, String field) {
+    Number number = row.getAs(field);
+    return number == null ? 0D : number.doubleValue();
+  }
+
+  private static long numberAsLong(Row row, String field) {
+    Number number = row.getAs(field);
+    return number == null ? 0L : number.longValue();
+  }
 }
diff --git 
a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.java
 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.java
index 25d6f2f509..0e8aca63f5 100644
--- 
a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.java
+++ 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.java
@@ -18,8 +18,10 @@
  */
 package org.apache.gravitino.maintenance.jobs.iceberg;
 
+import com.google.common.annotations.VisibleForTesting;
 import java.util.Arrays;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
@@ -28,8 +30,14 @@ import org.apache.gravitino.job.JobTemplateProvider;
 import org.apache.gravitino.job.SparkJobTemplate;
 import org.apache.gravitino.maintenance.jobs.BuiltInJob;
 import 
org.apache.gravitino.maintenance.optimizer.common.util.IcebergSparkConfigUtils;
+import org.apache.gravitino.policy.IcebergRewriteManifestsContent;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.Table;
 import org.apache.spark.sql.Row;
 import org.apache.spark.sql.SparkSession;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Built-in job for rewriting Iceberg table manifest files.
@@ -37,11 +45,13 @@ import org.apache.spark.sql.SparkSession;
  * <p>This job leverages Iceberg's RewriteManifestsProcedure to consolidate 
small manifest files and
  * cluster manifest entries within an existing partition spec to improve scan 
planning.
  */
-public class IcebergRewriteManifestsJob implements BuiltInJob {
+public class IcebergRewriteManifestsJob implements BuiltInJob, 
IcebergMaintenanceAction {
+
+  private static final Logger LOG = 
LoggerFactory.getLogger(IcebergRewriteManifestsJob.class);
 
   private static final String NAME =
       JobTemplateProvider.BUILTIN_NAME_PREFIX + "iceberg-rewrite-manifests";
-  private static final String VERSION = "v3";
+  private static final String VERSION = "v1";
 
   @Override
   public SparkJobTemplate jobTemplate() {
@@ -104,7 +114,30 @@ public class IcebergRewriteManifestsJob implements 
BuiltInJob {
 
   static int run(String[] args) {
     try {
-      execute(args);
+      Map<String, String> argMap = parseArguments(args);
+      Map<String, String> configs =
+          IcebergJobUtils.parseCustomSparkConfigs(argMap.get("spark-conf"));
+      SparkSession.Builder builder =
+          SparkSession.builder().appName("Gravitino Built-in Iceberg Rewrite 
Manifests");
+      configs.forEach(builder::config);
+
+      try (SparkSession spark = builder.getOrCreate()) {
+        IcebergJobUtils.requireIcebergSparkRuntime();
+        List<Row> results =
+            execute(
+                spark,
+                argMap.get("catalog"),
+                argMap.get("table"),
+                argMap.get("use-caching"),
+                argMap.get("spec-id"));
+        if (!results.isEmpty()) {
+          Row result = results.get(0);
+          System.out.printf(
+              "Rewrite Manifests Results: Rewritten manifests: %d, Added 
manifests: %d%n",
+              ((Number) result.get(0)).longValue(), ((Number) 
result.get(1)).longValue());
+        }
+        System.out.println("Rewrite manifests job completed successfully");
+      }
       return 0;
     } catch (Exception e) {
       System.err.println("Error rewriting manifests: " + e.getMessage());
@@ -202,31 +235,69 @@ public class IcebergRewriteManifestsJob implements 
BuiltInJob {
     }
   }
 
-  private static void execute(String[] args) {
-    Map<String, String> argMap = parseArguments(args);
-    String sql =
-        buildProcedureCall(
-            argMap.get("catalog"),
-            argMap.get("table"),
-            argMap.get("use-caching"),
-            argMap.get("spec-id"));
-    Map<String, String> configs = 
IcebergJobUtils.parseCustomSparkConfigs(argMap.get("spark-conf"));
-    SparkSession.Builder builder =
-        SparkSession.builder().appName("Gravitino Built-in Iceberg Rewrite 
Manifests");
-    configs.forEach(builder::config);
+  /**
+   * Runs {@code rewrite_manifests} on an existing Spark session. Shared by 
CLI and TMS {@link
+   * IcebergMaintenanceJob}.
+   *
+   * @return procedure result rows
+   */
+  static List<Row> execute(
+      SparkSession spark,
+      String catalogName,
+      String tableIdentifier,
+      @Nullable String useCaching,
+      @Nullable String specId) {
+    validateUseCaching(useCaching);
+    validateSpecId(specId);
+    String sql = buildProcedureCall(catalogName, tableIdentifier, useCaching, 
specId);
+    LOG.info("Executing Iceberg rewrite_manifests: {}", sql);
+    return spark.sql(sql).collectAsList();
+  }
+
+  @Override
+  public boolean hasBeforeMetrics() {
+    return true;
+  }
 
-    try (SparkSession spark = builder.getOrCreate()) {
-      IcebergJobUtils.requireIcebergSparkRuntime();
-      System.out.println("Executing Iceberg rewrite_manifests procedure: " + 
sql);
-      List<Row> results = spark.sql(sql).collectAsList();
-      if (!results.isEmpty()) {
-        Row result = results.get(0);
-        System.out.printf(
-            "Rewrite Manifests Results: Rewritten manifests: %d, Added 
manifests: %d%n",
-            ((Number) result.get(0)).longValue(), ((Number) 
result.get(1)).longValue());
-      }
-      System.out.println("Rewrite manifests job completed successfully");
+  @Override
+  public TableSnapshotMetrics collectBeforeMetrics(
+      SparkSession spark, String catalogName, String tableIdentifier) {
+    long snapshotId = IcebergJobUtils.requireCurrentSnapshotId(spark, 
catalogName, tableIdentifier);
+    Map<String, Object> payload = collectManifestBeforeMetrics(spark, 
catalogName, tableIdentifier);
+    return TableSnapshotMetrics.of(snapshotId, payload);
+  }
+
+  @Override
+  public boolean shouldCheckSnapshotDrift() {
+    return true;
+  }
+
+  @Override
+  public TableSnapshotMetrics executeAndCollectAfter(
+      SparkSession spark,
+      String catalogName,
+      String tableIdentifier,
+      Map<String, String> argsByName,
+      @Nullable TableSnapshotMetrics before) {
+    List<Row> results =
+        execute(
+            spark,
+            catalogName,
+            tableIdentifier,
+            
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("use-caching")),
+            
IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("spec-id")));
+    long rewritten = 0L;
+    if (!results.isEmpty()) {
+      Row result = results.get(0);
+      rewritten = ((Number) result.get(0)).longValue();
+      LOG.info(
+          "Rewrite manifests results: rewritten={}, added={}",
+          rewritten,
+          ((Number) result.get(1)).longValue());
     }
+    return TableSnapshotMetrics.of(
+        IcebergJobUtils.requireCurrentSnapshotId(spark, catalogName, 
tableIdentifier),
+        manifestAfterMetrics(rewritten));
   }
 
   private static void printUsage() {
@@ -263,4 +334,44 @@ public class IcebergRewriteManifestsJob implements 
BuiltInJob {
   private static Map<String, String> buildSparkConfigs() {
     return IcebergSparkConfigUtils.buildTemplateSparkConfigs();
   }
+
+  // -------------------------------------------------------------------------
+  // TMS metrics helpers (not used by CLI {@link #main})
+  // -------------------------------------------------------------------------
+
+  /**
+   * Collects manifest inventory for TMS S0. Reads the current snapshot's 
manifests via Iceberg API.
+   * CLI entry points never call this.
+   */
+  @VisibleForTesting
+  static Map<String, Object> collectManifestBeforeMetrics(
+      SparkSession spark, String catalogName, String tableIdentifier) {
+    Table table = IcebergJobUtils.loadIcebergTable(spark, catalogName, 
tableIdentifier);
+    Snapshot snapshot = table.currentSnapshot();
+    long count = 0L;
+    long totalSize = 0L;
+    if (snapshot != null) {
+      for (ManifestFile manifest : snapshot.allManifests(table.io())) {
+        count++;
+        totalSize += manifest.length();
+      }
+    }
+    return manifestBeforeMetrics(count, count == 0L ? 0D : (double) totalSize 
/ count);
+  }
+
+  @VisibleForTesting
+  static Map<String, Object> manifestBeforeMetrics(long manifestNumber, double 
avgManifestSize) {
+    Map<String, Object> metrics = new HashMap<>();
+    metrics.put(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC, 
manifestNumber);
+    metrics.put(IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC, 
avgManifestSize);
+    return metrics;
+  }
+
+  @VisibleForTesting
+  static Map<String, Object> manifestAfterMetrics(long 
rewrittenManifestNumber) {
+    Map<String, Object> metrics = new HashMap<>();
+    metrics.put(
+        IcebergRewriteManifestsContent.REWRITTEN_MANIFEST_NUMBER_METRIC, 
rewrittenManifestNumber);
+    return metrics;
+  }
 }
diff --git 
a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/MaintenanceTriggerGate.java
 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/MaintenanceTriggerGate.java
index 262785428a..d23d2b162f 100644
--- 
a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/MaintenanceTriggerGate.java
+++ 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/MaintenanceTriggerGate.java
@@ -33,6 +33,7 @@ import 
org.apache.gravitino.maintenance.optimizer.recommender.util.ExpressionEva
 import 
org.apache.gravitino.maintenance.optimizer.recommender.util.QLExpressionEvaluator;
 import org.apache.gravitino.policy.IcebergDataCompactionContent;
 import org.apache.gravitino.policy.IcebergOrphanFileRemovalContent;
+import org.apache.gravitino.policy.IcebergRewriteManifestsContent;
 import org.apache.gravitino.policy.PolicyContents;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -41,8 +42,8 @@ import org.slf4j.LoggerFactory;
  * In-Spark maintain-or-skip gate after S0 metrics (§5.2.2).
  *
  * <p>Evaluates enqueue-time policy rules locally with the same QL stack as 
the optimizer. Does not
- * call Gravitino. Expire / rewrite-manifests placeholders always maintain 
(optimizer-only {@code
- * trigger-expr=false} on those types).
+ * call Gravitino. Snapshot expiry always maintains (optimizer-only scheduling 
for that type).
+ * Compaction and manifest rewrite evaluate {@code trigger-expr} against S0 
metrics.
  */
 final class MaintenanceTriggerGate {
 
@@ -62,7 +63,7 @@ final class MaintenanceTriggerGate {
    */
   static boolean shouldMaintain(
       MaintenanceType type, Map<String, String> argMap, @Nullable String 
metricsJson) {
-    if (type == MaintenanceType.EXPIRE_SNAPSHOTS || type == 
MaintenanceType.REWRITE_MANIFESTS) {
+    if (type == MaintenanceType.EXPIRE_SNAPSHOTS) {
       return true;
     }
 
@@ -75,6 +76,13 @@ final class MaintenanceTriggerGate {
       LOG.warn("Compaction recommend skip: metrics JSON missing compaction 
fields");
       return false;
     }
+    if (type == MaintenanceType.REWRITE_MANIFESTS
+        && (metrics.isEmpty()
+            || 
!metrics.containsKey(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC)
+            || 
!metrics.containsKey(IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC))) 
{
+      LOG.warn("Manifest rewrite recommend skip: metrics JSON missing manifest 
fields");
+      return false;
+    }
 
     boolean maintain = evaluateTrigger(rules, metrics);
     LOG.info(
@@ -138,6 +146,9 @@ final class MaintenanceTriggerGate {
     if (type == MaintenanceType.REWRITE_DATA_FILES) {
       return new HashMap<>(PolicyContents.icebergDataCompaction().rules());
     }
+    if (type == MaintenanceType.REWRITE_MANIFESTS) {
+      return new HashMap<>(PolicyContents.icebergRewriteManifests().rules());
+    }
     if (type == MaintenanceType.REMOVE_ORPHAN_FILES) {
       return new HashMap<>(PolicyContents.icebergOrphanFileRemoval().rules());
     }
diff --git 
a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/RemoteLocationValidator.java
 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/RemoteLocationValidator.java
index 6d1a93a722..12b84b5514 100644
--- 
a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/RemoteLocationValidator.java
+++ 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/RemoteLocationValidator.java
@@ -22,6 +22,7 @@ import com.google.common.base.Preconditions;
 import java.io.IOException;
 import java.util.ArrayDeque;
 import java.util.Deque;
+import 
org.apache.gravitino.maintenance.optimizer.common.util.OrphanFileLocationUtils;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.fs.FileStatus;
 import org.apache.hadoop.fs.FileSystem;
@@ -46,9 +47,9 @@ final class RemoteLocationValidator {
     }
     Path lexicalRoot = new Path(tableLocation.toUri().normalize());
     scan = new Path(scan.toUri().normalize());
-    IcebergRemoveOrphanFilesJob.validateLocation(lexicalRoot.toString(), 
scan.toString());
+    OrphanFileLocationUtils.validateLocation(lexicalRoot.toString(), 
scan.toString());
     Path root = fs.resolvePath(lexicalRoot);
-    IcebergRemoveOrphanFilesJob.validateLocation(root.toString(), 
fs.resolvePath(scan).toString());
+    OrphanFileLocationUtils.validateLocation(root.toString(), 
fs.resolvePath(scan).toString());
     // Inspect the table root itself, but not warehouse parents outside this 
table. Use the
     // lexical boundary because a warehouse parent symlink can change the 
resolved root.
     for (Path ancestor = scan; ancestor != null; ancestor = 
ancestor.getParent()) {
diff --git 
a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/TableSnapshotMetrics.java
 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/TableSnapshotMetrics.java
new file mode 100644
index 0000000000..8fb8264515
--- /dev/null
+++ 
b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/TableSnapshotMetrics.java
@@ -0,0 +1,73 @@
+/*
+ * 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.
+ */
+package org.apache.gravitino.maintenance.jobs.iceberg;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import java.util.Map;
+import org.apache.gravitino.json.JsonUtils;
+
+/**
+ * Table-side metrics bound to a snapshot id. Used for both TMS S0 (before) 
and S1 (after)
+ * reporting.
+ */
+public final class TableSnapshotMetrics {
+
+  private final long snapshotId;
+  private final String metricsJson;
+
+  /**
+   * @param snapshotId Iceberg snapshot id for this sample ({@code -1} when 
HEAD is empty)
+   * @param metricsJson metrics payload JSON
+   */
+  public TableSnapshotMetrics(long snapshotId, String metricsJson) {
+    this.snapshotId = snapshotId;
+    this.metricsJson = metricsJson;
+  }
+
+  /**
+   * @param snapshotId Iceberg snapshot id for this sample ({@code -1} when 
HEAD is empty)
+   * @param metrics metrics payload
+   * @return sample with metrics serialized to JSON
+   */
+  public static TableSnapshotMetrics of(long snapshotId, Map<String, Object> 
metrics) {
+    return new TableSnapshotMetrics(snapshotId, toJson(metrics));
+  }
+
+  /**
+   * @return Iceberg snapshot id for this sample
+   */
+  public long snapshotId() {
+    return snapshotId;
+  }
+
+  /**
+   * @return metrics payload JSON
+   */
+  public String metricsJson() {
+    return metricsJson;
+  }
+
+  private static String toJson(Map<String, Object> metrics) {
+    try {
+      return JsonUtils.anyFieldMapper().writeValueAsString(metrics);
+    } catch (JsonProcessingException e) {
+      throw new IllegalStateException("Failed to serialize metrics JSON", e);
+    }
+  }
+}
diff --git 
a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergExpireSnapshotsJob.java
 
b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergExpireSnapshotsJob.java
index a0344d8301..24607f23e4 100644
--- 
a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergExpireSnapshotsJob.java
+++ 
b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergExpireSnapshotsJob.java
@@ -29,6 +29,7 @@ import java.util.Arrays;
 import java.util.Map;
 import org.apache.gravitino.job.JobTemplateProvider;
 import org.apache.gravitino.job.SparkJobTemplate;
+import org.apache.gravitino.policy.IcebergSnapshotExpirationContent;
 import org.junit.jupiter.api.Test;
 
 public class TestIcebergExpireSnapshotsJob {
@@ -133,7 +134,7 @@ public class TestIcebergExpireSnapshotsJob {
     
assertTrue(customFields.containsKey(JobTemplateProvider.PROPERTY_VERSION_KEY));
 
     String version = 
customFields.get(JobTemplateProvider.PROPERTY_VERSION_KEY);
-    assertEquals("v3", version);
+    assertEquals("v1", version);
     assertTrue(version.matches(JobTemplateProvider.VERSION_VALUE_PATTERN));
   }
 
@@ -500,4 +501,41 @@ public class TestIcebergExpireSnapshotsJob {
             IcebergJobUtils.parseArguments(new String[] {"--stream-results"})
                 .get("stream-results")));
   }
+
+  @Test
+  public void testExpireSetDifferenceIgnoresConcurrentAdds() {
+    java.util.Set<Long> beforeSnapshots = new java.util.HashSet<>();
+    beforeSnapshots.add(1L);
+    beforeSnapshots.add(2L);
+    beforeSnapshots.add(3L);
+    java.util.Set<Long> afterSnapshots = new java.util.HashSet<>();
+    afterSnapshots.add(2L);
+    afterSnapshots.add(3L);
+    afterSnapshots.add(99L);
+    assertEquals(1L, 
IcebergExpireSnapshotsJob.snapshotsCleared(beforeSnapshots, afterSnapshots));
+
+    java.util.Map<String, Long> beforeFiles = new java.util.HashMap<>();
+    beforeFiles.put("a.parquet", 100L);
+    beforeFiles.put("b.parquet", 200L);
+    java.util.Map<String, Long> afterFiles = new java.util.HashMap<>();
+    afterFiles.put("b.parquet", 200L);
+    afterFiles.put("c.parquet", 500L);
+    assertEquals(100L, IcebergExpireSnapshotsJob.bytesReclaimed(beforeFiles, 
afterFiles));
+
+    String sql = 
IcebergExpireSnapshotsJob.buildReachableContentFilesSql("cat", "db.tbl");
+    assertTrue(sql.contains("FROM `cat`.`db`.`tbl`.`all_files`"));
+    assertTrue(sql.contains("GROUP BY file_path"));
+  }
+
+  @Test
+  public void testExpireMetricNames() {
+    Map<String, Object> before = 
IcebergExpireSnapshotsJob.expireBeforeMetrics(3L);
+    assertEquals(1, before.size());
+    assertEquals(3L, 
before.get(IcebergSnapshotExpirationContent.SNAPSHOT_NUMBER_METRIC));
+
+    Map<String, Object> after = 
IcebergExpireSnapshotsJob.expireAfterMetrics(2L, 100L);
+    assertEquals(2, after.size());
+    assertEquals(2L, 
after.get(IcebergSnapshotExpirationContent.EXPIRED_SNAPSHOT_NUMBER_METRIC));
+    assertEquals(100L, 
after.get(IcebergSnapshotExpirationContent.EXPIRED_FILE_SIZE_METRIC));
+  }
 }
diff --git 
a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergMaintenanceJob.java
 
b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergMaintenanceJob.java
index f942ca3968..bf19a4639d 100644
--- 
a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergMaintenanceJob.java
+++ 
b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergMaintenanceJob.java
@@ -28,7 +28,7 @@ import org.apache.gravitino.job.SparkJobTemplate;
 import 
org.apache.gravitino.maintenance.jobs.iceberg.IcebergMaintenanceJob.MaintenanceType;
 import org.junit.jupiter.api.Test;
 
-/** Unit tests for {@link IcebergMaintenanceJob}. */
+/** Unit tests for {@link IcebergMaintenanceJob} orchestration. */
 public class TestIcebergMaintenanceJob {
 
   @Test
@@ -80,4 +80,26 @@ public class TestIcebergMaintenanceJob {
               "--maintenance-types", "expire_snapshots", "--policy-ids", "10", 
"--tables", "[]"
             }));
   }
+
+  @Test
+  public void testSnapshotDriftGateOnlyForCompactionAndManifest() {
+    
assertTrue(IcebergMaintenanceJob.shouldCheckSnapshotDrift(MaintenanceType.REWRITE_DATA_FILES));
+    
assertTrue(IcebergMaintenanceJob.shouldCheckSnapshotDrift(MaintenanceType.REWRITE_MANIFESTS));
+    
assertFalse(IcebergMaintenanceJob.shouldCheckSnapshotDrift(MaintenanceType.EXPIRE_SNAPSHOTS));
+    assertFalse(
+        
IcebergMaintenanceJob.shouldCheckSnapshotDrift(MaintenanceType.REMOVE_ORPHAN_FILES));
+  }
+
+  @Test
+  public void testMaintenanceActionsWireToJobClasses() {
+    assertTrue(MaintenanceType.REWRITE_DATA_FILES.action() instanceof 
IcebergRewriteDataFilesJob);
+    assertTrue(MaintenanceType.REWRITE_MANIFESTS.action() instanceof 
IcebergRewriteManifestsJob);
+    assertTrue(MaintenanceType.EXPIRE_SNAPSHOTS.action() instanceof 
IcebergExpireSnapshotsJob);
+    assertTrue(MaintenanceType.REMOVE_ORPHAN_FILES.action() instanceof 
IcebergRemoveOrphanFilesJob);
+
+    assertTrue(MaintenanceType.REWRITE_DATA_FILES.action().hasBeforeMetrics());
+    assertTrue(MaintenanceType.REWRITE_MANIFESTS.action().hasBeforeMetrics());
+    assertTrue(MaintenanceType.EXPIRE_SNAPSHOTS.action().hasBeforeMetrics());
+    
assertFalse(MaintenanceType.REMOVE_ORPHAN_FILES.action().hasBeforeMetrics());
+  }
 }
diff --git 
a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJob.java
 
b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJob.java
index 8599f1b1b1..c044f3003d 100644
--- 
a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJob.java
+++ 
b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJob.java
@@ -30,6 +30,8 @@ import java.net.URLClassLoader;
 import java.util.ArrayList;
 import java.util.List;
 import org.apache.gravitino.maintenance.jobs.BuiltInJobTemplateProvider;
+import 
org.apache.gravitino.maintenance.optimizer.common.util.OrphanFileLocationUtils;
+import org.apache.gravitino.policy.IcebergOrphanFileRemovalContent;
 import org.junit.jupiter.api.Test;
 
 /** Tests orphan cleanup templates, SQL arguments, and location boundaries. */
@@ -103,16 +105,25 @@ public class TestIcebergRemoveOrphanFilesJob {
     assertTrue(sql.contains("/a/b\\'c"));
   }
 
+  @Test
+  public void testOrphanAfterMetricNames() {
+    java.util.Map<String, Object> metrics =
+        IcebergRemoveOrphanFilesJob.orphanAfterMetrics(10L, 200L);
+    assertEquals(2, metrics.size());
+    assertEquals(10L, 
metrics.get(IcebergOrphanFileRemovalContent.REMOVED_FILE_NUMBER_METRIC));
+    assertEquals(200L, 
metrics.get(IcebergOrphanFileRemovalContent.REMOVED_FILE_SIZE_METRIC));
+  }
+
   /** Verifies location boundaries. */
   @Test
   public void testLocationBoundaries() {
     assertDoesNotThrow(
         () ->
-            IcebergRemoveOrphanFilesJob.validateLocation(
+            OrphanFileLocationUtils.validateLocation(
                 "s3://bucket/db/table", "s3://bucket/db/table/data/"));
     assertDoesNotThrow(
         () ->
-            IcebergRemoveOrphanFilesJob.validateLocation(
+            OrphanFileLocationUtils.validateLocation(
                 "s3://bucket/db/table/", "s3://bucket/db/table"));
     for (String location :
         new String[] {
@@ -127,7 +138,7 @@ public class TestIcebergRemoveOrphanFilesJob {
         }) {
       assertThrows(
           IllegalArgumentException.class,
-          () -> 
IcebergRemoveOrphanFilesJob.validateLocation("s3://bucket/db/table", location),
+          () -> 
OrphanFileLocationUtils.validateLocation("s3://bucket/db/table", location),
           location);
     }
   }
diff --git 
a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJobWithSpark.java
 
b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJobWithSpark.java
index f1e6c59626..d7fe870129 100644
--- 
a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJobWithSpark.java
+++ 
b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRemoveOrphanFilesJobWithSpark.java
@@ -29,10 +29,10 @@ import java.nio.file.Path;
 import java.nio.file.attribute.FileTime;
 import java.time.Instant;
 import java.time.temporal.ChronoUnit;
-import java.util.HashMap;
-import java.util.Map;
+import java.util.List;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
+import org.apache.spark.sql.Row;
 import org.apache.spark.sql.SparkSession;
 import org.junit.jupiter.api.AfterAll;
 import org.junit.jupiter.api.BeforeAll;
@@ -84,16 +84,34 @@ public class TestIcebergRemoveOrphanFilesJobWithSpark {
     Path old = Files.write(data.resolve("old-orphan.parquet"), new byte[] {1});
     Files.setLastModifiedTime(old, FileTime.from(Instant.now().minus(5, 
ChronoUnit.DAYS)));
     Path recent = Files.write(data.resolve("recent-orphan.parquet"), new 
byte[] {1});
-    Map<String, String> args = args("cleanup");
-    args.put("dry-run", "true");
-    assertEquals(1, IcebergRemoveOrphanFilesJob.execute(spark, args));
+    assertEquals(1, execute("cleanup", null, null, true).size());
     assertTrue(Files.exists(old));
-    args.put("dry-run", "false");
-    assertEquals(1, IcebergRemoveOrphanFilesJob.execute(spark, args));
+    assertEquals(1, execute("cleanup", null, null, false).size());
     assertFalse(Files.exists(old));
     assertTrue(Files.exists(recent));
     assertEquals(2, spark.table("test_catalog.db.cleanup").count());
-    assertEquals(0, IcebergRemoveOrphanFilesJob.execute(spark, args));
+    assertEquals(0, execute("cleanup", null, null, false).size());
+  }
+
+  /** Verifies TMS executeWithMetrics measures removed file size; CLI execute 
does not. */
+  @Test
+  public void testRemovedFileSizeMeasuredBeforeDelete() throws Exception {
+    spark.sql("CREATE TABLE test_catalog.db.bytes (id INT) USING iceberg");
+    Path root = tempDir.resolve("db/bytes");
+    byte[] payload = new byte[] {1, 2, 3, 4, 5, 6, 7};
+    Path old = Files.write(root.resolve("old-orphan.bin"), payload);
+    Files.setLastModifiedTime(old, FileTime.from(Instant.now().minus(5, 
ChronoUnit.DAYS)));
+    assertEquals(1, execute("bytes", null, null, true).size());
+    IcebergRemoveOrphanFilesJob.OrphanCleanupResult dry =
+        executeWithMetrics("bytes", null, null, true);
+    assertEquals(1, dry.filesRemoved());
+    assertEquals(payload.length, dry.bytesReclaimed());
+    assertTrue(Files.exists(old));
+    IcebergRemoveOrphanFilesJob.OrphanCleanupResult deleted =
+        executeWithMetrics("bytes", null, null, false);
+    assertEquals(1, deleted.filesRemoved());
+    assertEquals(payload.length, deleted.bytesReclaimed());
+    assertFalse(Files.exists(old));
   }
 
   /** Verifies blank locations default to the table root without CLI argument 
parsing. */
@@ -103,16 +121,11 @@ public class TestIcebergRemoveOrphanFilesJobWithSpark {
     Path root = tempDir.resolve("db/blank_location");
     Path old = Files.write(root.resolve("old-orphan"), new byte[] {1});
     Files.setLastModifiedTime(old, FileTime.from(Instant.now().minus(5, 
ChronoUnit.DAYS)));
-    Map<String, String> options = args("blank_location");
-    options.put("dry-run", "true");
     for (String location : new String[] {"", " ", "\t", "\u2003"}) {
-      options.put("location", location);
-      assertEquals(1, IcebergRemoveOrphanFilesJob.execute(spark, options));
+      assertEquals(1, execute("blank_location", null, location, true).size());
       assertTrue(Files.exists(old));
     }
-    options.put("location", "");
-    options.put("dry-run", "false");
-    assertEquals(1, IcebergRemoveOrphanFilesJob.execute(spark, options));
+    assertEquals(1, execute("blank_location", null, "", false).size());
     assertFalse(Files.exists(old));
   }
 
@@ -127,20 +140,16 @@ public class TestIcebergRemoveOrphanFilesJobWithSpark {
     FileTime old = FileTime.from(Instant.now().minus(5, ChronoUnit.DAYS));
     Files.setLastModifiedTime(inside, old);
     Files.setLastModifiedTime(outside, old);
-    Map<String, String> args = args("scoped");
-    args.put("location", sub.toString());
-    assertEquals(1, IcebergRemoveOrphanFilesJob.execute(spark, args));
+    assertEquals(1, execute("scoped", null, sub.toString(), false).size());
     assertFalse(Files.exists(inside));
     assertTrue(Files.exists(outside));
-    args.put("location", tempDir.toString());
     assertThrows(
-        IllegalArgumentException.class, () -> 
IcebergRemoveOrphanFilesJob.execute(spark, args));
+        IllegalArgumentException.class, () -> execute("scoped", null, 
tempDir.toString(), false));
     assertTrue(Files.exists(outside));
     Path link = root.resolve("escape");
     Files.createSymbolicLink(link, tempDir);
-    args.put("location", link.toString());
     assertThrows(
-        IllegalArgumentException.class, () -> 
IcebergRemoveOrphanFilesJob.execute(spark, args));
+        IllegalArgumentException.class, () -> execute("scoped", null, 
link.toString(), false));
   }
 
   /** Verifies UTC cutoffs from the policy adapter retain their meaning in 
other session zones. */
@@ -153,12 +162,11 @@ public class TestIcebergRemoveOrphanFilesJobWithSpark {
     Path newer = Files.write(root.resolve("newer"), new byte[] {1});
     Files.setLastModifiedTime(older, FileTime.from(cutoff.minusSeconds(60)));
     Files.setLastModifiedTime(newer, FileTime.from(cutoff.plusSeconds(60)));
-    Map<String, String> options = args("utc_cutoff");
-    options.put("older-than", cutoff.toString().replace("T", " "));
+    String olderThan = cutoff.toString().replace("T", " ");
     String timezone = spark.conf().get("spark.sql.session.timeZone");
     spark.conf().set("spark.sql.session.timeZone", "America/Los_Angeles");
     try {
-      assertEquals(1, IcebergRemoveOrphanFilesJob.execute(spark, options));
+      assertEquals(1, execute("utc_cutoff", olderThan, null, false).size());
       assertFalse(Files.exists(older));
       assertTrue(Files.exists(newer));
     } finally {
@@ -170,23 +178,17 @@ public class TestIcebergRemoveOrphanFilesJobWithSpark {
   @Test
   public void testInvalidInputsFailBeforeDeletion() throws Exception {
     spark.sql("CREATE TABLE test_catalog.db.invalid (id INT) USING iceberg");
-    Map<String, String> options = args("invalid");
-    options.put("dry-run", "yes");
     assertThrows(
-        IllegalArgumentException.class, () -> 
IcebergRemoveOrphanFilesJob.execute(spark, options));
-    options.remove("dry-run");
-    options.put("location", tempDir.resolve("db/invalid/missing").toString());
-    assertThrows(IOException.class, () -> 
IcebergRemoveOrphanFilesJob.execute(spark, options));
-    options.remove("location");
-    options.put("older-than", "2999-01-01 00:00:00");
+        IllegalArgumentException.class, () -> 
IcebergRemoveOrphanFilesJob.parseDryRun("yes"));
+    assertThrows(
+        IOException.class,
+        () -> execute("invalid", null, 
tempDir.resolve("db/invalid/missing").toString(), false));
     assertThrows(
-        IllegalArgumentException.class, () -> 
IcebergRemoveOrphanFilesJob.execute(spark, options));
-    options.remove("older-than");
+        IllegalArgumentException.class,
+        () -> execute("invalid", "2999-01-01 00:00:00", null, false));
     spark.conf().set("spark.sql.parser.escapedStringLiterals", "true");
     try {
-      assertThrows(
-          IllegalArgumentException.class,
-          () -> IcebergRemoveOrphanFilesJob.execute(spark, options));
+      assertThrows(IllegalArgumentException.class, () -> execute("invalid", 
null, null, false));
     } finally {
       spark.conf().set("spark.sql.parser.escapedStringLiterals", "false");
     }
@@ -215,21 +217,31 @@ public class TestIcebergRemoveOrphanFilesJobWithSpark {
     Path newer = Files.write(location.resolve("newer"), new byte[] {1});
     Files.setLastModifiedTime(old, 
FileTime.from(Instant.parse("2023-01-01T00:00:00Z")));
     Files.setLastModifiedTime(newer, 
FileTime.from(Instant.parse("2025-01-01T00:00:00Z")));
-    Map<String, String> options = args("`quo'te`");
-    options.put("older-than", "2024-01-01 00:00:00");
-    options.put("dry-run", "true");
-    assertEquals(1, IcebergRemoveOrphanFilesJob.execute(spark, options));
+    String table = "db.`quo'te`";
+    assertEquals(
+        1,
+        IcebergRemoveOrphanFilesJob.execute(
+                spark, "test_catalog", table, "2024-01-01 00:00:00", null, 
true)
+            .size());
     assertTrue(Files.exists(old));
-    options.put("dry-run", "false");
-    assertEquals(1, IcebergRemoveOrphanFilesJob.execute(spark, options));
+    assertEquals(
+        1,
+        IcebergRemoveOrphanFilesJob.execute(
+                spark, "test_catalog", table, "2024-01-01 00:00:00", null, 
false)
+            .size());
     assertFalse(Files.exists(old));
     assertTrue(Files.exists(newer));
   }
 
-  private static Map<String, String> args(String table) {
-    Map<String, String> args = new HashMap<>();
-    args.put("catalog", "test_catalog");
-    args.put("table", "db." + table);
-    return args;
+  private static List<Row> execute(String table, String olderThan, String 
location, boolean dryRun)
+      throws IOException {
+    return IcebergRemoveOrphanFilesJob.execute(
+        spark, "test_catalog", "db." + table, olderThan, location, dryRun);
+  }
+
+  private static IcebergRemoveOrphanFilesJob.OrphanCleanupResult 
executeWithMetrics(
+      String table, String olderThan, String location, boolean dryRun) throws 
IOException {
+    return IcebergRemoveOrphanFilesJob.executeWithMetrics(
+        spark, "test_catalog", "db." + table, olderThan, location, dryRun);
   }
 }
diff --git 
a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.java
 
b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.java
index 7aec76aad0..0fc2d0bd54 100644
--- 
a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.java
+++ 
b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.java
@@ -28,6 +28,7 @@ import java.util.Arrays;
 import java.util.Map;
 import org.apache.gravitino.job.JobTemplateProvider;
 import org.apache.gravitino.job.SparkJobTemplate;
+import org.apache.gravitino.policy.IcebergDataCompactionContent;
 import org.junit.jupiter.api.Test;
 
 public class TestIcebergRewriteDataFilesJob {
@@ -134,7 +135,7 @@ public class TestIcebergRewriteDataFilesJob {
     
assertTrue(customFields.containsKey(JobTemplateProvider.PROPERTY_VERSION_KEY));
 
     String version = 
customFields.get(JobTemplateProvider.PROPERTY_VERSION_KEY);
-    assertEquals("v3", version);
+    assertEquals("v1", version);
     assertTrue(version.matches(JobTemplateProvider.VERSION_VALUE_PATTERN));
   }
 
@@ -147,99 +148,6 @@ public class TestIcebergRewriteDataFilesJob {
     
assertTrue(template.name().startsWith(JobTemplateProvider.BUILTIN_NAME_PREFIX));
   }
 
-  // Test parseArguments method
-
-  @Test
-  public void testParseArgumentsWithAllRequired() {
-    String[] args = {"--catalog", "iceberg_prod", "--table", "db.sample"};
-    Map<String, String> result = 
IcebergRewriteDataFilesJob.parseArguments(args);
-
-    assertEquals(2, result.size());
-    assertEquals("iceberg_prod", result.get("catalog"));
-    assertEquals("db.sample", result.get("table"));
-  }
-
-  @Test
-  public void testParseArgumentsWithOptional() {
-    String[] args = {
-      "--catalog", "iceberg_prod",
-      "--table", "db.sample",
-      "--strategy", "binpack",
-      "--where", "year = 2024"
-    };
-    Map<String, String> result = 
IcebergRewriteDataFilesJob.parseArguments(args);
-
-    assertEquals(4, result.size());
-    assertEquals("iceberg_prod", result.get("catalog"));
-    assertEquals("db.sample", result.get("table"));
-    assertEquals("binpack", result.get("strategy"));
-    assertEquals("year = 2024", result.get("where"));
-  }
-
-  @Test
-  public void testParseArgumentsWithEmptyValues() {
-    String[] args = {"--catalog", "iceberg_prod", "--table", "db.sample", 
"--strategy", ""};
-    Map<String, String> result = 
IcebergRewriteDataFilesJob.parseArguments(args);
-
-    // Empty values should be ignored
-    assertEquals(2, result.size());
-    assertEquals("iceberg_prod", result.get("catalog"));
-    assertEquals("db.sample", result.get("table"));
-    assertFalse(result.containsKey("strategy"));
-  }
-
-  @Test
-  public void testParseArgumentsWithMissingValues() {
-    String[] args = {"--catalog", "iceberg_prod", "--table"};
-    Map<String, String> result = 
IcebergRewriteDataFilesJob.parseArguments(args);
-
-    // catalog has a value, table is a flag at end (treated as boolean)
-    assertEquals(2, result.size());
-    assertEquals("iceberg_prod", result.get("catalog"));
-    assertEquals("true", result.get("table"));
-  }
-
-  @Test
-  public void testParseArgumentsWithComplexValues() {
-    String[] args = {
-      "--catalog", "iceberg_prod",
-      "--table", "db.sample",
-      "--where", "year = 2024 and month = 1",
-      "--options", "{\"min-input-files\":\"2\"}"
-    };
-    Map<String, String> result = 
IcebergRewriteDataFilesJob.parseArguments(args);
-
-    assertEquals(4, result.size());
-    assertEquals("year = 2024 and month = 1", result.get("where"));
-    assertEquals("{\"min-input-files\":\"2\"}", result.get("options"));
-  }
-
-  @Test
-  public void testParseArgumentsWithSortOrder() {
-    String[] args = {
-      "--catalog", "iceberg_prod",
-      "--table", "db.sample",
-      "--strategy", "sort",
-      "--sort-order", "id DESC NULLS LAST, name ASC"
-    };
-    Map<String, String> result = 
IcebergRewriteDataFilesJob.parseArguments(args);
-
-    assertEquals(4, result.size());
-    assertEquals("sort", result.get("strategy"));
-    assertEquals("id DESC NULLS LAST, name ASC", result.get("sort-order"));
-  }
-
-  @Test
-  public void testParseArgumentsOrderIndependent() {
-    String[] args1 = {"--catalog", "cat1", "--table", "tbl1", "--strategy", 
"binpack"};
-    String[] args2 = {"--strategy", "binpack", "--table", "tbl1", "--catalog", 
"cat1"};
-
-    Map<String, String> result1 = 
IcebergRewriteDataFilesJob.parseArguments(args1);
-    Map<String, String> result2 = 
IcebergRewriteDataFilesJob.parseArguments(args2);
-
-    assertEquals(result1, result2);
-  }
-
   // Test parseOptionsJson method
 
   @Test
@@ -521,34 +429,6 @@ public class TestIcebergRewriteDataFilesJob {
     assertTrue(sql.contains("'remove-dangling-deletes', 'true'"));
   }
 
-  @Test
-  public void testEscapeSqlString() {
-    // Test basic escaping of single quotes
-    assertEquals("O''Brien", 
IcebergRewriteDataFilesJob.escapeSqlString("O'Brien"));
-    assertEquals(
-        "test''with''quotes", 
IcebergRewriteDataFilesJob.escapeSqlString("test'with'quotes"));
-
-    // Test strings without quotes remain unchanged
-    assertEquals("normal_string", 
IcebergRewriteDataFilesJob.escapeSqlString("normal_string"));
-
-    // Test null and empty
-    assertEquals(null, IcebergRewriteDataFilesJob.escapeSqlString(null));
-    assertEquals("", IcebergRewriteDataFilesJob.escapeSqlString(""));
-  }
-
-  @Test
-  public void testEscapeSqlIdentifier() {
-    // Test basic escaping and quoting of backticks
-    assertEquals("`catalog``name`", 
IcebergRewriteDataFilesJob.escapeSqlIdentifier("catalog`name"));
-
-    // Test strings without backticks are still quoted
-    assertEquals(
-        "`normal_catalog`", 
IcebergRewriteDataFilesJob.escapeSqlIdentifier("normal_catalog"));
-
-    // Test null
-    assertEquals(null, IcebergRewriteDataFilesJob.escapeSqlIdentifier(null));
-  }
-
   @Test
   public void testBuildProcedureCallWithSqlInjectionAttempt() {
     // Test SQL injection attempt in table name
@@ -657,58 +537,21 @@ public class TestIcebergRewriteDataFilesJob {
     }
   }
 
-  // Tests for custom Spark configurations
-
-  @Test
-  public void testParseCustomSparkConfigsWithValidJson() {
-    String json = 
"{\"spark.sql.shuffle.partitions\":\"200\",\"spark.executor.memory\":\"4g\"}";
-    Map<String, String> configs = 
IcebergRewriteDataFilesJob.parseCustomSparkConfigs(json);
-
-    assertEquals(2, configs.size());
-    assertEquals("200", configs.get("spark.sql.shuffle.partitions"));
-    assertEquals("4g", configs.get("spark.executor.memory"));
-  }
-
-  @Test
-  public void testParseCustomSparkConfigsWithNumericValues() {
-    String json = 
"{\"spark.sql.shuffle.partitions\":200,\"spark.executor.cores\":4}";
-    Map<String, String> configs = 
IcebergRewriteDataFilesJob.parseCustomSparkConfigs(json);
-
-    assertEquals(2, configs.size());
-    assertEquals("200", configs.get("spark.sql.shuffle.partitions"));
-    assertEquals("4", configs.get("spark.executor.cores"));
-  }
-
   @Test
-  public void testParseCustomSparkConfigsWithBooleanValues() {
-    String json = 
"{\"spark.dynamicAllocation.enabled\":true,\"spark.speculation\":false}";
-    Map<String, String> configs = 
IcebergRewriteDataFilesJob.parseCustomSparkConfigs(json);
-
-    assertEquals(2, configs.size());
-    assertEquals("true", configs.get("spark.dynamicAllocation.enabled"));
-    assertEquals("false", configs.get("spark.speculation"));
-  }
-
-  @Test
-  public void testParseCustomSparkConfigsWithEmptyString() {
-    Map<String, String> configs = 
IcebergRewriteDataFilesJob.parseCustomSparkConfigs("");
-    assertTrue(configs.isEmpty());
-  }
-
-  @Test
-  public void testParseCustomSparkConfigsWithNull() {
-    Map<String, String> configs = 
IcebergRewriteDataFilesJob.parseCustomSparkConfigs(null);
-    assertTrue(configs.isEmpty());
-  }
-
-  @Test
-  public void testParseCustomSparkConfigsWithInvalidJson() {
-    String json = "{invalid json}";
-    try {
-      IcebergRewriteDataFilesJob.parseCustomSparkConfigs(json);
-      fail("Expected IllegalArgumentException for invalid JSON");
-    } catch (IllegalArgumentException e) {
-      assertTrue(e.getMessage().contains("--spark-conf"));
-    }
+  public void testCompactionMetricsSchemaForTms() {
+    Map<String, Object> metrics =
+        IcebergRewriteDataFilesJob.compactionMetrics(1.23e15, 42L, 126877696D, 
9876543210L, 80L);
+    assertEquals(5, metrics.size());
+    assertEquals(
+        1.23e15,
+        ((Number) 
metrics.get(IcebergDataCompactionContent.DATA_FILE_MSE_METRIC)).doubleValue());
+    assertEquals(
+        126877696D,
+        ((Number) 
metrics.get(IcebergDataCompactionContent.AVG_FILE_SIZE_METRIC)).doubleValue());
+    assertEquals(
+        9876543210L,
+        ((Number) 
metrics.get(IcebergDataCompactionContent.TOTAL_FILE_SIZE_METRIC)).longValue());
+    assertEquals(
+        80L, ((Number) 
metrics.get(IcebergDataCompactionContent.FILE_NUMBER_METRIC)).longValue());
   }
 }
diff --git 
a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.java
 
b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.java
index 7f819d1d41..f49afa3c11 100644
--- 
a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.java
+++ 
b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.java
@@ -33,6 +33,7 @@ import java.util.Arrays;
 import java.util.Map;
 import org.apache.gravitino.job.JobTemplateProvider;
 import org.apache.gravitino.job.SparkJobTemplate;
+import org.apache.gravitino.policy.IcebergRewriteManifestsContent;
 import org.junit.jupiter.api.Test;
 
 public class TestIcebergRewriteManifestsJob {
@@ -197,7 +198,7 @@ public class TestIcebergRewriteManifestsJob {
     
assertTrue(customFields.containsKey(JobTemplateProvider.PROPERTY_VERSION_KEY));
 
     String version = 
customFields.get(JobTemplateProvider.PROPERTY_VERSION_KEY);
-    assertEquals("v3", version);
+    assertEquals("v1", version);
     assertTrue(version.matches(JobTemplateProvider.VERSION_VALUE_PATTERN));
   }
 
@@ -445,4 +446,19 @@ public class TestIcebergRewriteManifestsJob {
     // Verify backticks are escaped and the whole identifier stays quoted
     assertTrue(sql.startsWith("CALL `catalog``; DROP TABLE users; 
--`.system.rewrite_manifests("));
   }
+
+  @Test
+  public void testManifestMetricsSchemaForTms() {
+    Map<String, Object> before = 
IcebergRewriteManifestsJob.manifestBeforeMetrics(120L, 8388608D);
+    assertEquals(2, before.size());
+    assertEquals(
+        120L,
+        ((Number) 
before.get(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC)).longValue());
+    Map<String, Object> after = 
IcebergRewriteManifestsJob.manifestAfterMetrics(18750L);
+    assertEquals(1, after.size());
+    assertEquals(
+        18750L,
+        ((Number) 
after.get(IcebergRewriteManifestsContent.REWRITTEN_MANIFEST_NUMBER_METRIC))
+            .longValue());
+  }
 }
diff --git 
a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJobWithSpark.java
 
b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJobWithSpark.java
index e91877dcea..00b2763952 100644
--- 
a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJobWithSpark.java
+++ 
b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJobWithSpark.java
@@ -305,18 +305,11 @@ public class TestIcebergRewriteManifestsJobWithSpark {
       System.setOut(originalOut);
     }
     String stdout = output.toString(StandardCharsets.UTF_8);
-    String expectedSql = "CALL 
`manifest_catalog`.system.rewrite_manifests(table => 'db.events'";
-    if (caching != null) {
-      expectedSql += ", use_caching => " + caching;
-    }
-    if (spec != null) {
-      expectedSql += ", spec_id => " + spec;
-    }
-    expectedSql += ")";
-    int execution = stdout.indexOf("Executing Iceberg rewrite_manifests 
procedure: " + expectedSql);
+    // Execution SQL is LOG.info only; Spark IT asserts the System.out 
result/success contract.
     int results = stdout.indexOf("Rewrite Manifests Results: Rewritten 
manifests:");
-    assertTrue(execution >= 0, stdout);
-    assertTrue(results > execution, stdout);
+    int success = stdout.indexOf("Rewrite manifests job completed 
successfully");
+    assertTrue(results >= 0, stdout);
+    assertTrue(success > results, stdout);
     if (SparkSession.getActiveSession().isDefined()) {
       
assertTrue(SparkSession.getActiveSession().get().sparkContext().isStopped());
     }
diff --git 
a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestMaintenanceTriggerGate.java
 
b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestMaintenanceTriggerGate.java
index 10abbe887f..1d08cc464a 100644
--- 
a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestMaintenanceTriggerGate.java
+++ 
b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestMaintenanceTriggerGate.java
@@ -25,16 +25,17 @@ import java.util.HashMap;
 import java.util.Map;
 import 
org.apache.gravitino.maintenance.jobs.iceberg.IcebergMaintenanceJob.MaintenanceType;
 import org.apache.gravitino.policy.IcebergDataCompactionContent;
+import org.apache.gravitino.policy.IcebergRewriteManifestsContent;
 import org.junit.jupiter.api.Test;
 
 /** Unit tests for {@link MaintenanceTriggerGate}. */
 public class TestMaintenanceTriggerGate {
 
   @Test
-  public void testNonCompactionAlwaysMaintain() {
+  public void testExpireSnapshotsAlwaysMaintain() {
     assertTrue(
         MaintenanceTriggerGate.shouldMaintain(
-            MaintenanceType.EXPIRE_SNAPSHOTS, new HashMap<>(), 
"{\"snapshotId\":1}"));
+            MaintenanceType.EXPIRE_SNAPSHOTS, new HashMap<>(), 
"{\"custom-snapshot-number\":1}"));
   }
 
   @Test
@@ -64,4 +65,83 @@ public class TestMaintenanceTriggerGate {
     assertTrue(
         
MaintenanceTriggerGate.shouldMaintain(MaintenanceType.REWRITE_DATA_FILES, args, 
above));
   }
+
+  @Test
+  public void testManifestRewriteUsesDefaultThresholds() {
+    // Defaults: critical=500, warning=100, avg threshold=8MiB.
+    String belowWarning =
+        "{\""
+            + IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC
+            + "\":50,\""
+            + IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC
+            + "\":1000}";
+    assertFalse(
+        MaintenanceTriggerGate.shouldMaintain(
+            MaintenanceType.REWRITE_MANIFESTS, new HashMap<>(), belowWarning));
+
+    String warningAndSmall =
+        "{\""
+            + IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC
+            + "\":120,\""
+            + IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC
+            + "\":1000}";
+    assertTrue(
+        MaintenanceTriggerGate.shouldMaintain(
+            MaintenanceType.REWRITE_MANIFESTS, new HashMap<>(), 
warningAndSmall));
+
+    String critical =
+        "{\""
+            + IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC
+            + "\":500,\""
+            + IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC
+            + "\":9000000}";
+    assertTrue(
+        MaintenanceTriggerGate.shouldMaintain(
+            MaintenanceType.REWRITE_MANIFESTS, new HashMap<>(), critical));
+
+    String warningButLarge =
+        "{\""
+            + IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC
+            + "\":120,\""
+            + IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC
+            + "\":9000000}";
+    assertFalse(
+        MaintenanceTriggerGate.shouldMaintain(
+            MaintenanceType.REWRITE_MANIFESTS, new HashMap<>(), 
warningButLarge));
+  }
+
+  @Test
+  public void testManifestRewriteUsesEnqueueRules() {
+    Map<String, String> args = new HashMap<>();
+    args.put(
+        MaintenanceTriggerGate.RULES_ARG,
+        "{\"rewrite_manifests\":{"
+            + "\"trigger-expr\":\"custom-manifest-number >= 
manifest_count_critical\","
+            + "\"manifest_count_critical\":10}}");
+
+    String below =
+        "{\""
+            + IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC
+            + "\":5,\""
+            + IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC
+            + "\":1}";
+    assertFalse(
+        
MaintenanceTriggerGate.shouldMaintain(MaintenanceType.REWRITE_MANIFESTS, args, 
below));
+
+    String above =
+        "{\""
+            + IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC
+            + "\":10,\""
+            + IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC
+            + "\":1}";
+    assertTrue(
+        
MaintenanceTriggerGate.shouldMaintain(MaintenanceType.REWRITE_MANIFESTS, args, 
above));
+  }
+
+  @Test
+  public void testManifestRewriteSkipsWhenMetricsMissing() {
+    assertFalse(
+        MaintenanceTriggerGate.shouldMaintain(
+            MaintenanceType.REWRITE_MANIFESTS, new HashMap<>(), "{}"));
+  }
 }
diff --git 
a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/MaintenanceJobConfBuilder.java
 
b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/MaintenanceJobConfBuilder.java
index 7620f74c28..b6606afaab 100644
--- 
a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/MaintenanceJobConfBuilder.java
+++ 
b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/MaintenanceJobConfBuilder.java
@@ -242,6 +242,15 @@ public final class MaintenanceJobConfBuilder {
     putIfAbsentSparkFromPlaceholder(jobConf, sparkConf, "catalog_uri", 
catalogPrefix + ".uri");
     putIfAbsentSparkFromPlaceholder(
         jobConf, sparkConf, "warehouse_location", catalogPrefix + 
".warehouse");
+    // IcebergMaintenanceJob builds SparkSession from spark_conf JSON alone in 
some executors;
+    // without the catalog impl class, Spark falls back to spark_catalog and 
multipart names fail.
+    if (sparkConf.containsKey(catalogPrefix + ".type")
+        || sparkConf.containsKey(catalogPrefix + ".uri")
+        || sparkConf.containsKey(catalogPrefix + ".warehouse")) {
+      sparkConf.putIfAbsent(catalogPrefix, 
"org.apache.iceberg.spark.SparkCatalog");
+      sparkConf.putIfAbsent(
+          "spark.sql.extensions", 
IcebergSparkConfigUtils.ICEBERG_SPARK_EXTENSIONS);
+    }
     if (!sparkConf.isEmpty()) {
       jobConf.put("spark_conf", writeJson(sparkConf, "spark_conf"));
     }
diff --git 
a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/TestMaintenanceJobConfBuilder.java
 
b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/TestMaintenanceJobConfBuilder.java
index 8880a1b598..3f501c382c 100644
--- 
a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/TestMaintenanceJobConfBuilder.java
+++ 
b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/TestMaintenanceJobConfBuilder.java
@@ -21,8 +21,10 @@ package org.apache.gravitino.maintenance.scheduler.job;
 import java.time.Clock;
 import java.time.Instant;
 import java.time.ZoneOffset;
+import java.util.HashMap;
 import java.util.Map;
 import org.apache.gravitino.Config;
+import org.apache.gravitino.json.JsonUtils;
 import org.apache.gravitino.maintenance.policy.MaintenanceAuthConfigs;
 import org.apache.gravitino.meta.AuditInfo;
 import org.apache.gravitino.meta.PolicyEntity;
@@ -248,6 +250,27 @@ class TestMaintenanceJobConfBuilder {
     Assertions.assertFalse(conf.get("updater_options").contains("policy-ml"));
   }
 
+  @Test
+  void testFoldPlaceholdersFillsIcebergCatalogImpl() throws Exception {
+    Map<String, String> jobConf = new HashMap<>();
+    jobConf.put("catalog_type", "rest");
+    jobConf.put("catalog_uri", "http://localhost:9001/iceberg";);
+    jobConf.put("warehouse_location", "wh");
+    jobConf.put("spark_conf", "{}");
+
+    MaintenanceJobConfBuilder.foldPlaceholdersIntoSparkConf(jobConf, 
"iceberg");
+
+    @SuppressWarnings("unchecked")
+    Map<String, String> sparkConf =
+        JsonUtils.anyFieldMapper().readValue(jobConf.get("spark_conf"), 
Map.class);
+    Assertions.assertEquals(
+        "org.apache.iceberg.spark.SparkCatalog", 
sparkConf.get("spark.sql.catalog.iceberg"));
+    Assertions.assertEquals("rest", 
sparkConf.get("spark.sql.catalog.iceberg.type"));
+    Assertions.assertEquals(
+        "http://localhost:9001/iceberg";, 
sparkConf.get("spark.sql.catalog.iceberg.uri"));
+    Assertions.assertTrue(sparkConf.containsKey("spark.sql.extensions"));
+  }
+
   private static Config configWithUri() {
     Config config = new Config(false) {};
     config.loadFromMap(

Reply via email to