Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#14807] docs(tms): secured IRC/S3 walkthrough and per-task sections (#14808)

MaSai103727106a2c
diff --git a/docs/table-maintenance-service/optimizer-cli-reference.md b/docs/table-maintenance-service/optimizer-cli-reference.md
index b7f6ff8e2b..75bd2113e1 100644
--- a/docs/table-maintenance-service/optimizer-cli-reference.md
+++ b/docs/table-maintenance-service/optimizer-cli-reference.md
@@ -18,7 +18,7 @@ directory. Use `--conf-path` only when you need a custom config file.
## Command Quick Reference
| Command (`--type`) | Required options | Optional options | Purpose |
-|---------------------------|------------------------------------|-------------------------------------------------------------------|---------------------------------------------------------|
+| ------------------------- | ---------------------------------- | ----------------------------------------------------------------- | ------------------------------------------------------- |
| `submit-strategy-jobs` | `--identifiers`, `--strategy-name` | `--dry-run`, `--limit` | Recommend and optionally submit jobs |
| `update-statistics` | `--calculator-name` | `--identifiers`, `--statistics-payload`, `--file-path` | Calculate and persist statistics |
| `append-metrics` | `--calculator-name` | `--identifiers`, `--statistics-payload`, `--file-path` | Calculate and append metrics |
@@ -30,7 +30,7 @@ directory. Use `--conf-path` only when you need a custom config file.
## Option Field Meanings
| Option | Meaning | Used by |
-|------------------------|------------------------------------------------------------------------------------------------------|---------------------------------------------------|
+| ---------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------- |
| `--identifiers` | Comma-separated identifiers. See [Identifier Rules](#identifier-rules) for command-specific formats. | All commands |
| `--strategy-name` | Policy name to evaluate, for example `iceberg_compaction_default`. | `submit-strategy-jobs` |
| `--dry-run` | Preview mode. Prints recommendations or job configs without submitting jobs. | `submit-strategy-jobs`, `submit-update-stats-job` |
@@ -243,7 +243,7 @@ EvaluationResult{scopeType=TABLE, identifier=rest_catalog.db.t1, partitionPath=<
The following Iceberg job templates ship with the service. A full maintenance pass collects statistics, compacts data files, expires the snapshot history that compaction just created, consolidates manifests, and removes old orphan files.
| Job template | What it does |
-|-----------------------------------------|------------------------------------------|
+| --------------------------------------- | ---------------------------------------- |
| `builtin-iceberg-update-stats` | Collects file statistics and metrics |
| `builtin-iceberg-rewrite-data-files` | Compacts small data files |
| `builtin-iceberg-expire-snapshots` | Removes old snapshot metadata |
@@ -251,7 +251,9 @@ The following Iceberg job templates ship with the service. A full maintenance pa
| `builtin-iceberg-rewrite-manifests` | Consolidates small manifest files |
| `builtin-iceberg-update-manifest-stats` | Collects complete per-spec manifest maps |
-Each can be submitted directly over REST, and the first two are also what the policy-driven workflow submits on your behalf. See [Quick Start](./optimizer.md#walkthrough) for the policy-driven path.
+Each can be submitted directly over REST. Compaction, manifest rewrite, snapshot expiry, and
+orphan cleanup also have policy-driven paths through `submit-strategy-jobs`. See
+[Walkthrough](./optimizer.md#walkthrough).
These templates set Iceberg Spark session and catalog classes, but they do not list an Iceberg Spark
runtime in `jars`. `gravitino-jobs` also excludes that runtime from its shaded JAR, so the version
@@ -274,7 +276,7 @@ missing keys. An empty string is a value, not an omission: it overrides the defa
"not set" to these jobs.
| Job template | Required keys | Optional keys and defaults |
-|---------------------------------------|-----------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| ------------------------------------- | --------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Every Iceberg job | `catalog_name`, `table_identifier`, `catalog_type`, `catalog_uri`, `warehouse_location` | `spark_master` (empty), `spark_executor_instances` (`1`), `spark_executor_cores` (`1`), `spark_executor_memory` (`1g`), `spark_driver_memory` (`1g`), `spark_conf` (empty) |
| `builtin-iceberg-update-stats` | — | `update_mode` (`all`), `updater_options` (empty) |
| `builtin-iceberg-rewrite-data-files` | `where_clause` (pass `""` to rewrite the whole table) | `strategy` (`binpack`), `sort_order` (empty), `options` (empty) |
@@ -304,7 +306,7 @@ Its `jobConf` is documented in [Configuration](./optimizer-configuration.md#job-
statistics, including for partitioned tables:
| Statistic | Object entry for each decimal spec ID |
-|------------------------------------|---------------------------------------|
+| ---------------------------------- | ------------------------------------- |
| `custom-manifest-number-by-spec` | Long manifest count |
| `custom-avg-manifest-size-by-spec` | Double average manifest size in bytes |
@@ -401,56 +403,60 @@ locks. If the previous PUT outcome cannot be established, leave the marker intac
Consumers must read both objects from one table-statistics response and use the same chosen
spec key in each. A missing object or key means collection is required, not zero manifests.
`IcebergManifestStatistics.fromStatistics` returns an empty result for an incomplete pair.
-Automatic manifest policy triggering is separate follow-up work.
+After collection, evaluate and submit with a `system_iceberg_rewrite_manifests` policy through
+`submit-strategy-jobs` (see [Rewrite Manifests](#rewrite-manifests)).
## Rewrite Data Files
-`builtin-iceberg-rewrite-data-files` performs the compaction itself, merging small data files into larger ones. It is what a compaction policy submits when its thresholds are crossed.
+`builtin-iceberg-rewrite-data-files` merges small Iceberg data files into larger ones. It is the
+compaction job: a compaction policy submits it when thresholds are crossed, and you can also run it
+directly with `POST .../jobs/runs`.
-In alpha this works only on Iceberg tables where every partition uses an identity transform. Tables combining identity with a time or bucket transform fail during the rewrite, which is covered in [Troubleshooting](./optimizer-troubleshooting.md#job-execution-failures).
+| Property | Value |
+| ---------- | -------------------------------------------------------------------------- |
+| Name | `builtin-iceberg-rewrite-data-files` |
+| Type | Spark |
+| Version | `v1` |
+| Main class | `org.apache.gravitino.maintenance.jobs.iceberg.IcebergRewriteDataFilesJob` |
-For the policy that drives it, including threshold tuning, see [Iceberg Compaction Policy](../iceberg-compaction-policy.md).
-
-## Expire Snapshots
-
-`builtin-iceberg-expire-snapshots` removes old Iceberg snapshots and the metadata files behind them. Without periodic expiration, snapshot JSON files and manifest lists accumulate indefinitely, which slows table operations and wastes storage. Compaction makes this worse, since every rewrite creates a snapshot.
-
-The job calls Iceberg's `expire_snapshots` stored procedure through Spark SQL.
-
-| Property | Value |
-|-------------|-----------------------------------------------------------------------------|
-| Name | `builtin-iceberg-expire-snapshots` |
-| Type | Spark |
-| Version | `v1` |
-| Main class | `org.apache.gravitino.maintenance.jobs.iceberg.IcebergExpireSnapshotsJob` |
-
-## Parameters
-
-`catalog_name` and `table_identifier` are required. The rest are optional.
-
-| Key | Description | Default |
-|--------------------|------------------------------------------------------------------|---------------|
-| `catalog_name` | Iceberg catalog name as registered in Spark | Required |
-| `table_identifier` | Fully qualified table name, such as `db.sample` | Required |
-| `older_than` | Expire snapshots older than this `yyyy-MM-dd HH:mm:ss` timestamp | Five days ago |
-| `retain_last` | Minimum number of recent snapshots to keep regardless of age | `1` |
-| `stream_results` | Streams intermediate delete results when present | Disabled |
-| `spark_conf` | JSON map of Spark configuration | None |
+### Parameters
-`older_than` and `retain_last` work together, and `retain_last` wins. Setting `older_than` to yesterday with `retain_last` at `5` keeps five snapshots even if all five are older than yesterday.
+Besides the shared catalog keys, only `where_clause` is required with no template default (pass
+`""` to rewrite the whole table). `strategy` defaults to `binpack` and `sort_order` / `options`
+default to empty when omitted. An empty string is a value, not an omission: it overrides the
+default. Policy-driven `submit-strategy-jobs` fills these through the compaction adapter.
+
+| Key | Description | Default |
+| ------------------ | ------------------------------------------------------------------- | --------- |
+| `catalog_name` | Iceberg catalog name as registered in Spark | Required |
+| `table_identifier` | Fully qualified table name, such as `db.sample` | Required |
+| `where_clause` | Filter predicate; `""` rewrites the whole table | Required |
+| `strategy` | Iceberg rewrite strategy: `binpack` or `sort` | `binpack` |
+| `sort_order` | Sort order when `strategy` is `sort`; empty for `binpack` | empty |
+| `options` | JSON map of Iceberg rewrite options (for example `min-input-files`) | empty |
+| `spark_conf` | JSON map of Spark configuration | None |
+
+Include the shared Spark and catalog keys from [Built-in Job Templates](#built-in-job-templates).
+In alpha, prefer identity-partitioned tables for the **policy/strategy** path: partition filters
+built for time/bucket transforms can fail Spark filter translation. A direct submit with an empty
+`where_clause` rewrites the whole table and works on broader layouts such as
+`PARTITIONED BY (p, days(ts))`; see
+[Troubleshooting](./optimizer-troubleshooting.md#job-execution-failures).
-## Submitting the Job
+### Submitting the Job
```bash
curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
-H "Content-Type: application/json" \
-d '{
- "jobTemplateName": "builtin-iceberg-expire-snapshots",
+ "jobTemplateName": "builtin-iceberg-rewrite-data-files",
"jobConf": {
"catalog_name": "rest_catalog",
"table_identifier": "db.t1",
- "older_than": "2024-01-01 00:00:00",
- "retain_last": "3",
+ "strategy": "binpack",
+ "sort_order": "",
+ "where_clause": "",
+ "options": "",
"spark_master": "local[2]",
"spark_executor_instances": "1",
"spark_executor_cores": "1",
@@ -458,86 +464,77 @@ curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
"spark_driver_memory": "1g",
"catalog_type": "rest",
"catalog_uri": "http://localhost:9001/iceberg",
- "warehouse_location": ""
+ "warehouse_location": "",
+ "spark_conf": "{\"spark.hadoop.fs.defaultFS\":\"file:///\"}"
}
}' \
- http://localhost:8090/api/metalakes/test/jobs
+ http://localhost:8090/api/metalakes/test/jobs/runs
```
-Omitting `older_than` and passing only `retain_last` is the safer default for a first run, since it bounds the result by count rather than by a date you have to reason about.
-
-The job builds this statement, including only the optional parameters you supplied:
-
-```sql
-CALL `rest_catalog`.system.expire_snapshots(
- table => 'db.t1',
- older_than => TIMESTAMP '2024-01-01 00:00:00',
- retain_last => 3,
- stream_results => true
-)
-```
+Policy-driven submission uses `submit-strategy-jobs` with a compaction policy name. For threshold
+tuning see [Iceberg Compaction Policy](../iceberg-compaction-policy.md).
-## Verifying the Result
+### Verifying the Result
```bash
-curl -sS "http://localhost:8090/api/metalakes/test/jobs/{job_id}" | jq '.job.state'
-cat /tmp/gravitino/jobs/staging/job-runs/{job_id}/output.log
+curl -sS "http://localhost:8090/api/metalakes/test/jobs/runs/{job_id}" | jq '.job.status'
+cat /tmp/gravitino/jobs/staging/test/builtin-iceberg-rewrite-data-files/{job_id}/output.log
```
-A successful run reports its state as `SUCCEEDED` and logs the counts it removed:
-
-```text
-Expire Snapshots Results:
- Deleted data files: 12
- Deleted manifest files: 8
- Deleted manifest lists: 3
-```
+A successful run reports `SUCCEEDED`. Look for rewrite counts in the log. `Rewritten data files: N`
+with `N > 0` means data was compacted. `N = 0` with a successful job usually means fewer than
+Iceberg's `min-input-files` (default 5) eligible files — add more small files or pass rewrite
+options, then re-run.
## Rewrite Manifests
-`builtin-iceberg-rewrite-manifests` consolidates a table's manifest files. Frequent writes can leave many small manifests. Scan planning uses manifest-list summaries to prune them, then reads the remaining manifests. Rewriting consolidates and clusters entries for one existing partition spec without repartitioning data files.
-
-This complements `builtin-iceberg-rewrite-data-files`: that job improves the data file layout, this one improves the metadata that points at it.
+`builtin-iceberg-rewrite-manifests` consolidates a table's manifest files. Frequent writes can leave
+many small manifests. Scan planning uses manifest-list summaries to prune them, then reads the
+remaining manifests. Rewriting consolidates and clusters entries for one existing partition spec
+without repartitioning data files.
-The job calls Iceberg's `rewrite_manifests` stored procedure through Spark SQL.
+This complements `builtin-iceberg-rewrite-data-files`: that job improves the data file layout; this
+one improves the metadata that points at it.
-| Property | Value |
-| ------------- | ------------------------------------------------------------------------------ |
-| Name | `builtin-iceberg-rewrite-manifests` |
-| Type | Spark |
-| Version | `v1` |
-| Main class | `org.apache.gravitino.maintenance.jobs.iceberg.IcebergRewriteManifestsJob` |
+| Property | Value |
+| ---------- | -------------------------------------------------------------------------- |
+| Name | `builtin-iceberg-rewrite-manifests` |
+| Type | Spark |
+| Version | `v1` |
+| Main class | `org.apache.gravitino.maintenance.jobs.iceberg.IcebergRewriteManifestsJob` |
### Parameters
-`catalog_name` and `table_identifier` are required. For this job, omitted or blank optional argument values use the defaults below; unresolved optional template placeholders are also treated as absent.
-
-| Key | Description | Default |
-| -------------------- | ------------------------------------------------------------------------ | ----------------------------------- |
-| `catalog_name` | Iceberg catalog name as registered in Spark | Required |
-| `table_identifier` | Fully qualified table name, such as `db.sample` | Required |
-| `use_caching` | Caches table metadata in Spark while rewriting; `true` or `false` | Installed Iceberg version's default |
-| `spec_id` | Existing partition spec whose manifests to rewrite; non-negative integer | The table's current spec |
-| `spark_conf` | JSON map of Spark configuration | None |
-
-Leave `use_caching` unset to use the installed Iceberg version's default (`false` in Iceberg 1.11.0). Set it explicitly when consistent behavior across versions is required.
+`catalog_name` and `table_identifier` are required. Omitted or blank optional argument values use
+the defaults below; unresolved optional template placeholders are treated as absent.
-### How to find `spec_id`
+| Key | Description | Default |
+| ------------------ | ------------------------------------------------------------------------ | ----------------------------------- |
+| `catalog_name` | Iceberg catalog name as registered in Spark | Required |
+| `table_identifier` | Fully qualified table name, such as `db.sample` | Required |
+| `use_caching` | Caches table metadata in Spark while rewriting; `true` or `false` | Installed Iceberg version's default |
+| `spec_id` | Existing partition spec whose manifests to rewrite; non-negative integer | The table's current spec |
+| `spark_conf` | JSON map of Spark configuration | None |
-Omit `spec_id` for routine maintenance of the current partition spec. Do not guess IDs such as `0` or `1`. Read the reserved, read-only Gravitino table property `default-spec-id` for the current default. Use the `partition-specs` array in the table's Iceberg metadata JSON to see each `spec-id`'s partition fields and transforms.
+Leave `use_caching` unset to use the installed Iceberg version's default (`false` in Iceberg
+1.11.0). Set it explicitly when consistent behavior across versions is required.
-To discover which specs have manifests in the current snapshot, run:
+Omit `spec_id` for routine maintenance of the current partition spec. Do not guess IDs such as
+`0` or `1`. Read the reserved, read-only Gravitino table property `default-spec-id` for the current
+default. Use the `partition-specs` array in the table's Iceberg metadata JSON to see each
+`spec-id`'s partition fields and transforms. To list specs represented in the current snapshot:
```sql
SELECT DISTINCT partition_spec_id
FROM rest_catalog.db.t1.manifests;
```
-This query lists represented specs, not which one is current. A defined spec with no manifests may be absent; use `default-spec-id` to identify the current default and the metadata JSON to interpret the transforms.
-
-For example, suppose metadata shows spec `0` uses `day(event_time)` and the current spec `1` uses `hour(event_time)`. Omitting `spec_id` rewrites eligible manifests for spec `1`. Passing `"spec_id": "0"` consolidates the old day-spec manifests. Neither run converts day-partitioned data files to hour partitioning or rewrites manifests belonging to the other spec.
-
-`spec_id` selects the existing spec whose manifests are eligible for rewriting, and replacement manifests use that same spec. Iceberg validates that the ID exists. This follows the [Iceberg 1.11.0 action implementation](https://github.com/apache/iceberg/blob/apache-iceberg-1.11.0/spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/actions/RewriteManifestsSparkAction.java), where `findMatchingManifests` compares each manifest's `partitionSpecId()` to the selected spec. It is not a partition-evolution operation.
+`spec_id` selects the existing spec whose manifests are eligible; it is not a partition-evolution
+operation. Policy-driven submission uses `system_iceberg_rewrite_manifests` with strategy type
+`iceberg-rewrite-manifests` (handler and job adapter are built in). Collect manifest statistics
+first, then run `submit-strategy-jobs` with the policy name. See
+[Iceberg manifest rewrite policy](../iceberg-rewrite-manifests-policy.md) and
+[Configuration](./optimizer-configuration.md#rewrite-manifests).
### Submitting the Job
@@ -562,7 +559,7 @@ curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
http://localhost:8090/api/metalakes/test/jobs/runs
```
-The request above uses Iceberg defaults. Adding `"use_caching": "false"` and `"spec_id": "2"` to `jobConf` produces:
+Adding `"use_caching": "false"` and `"spec_id": "2"` to `jobConf` produces:
```sql
CALL `rest_catalog`.system.rewrite_manifests(
@@ -579,30 +576,119 @@ curl -sS "http://localhost:8090/api/metalakes/test/jobs/runs/{job_id}" | jq '.jo
cat /tmp/gravitino/jobs/staging/test/builtin-iceberg-rewrite-manifests/{job_id}/output.log
```
-A successful run reports its state as `SUCCEEDED` and logs how many manifests it replaced:
+A successful run reports `SUCCEEDED` and logs how many manifests it replaced:
```text
Rewrite Manifests Results: Rewritten manifests: 24, Added manifests: 2
```
-Both counts at zero indicate a successful no-op, for example when no manifests for the selected spec need rewriting. Other specs remain unchanged.
+Both counts at zero indicate a successful no-op (for example when no manifests for the selected
+spec need rewriting). Other specs remain unchanged.
-The [manifest rewrite policy](../iceberg-rewrite-manifests-policy.md) evaluates fresh per-spec
-measurements from the table-wide collector and submits this job with the evaluated `spec_id`.
+## Expire Snapshots
-## Related
+`builtin-iceberg-expire-snapshots` removes old Iceberg snapshots and the metadata files behind them.
+Without periodic expiration, snapshot JSON files and manifest lists accumulate, which slows table
+operations and wastes storage. Compaction and other rewrites create snapshots; expire cleans them up.
-- [Table Maintenance Service](./optimizer.md) for the concepts and the walkthrough
-- [Configuration](./optimizer-configuration.md) for the three configuration layers
-- [Iceberg Compaction Policy](../iceberg-compaction-policy.md) for tuning the built-in strategy
-- [Manage Jobs](../manage-jobs-in-gravitino.md) for job status and templates
+| Property | Value |
+| ---------- | ------------------------------------------------------------------------- |
+| Name | `builtin-iceberg-expire-snapshots` |
+| Type | Spark |
+| Version | `v1` |
+| Main class | `org.apache.gravitino.maintenance.jobs.iceberg.IcebergExpireSnapshotsJob` |
+
+### Parameters
+
+`catalog_name` and `table_identifier` are required. The rest are optional.
+
+| Key | Description | Default |
+| ------------------ | ---------------------------------------------------------------- | ------------- |
+| `catalog_name` | Iceberg catalog name as registered in Spark | Required |
+| `table_identifier` | Fully qualified table name, such as `db.sample` | Required |
+| `older_than` | Expire snapshots older than this `yyyy-MM-dd HH:mm:ss` timestamp | Five days ago |
+| `retain_last` | Minimum number of recent snapshots to keep regardless of age | `1` |
+| `stream_results` | Streams intermediate delete results when present | Disabled |
+| `spark_conf` | JSON map of Spark configuration | None |
+
+`older_than` and `retain_last` work together, and `retain_last` wins. Setting `older_than` to
+yesterday with `retain_last` at `5` keeps five snapshots even if all five are older than yesterday.
+Prefer starting with `retain_last` alone before combining it with `older_than`.
+
+### Submitting the Job
+
+```bash
+curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jobTemplateName": "builtin-iceberg-expire-snapshots",
+ "jobConf": {
+ "catalog_name": "rest_catalog",
+ "table_identifier": "db.t1",
+ "older_than": "2024-01-01 00:00:00",
+ "retain_last": "3",
+ "spark_master": "local[2]",
+ "spark_executor_instances": "1",
+ "spark_executor_cores": "1",
+ "spark_executor_memory": "1g",
+ "spark_driver_memory": "1g",
+ "catalog_type": "rest",
+ "catalog_uri": "http://localhost:9001/iceberg",
+ "warehouse_location": ""
+ }
+ }' \
+ http://localhost:8090/api/metalakes/test/jobs/runs
+```
+
+Omitting `older_than` and passing only `retain_last` is the safer default for a first run. The job
+builds a statement such as:
+
+```sql
+CALL `rest_catalog`.system.expire_snapshots(
+ table => 'db.t1',
+ older_than => TIMESTAMP '2024-01-01 00:00:00',
+ retain_last => 3,
+ stream_results => true
+)
+```
+
+Policy handler wiring is under
+[Snapshot expiration](./optimizer-configuration.md#snapshot-expiration).
+
+### Verifying the Result
+
+```bash
+curl -sS "http://localhost:8090/api/metalakes/test/jobs/runs/{job_id}" | jq '.job.status'
+cat /tmp/gravitino/jobs/staging/test/builtin-iceberg-expire-snapshots/{job_id}/output.log
+```
+
+A successful run reports `SUCCEEDED` and logs the counts it removed:
+
+```text
+Expire Snapshots Results:
+ Deleted data files: 12
+ Deleted manifest files: 8
+ Deleted manifest lists: 3
+```
## Remove Orphan Files
-`builtin-iceberg-remove-orphan-files` runs Iceberg's `remove_orphan_files` Spark
-procedure. It removes files in the scan location that are no longer referenced
-by table metadata. This job is available for direct submission; policy-driven
-scheduling is a separate feature.
+`builtin-iceberg-remove-orphan-files` runs Iceberg's `remove_orphan_files` Spark procedure. It
+removes files in the scan location that are no longer referenced by table metadata. Direct
+submission and policy-driven submission are both available.
+
+| Property | Value |
+| ---------- | --------------------------------------------------------------------------- |
+| Name | `builtin-iceberg-remove-orphan-files` |
+| Type | Spark |
+| Version | `v1` |
+| Main class | `org.apache.gravitino.maintenance.jobs.iceberg.IcebergRemoveOrphanFilesJob` |
+
+### Parameters
+
+`catalog_name` and `table_identifier` are required. Supply every template placeholder in `jobConf`:
+use empty strings for `older_than` and `location` to keep their defaults, an explicit boolean string
+for `dry_run`, and `{}` for `spark_conf` when no overrides are needed.
| Key | Description | Default |
| ------------------ | ---------------------------------------------------------------------------------------------- | -------------------------------- |
@@ -613,49 +699,59 @@ scheduling is a separate feature.
| `dry_run` | `true` logs candidate paths without deleting; `false` deletes | `false` |
| `spark_conf` | JSON map of custom Spark configuration | None |
-The template uses the same Spark and catalog connection settings as the other
-Iceberg jobs. Supply every template placeholder in `jobConf`: use empty strings
-for `older_than` and `location` to keep their defaults, an explicit boolean string
-for `dry_run`, and `{}` for `spark_conf` when no overrides are needed.
-For example, submit a preview using:
+Retain the three-day default unless a longer interval is needed. Iceberg 1.11's SQL procedure
+rejects explicit cutoffs less than 24 hours old, including for dry runs. A custom location must be
+the table's own location or a descendant, on the same storage scheme and authority. Relative paths,
+ambiguous percent-encoded paths, query strings, fragments, and symlinks in the scan directory are
+rejected.
-```json
-{
- "jobTemplateName": "builtin-iceberg-remove-orphan-files",
- "jobConf": {
- "catalog_name": "rest_catalog",
- "table_identifier": "db.t1",
- "older_than": "",
- "location": "",
- "dry_run": "true",
- "spark_conf": "{}",
- "spark_master": "local[2]",
- "spark_executor_instances": "1",
- "spark_executor_cores": "1",
- "spark_executor_memory": "1g",
- "spark_driver_memory": "1g",
- "catalog_type": "rest",
- "catalog_uri": "http://localhost:9001/iceberg",
- "warehouse_location": ""
- }
-}
+### Submitting the Job
+
+Start with `dry_run: "true"` and review candidate paths before deleting:
+
+```bash
+curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "jobTemplateName": "builtin-iceberg-remove-orphan-files",
+ "jobConf": {
+ "catalog_name": "rest_catalog",
+ "table_identifier": "db.t1",
+ "older_than": "",
+ "location": "",
+ "dry_run": "true",
+ "spark_conf": "{}",
+ "spark_master": "local[2]",
+ "spark_executor_instances": "1",
+ "spark_executor_cores": "1",
+ "spark_executor_memory": "1g",
+ "spark_driver_memory": "1g",
+ "catalog_type": "rest",
+ "catalog_uri": "http://localhost:9001/iceberg",
+ "warehouse_location": ""
+ }
+ }' \
+ http://localhost:8090/api/metalakes/test/jobs/runs
```
-POST this body to `/api/metalakes/{metalake}/jobs`. Review the candidate paths in
-the job logs before resubmitting with `dry_run: "false"`. A successful run also
-logs the candidate count. CLI equivalents are `--catalog`, `--table`,
-`--older-than`, `--location`, `--dry-run true|false`, and `--spark-conf`.
-
-The job validates the location before executing the procedure. A custom
-location must be the table's own location or a descendant, on the same storage
-scheme and authority. Relative paths, ambiguous percent-encoded paths, query
-strings, fragments, and symlinks in the scan directory are rejected. Filesystem
-validation errors fail the job before deletion. Keep the scan directory free of
-concurrent location or symlink changes during cleanup.
-
-Retain the three-day default unless a longer interval is needed for your writers.
-Files staged by active writers can appear to be orphaned. Iceberg 1.11's SQL
-procedure rejects explicit cutoffs less than 24 hours old, including a cutoff of
-"now", even for dry runs. This job preserves that safeguard and does not enable
-Iceberg's testing override. Spark's `spark.sql.parser.escapedStringLiterals` must
-remain `false` for procedure arguments to be interpreted correctly.
+Policy-driven submission uses `system_iceberg_orphan_file_removal`; see
+[Orphan cleanup](./optimizer-configuration.md#orphan-cleanup). CLI equivalents for direct Spark
+invocation are `--catalog`, `--table`, `--older-than`, `--location`, `--dry-run true|false`, and
+`--spark-conf`.
+
+### Verifying the Result
+
+```bash
+curl -sS "http://localhost:8090/api/metalakes/test/jobs/runs/{job_id}" | jq '.job.status'
+cat /tmp/gravitino/jobs/staging/test/builtin-iceberg-remove-orphan-files/{job_id}/output.log
+```
+
+A successful dry run reports `SUCCEEDED` and logs candidate paths and counts without deleting.
+Resubmit with `dry_run: "false"` only after reviewing those paths.
+
+## Related
+
+- [Table Maintenance Service](./optimizer.md) for the concepts and the walkthrough
+- [Configuration](./optimizer-configuration.md) for the three configuration layers
+- [Iceberg Compaction Policy](../iceberg-compaction-policy.md) for tuning the built-in strategy
+- [Manage Jobs](../manage-jobs-in-gravitino.md) for job status and templates
diff --git a/docs/table-maintenance-service/optimizer-configuration.md b/docs/table-maintenance-service/optimizer-configuration.md
index f1b0e2f2ec..283565f195 100644
--- a/docs/table-maintenance-service/optimizer-configuration.md
+++ b/docs/table-maintenance-service/optimizer-configuration.md
@@ -199,6 +199,9 @@ gravitino.optimizer.recommender.strategyProvider = gravitino-strategy-provider
gravitino.optimizer.recommender.tableMetaProvider = gravitino-table-metadata-provider
gravitino.optimizer.recommender.jobSubmitter = gravitino-job-submitter
gravitino.optimizer.strategyHandler.iceberg-data-compaction.className = org.apache.gravitino.maintenance.optimizer.recommender.handler.compaction.CompactionStrategyHandler
+gravitino.optimizer.strategyHandler.iceberg-rewrite-manifests.className = org.apache.gravitino.maintenance.optimizer.recommender.handler.ManifestRewriteStrategyHandler
+gravitino.optimizer.strategyHandler.iceberg-snapshot-expiration.className = org.apache.gravitino.maintenance.optimizer.recommender.handler.snapshot.SnapshotExpirationStrategyHandler
+gravitino.optimizer.strategyHandler.iceberg-orphan-file-removal.className = org.apache.gravitino.maintenance.optimizer.recommender.handler.orphan.OrphanFileRemovalStrategyHandler
gravitino.optimizer.jobSubmitterConfig.catalog_name = rest_catalog
gravitino.optimizer.jobSubmitterConfig.spark_master = local[2]
gravitino.optimizer.jobSubmitterConfig.spark_executor_instances = 1
@@ -207,32 +210,36 @@ gravitino.optimizer.jobSubmitterConfig.spark_executor_memory = 1g
gravitino.optimizer.jobSubmitterConfig.spark_driver_memory = 1g
gravitino.optimizer.jobSubmitterConfig.catalog_type = rest
gravitino.optimizer.jobSubmitterConfig.catalog_uri = http://localhost:9001/iceberg
-# Leave empty for a local filesystem; set to your warehouse URI for cloud or HDFS storage.
+# Local filesystem: leave empty. Iceberg REST: Gravitino catalog name (not s3://...).
gravitino.optimizer.jobSubmitterConfig.warehouse_location =
gravitino.optimizer.jobSubmitterConfig.spark_conf = {"spark.hadoop.fs.defaultFS":"file:///"}
```
-For manifest rewrite policies, the mapping
-`gravitino.optimizer.strategyHandler.iceberg-rewrite-manifests.className` is optional. When
-omitted or blank, the recommender uses the built-in
-`org.apache.gravitino.maintenance.optimizer.recommender.handler.ManifestRewriteStrategyHandler`.
-An explicit class name overrides that default. An omitted policy `spec_id` uses Iceberg's
-current default spec from table metadata; see [Iceberg manifest rewrite policy](../iceberg-rewrite-manifests-policy.md).
+### Gravitino client auth (CLI and update-stats)
+
+One auth model backs both the CLI Gravitino client (`submit-strategy-jobs` and related providers)
+and `builtin-iceberg-update-stats` / `submit-update-stats-job`. Supported types are **`none`**,
+**`simple`**, **`basic`**, and **`oauth`** (client-credentials only). Put the same fields in either
+place:
-When the Gravitino server has authentication enabled, `builtin-iceberg-update-stats` needs
-credentials in `--updater-options` / `updater_options` for the Gravitino client (statistics
-updater and `submit-update-stats-job` `runJob` calls):
+| Type | CLI conf (`gravitino-optimizer.conf`) | Short name in `updater_options` / `--updater-options` |
+| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
+| `none` (default) | omit keys, or `gravitino.optimizer.auth.type = none` | omit keys, or `auth_type=none` |
+| `simple` | `gravitino.optimizer.auth.type`, optional `gravitino.optimizer.auth.username` | `auth_type`, optional `username` |
+| `basic` | `gravitino.optimizer.auth.type`, `gravitino.optimizer.auth.username`, `gravitino.optimizer.auth.password` | `auth_type`, `username`, `password` |
+| `oauth` | `gravitino.optimizer.auth.type`, `gravitino.optimizer.auth.oauth.serverUri`, `gravitino.optimizer.auth.oauth.path`, `gravitino.optimizer.auth.oauth.credential`, `gravitino.optimizer.auth.oauth.scope` | `auth_type`, `oauth_server_uri`, `oauth_path`, `oauth_credential`, `oauth_scope` |
-| `auth_type` | Fields |
-| ---------------- | -------------------------------------------------------------------------------------------- |
-| `none` (default) | (none) |
-| `simple` | `username` (optional) |
-| `basic` | `username`, `password` |
-| `oauth` | client-credentials only: `oauth_server_uri`, `oauth_path`, `oauth_credential`, `oauth_scope` |
+Short names are promoted onto the `gravitino.optimizer.auth.*` keys before the client is built.
+Use CLI conf when the optimizer process talks to a secured server; use short names in
+`updater_options` when the update-stats Spark job (or `submit-update-stats-job` `runJob`) must
+authenticate. They are two surfaces for the same fields, not two auth systems.
Iceberg REST catalog authentication is separate: set `rest.auth.*` in `spark-conf` for any built-in
job that talks to a secured IRC (including update-stats). Expire-snapshots and rewrite-data-files
-do not read `updater_options` auth fields.
+do not read these Gravitino client auth fields. For Iceberg REST on object storage, set
+`warehouse_location` to the catalog name and put vended credentials (plus IRC `rest.auth.*` when
+required) in `spark_conf`. See
+[Secured Gravitino and Iceberg REST](./optimizer.md#secured-gravitino-and-iceberg-rest-object-storage).
Passwords and OAuth credentials in `updater_options` (and secrets in `spark_conf`) travel with
the job command line and `jobConf`; avoid logging raw `jobConf` (the submit-update-stats CLI
@@ -240,10 +247,11 @@ redacts them in DRY-RUN / SUBMIT output).
Everything under `gravitino.optimizer.jobSubmitterConfig.` becomes the `jobConf` of jobs this CLI submits, so the two layers carry the same keys under different names.
-The policy-driven path needs the same keys. Its compaction adapter only derives the table, the
-where clause and the rewrite options from the policy, so `catalog_name`, `catalog_type`,
-`catalog_uri` and `warehouse_location` must come from `gravitino.optimizer.jobSubmitterConfig.`.
-Missing ones are reported when the job is submitted, instead of failing later inside Spark.
+The policy-driven path needs the same catalog Spark keys. Strategy adapters derive
+task-specific fields (table identifier, where clause, retention options, and so on) from the
+policy, so `catalog_name`, `catalog_type`, `catalog_uri`, and `warehouse_location` must come from
+`gravitino.optimizer.jobSubmitterConfig.`. Missing ones are reported when the job is submitted,
+instead of failing later inside Spark.
## Job Submission Configuration
@@ -285,12 +293,56 @@ after it starts. Match the artifact to
your Spark, Scala, and Iceberg versions. Details are under
[Built-in Job Templates](./optimizer-cli-reference.md#built-in-job-templates).
-`warehouse_location` may be empty for local filesystem testing. Set it to the warehouse URI for HDFS or cloud object storage.
+`warehouse_location` may be empty for local filesystem testing. For Iceberg REST catalogs, set it
+to the **Gravitino catalog name** (for example `rest_catalog` or `catalog_iceberg_s3`), not an
+`s3://` or other object-store URI — that URI form yields `NoSuchWarehouse`. For non-REST backends
+that expect a storage root, use the warehouse URI those backends document.
+
+## Compaction (rewrite data files)
+
+Submit `builtin-iceberg-rewrite-data-files` through `POST /api/metalakes/{metalake}/jobs/runs` or
+through `submit-strategy-jobs`. Besides the shared catalog keys, only `where_clause` is required
+with no template default (pass `""` to rewrite the whole table). `strategy` defaults to `binpack`;
+`sort_order` and `options` default to empty when omitted. Policy-driven submits fill these through
+the compaction adapter.
+
+| Key | Meaning | Default |
+| ------------------ | ------------------------------------------------- | --------- |
+| `catalog_name` | Iceberg catalog registered in Spark | Required |
+| `table_identifier` | Table identifier, for example `db.t1` | Required |
+| `where_clause` | Filter predicate; `""` rewrites the whole table | Required |
+| `strategy` | `binpack` or `sort` | `binpack` |
+| `sort_order` | Sort order when using `sort`; empty for `binpack` | empty |
+| `options` | JSON map of Iceberg rewrite options | empty |
+| `spark_conf` | JSON string containing additional Spark settings | None |
+
+Include the shared Spark and catalog template settings. Register the handler (optional when using
+the Recommender default):
+
+```properties
+gravitino.optimizer.strategyHandler.iceberg-data-compaction.className = org.apache.gravitino.maintenance.optimizer.recommender.handler.compaction.CompactionStrategyHandler
+```
+
+Create a policy through `POST /api/metalakes/{metalake}/policies`:
-### Rewrite Manifests Job
+```json
+{
+ "name": "iceberg_compaction_default",
+ "policyType": "system_iceberg_compaction",
+ "enabled": true,
+ "content": {}
+}
+```
-Submit `builtin-iceberg-rewrite-manifests` directly through
-`POST /api/metalakes/{metalake}/jobs/runs`. Its `jobConf` uses these job-specific keys:
+Associate the policy with a tag and attach that tag to the target table, schema, or catalog.
+Threshold fields (`minDataFileMse`, `minDeleteFileNumber`, `rewriteStrategy`, and related options)
+are documented in [Iceberg Compaction Policy](../iceberg-compaction-policy.md). Use
+`submit-strategy-jobs --strategy-name iceberg_compaction_default`. Submission and verification
+examples are under [Rewrite Data Files](./optimizer-cli-reference.md#rewrite-data-files).
+
+## Rewrite Manifests
+
+Submit `builtin-iceberg-rewrite-manifests` through `POST /api/metalakes/{metalake}/jobs/runs`.
| Key | Meaning | Default |
| ------------------ | ----------------------------------------------------- | --------------------------------------------- |
@@ -300,84 +352,56 @@ Submit `builtin-iceberg-rewrite-manifests` directly through
| `use_caching` | `true` or `false` to control caching during rewriting | Installed Iceberg default (`false` in 1.11.0) |
| `spark_conf` | JSON string containing additional Spark settings | None |
-Include the Spark and catalog template settings shown in the
-[submission example](./optimizer-cli-reference.md#submitting-the-job), and make the matching
-Iceberg Spark runtime available as described above. For this job, omitted, blank, or
-unresolved optional argument placeholders are treated as absent. Required catalog/table
-arguments cannot be blank or unresolved. `spec_id` must be a non-negative integer identifying
-an existing spec; it does not repartition data or migrate manifests between specs.
+`spec_id` must be a non-negative integer identifying an existing spec; it does not repartition data
+or migrate manifests between specs. Omitted, blank, or unresolved optional placeholders are treated
+as absent. Include the shared Spark and catalog template settings.
-This job currently supports direct submission. Policy -> Strategy -> Adapter integration
-for automatic manifest maintenance will follow separately.
-
-## Running Against a Local Filesystem
-
-On a machine with no HDFS, Spark still defaults to `hdfs://localhost:9000` and fails. Set the default filesystem explicitly, in `spark_conf` for job submissions and in the CLI `spark_conf` value:
+Register the handler (optional; the Recommender defaults this class when unset):
```properties
-spark.hadoop.fs.defaultFS=file:///
+gravitino.optimizer.strategyHandler.iceberg-rewrite-manifests.className = org.apache.gravitino.maintenance.optimizer.recommender.handler.ManifestRewriteStrategyHandler
```
-## Checking Your Configuration
-
-Four things are worth confirming before assuming a configuration problem is a code problem.
-
-- `builtin-iceberg-update-stats` and `builtin-iceberg-rewrite-data-files` appear in the job template list.
-- The policy is associated with a tag assigned to the target table or one of its ancestors.
-- `submit-strategy-jobs` prints `SUBMIT` lines rather than nothing.
-- The rewrite log shows `Rewritten data files: N` with `N` greater than zero for a non-empty table.
-
-## Related
-
-- [Service](./service.md) for the in-process service, `timeTrigger`, and the cron path
-- [Table Maintenance Service](./optimizer.md) for the CLI walkthrough
-- [CLI Reference](./optimizer-cli-reference.md) for every command and the built-in job templates
-- [Troubleshooting](./optimizer-troubleshooting.md) when a command or job fails
-- [Extension Guide](./optimizer-extension-guide.md) for custom strategies and providers
-
-## Orphan File Cleanup Job Configuration
-
-Submit `builtin-iceberg-remove-orphan-files` with the same Spark and catalog
-settings described above. Its job-specific `jobConf` keys are:
+Create a policy through `POST /api/metalakes/{metalake}/policies`:
-| Key | Meaning | Default |
-| ------------------ | --------------------------------------------------------------------------------------- | -------------------------------- |
-| `catalog_name` | Iceberg catalog registered in Spark | Required |
-| `table_identifier` | Table identifier within the catalog, such as `db.sample` | Required |
-| `older_than` | Timestamp (explicit offset or Spark session time zone); must be at least 24 hours old | Three days ago (Iceberg default) |
-| `location` | Scan only this directory within the table's storage location | Table location |
-| `dry_run` | `true` logs candidate paths without deleting; `false` deletes | `false` |
-| `spark_conf` | JSON string containing custom Spark settings, including the Iceberg runtime if needed | None |
+```json
+{
+ "name": "rewrite_manifests",
+ "policyType": "system_iceberg_rewrite_manifests",
+ "enabled": true,
+ "content": {}
+}
+```
-For direct template submission, supply `older_than: ""` and `location: ""` to
-use the defaults, `dry_run: "false"` (or `"true"` to preview), and
-`spark_conf: "{}"` when no overrides are needed.
+Associate the policy with a tag and attach that tag to the target table, schema, or catalog.
+Collect with `builtin-iceberg-update-manifest-stats`, then run
+`submit-strategy-jobs --strategy-name rewrite_manifests`. Content fields and thresholds are in
+[Iceberg manifest rewrite policy](../iceberg-rewrite-manifests-policy.md). Direct submission and
+verification examples are under [Rewrite Manifests](./optimizer-cli-reference.md#rewrite-manifests).
-Keep the three-day default unless your workload needs a longer retention window.
-The 24-hour minimum also applies to dry runs; passing the current timestamp is
-not supported. For a secured Iceberg REST catalog, supply its authentication
-settings explicitly in `spark_conf`, as described above.
+## Snapshot Expiration
-See [Remove Orphan Files](./optimizer-cli-reference.md#remove-orphan-files) for a
-complete submission example. For policy-driven submission, configure the handler
-and policy below. Periodic scheduling remains separate.
+Submit `builtin-iceberg-expire-snapshots` with the shared Spark and catalog keys plus:
-### Snapshot expiration policy integration
+| Key | Meaning | Default |
+| ------------------ | ------------------------------------------------ | ------------- |
+| `catalog_name` | Iceberg catalog registered in Spark | Required |
+| `table_identifier` | Table identifier, for example `db.t1` | Required |
+| `older_than` | Expire snapshots older than this timestamp | Five days ago |
+| `retain_last` | Minimum number of recent snapshots to keep | `1` |
+| `stream_results` | Stream intermediate delete results when present | Disabled |
+| `spark_conf` | JSON string containing additional Spark settings | None |
-Register the handler alongside the existing optimizer providers (optional; the
-Recommender also defaults this class when the property is unset):
+Register the handler (optional; the Recommender defaults this class when unset):
```properties
gravitino.optimizer.strategyHandler.iceberg-snapshot-expiration.className = org.apache.gravitino.maintenance.optimizer.recommender.handler.snapshot.SnapshotExpirationStrategyHandler
```
-The built-in job adapter is registered automatically. Keep the same Spark and
-catalog submission configuration as for direct expire-snapshots runs, including
-`catalog_name` and `spark_conf`. The adapter supplies `table_identifier` and
-`stream_results`. For `older_than` / `retain_last`, values equal to Iceberg's
-procedure defaults (`olderThanDays=5`, `retainLast=1`) are omitted so the job
-template placeholders stay empty and Iceberg table `history.expire.*`
-properties remain authoritative; non-default values are emitted explicitly.
+The built-in job adapter is registered automatically. It supplies `table_identifier` and
+`stream_results`. For `older_than` / `retain_last`, values equal to Iceberg's procedure defaults
+(`olderThanDays=5`, `retainLast=1`) are omitted so template placeholders stay empty and Iceberg
+table `history.expire.*` properties remain authoritative; non-default values are emitted explicitly.
Create a policy through `POST /api/metalakes/{metalake}/policies`:
@@ -394,34 +418,38 @@ Create a policy through `POST /api/metalakes/{metalake}/policies`:
}
```
-Associate the policy with a tag and attach that tag to the target table, schema,
-or catalog, following the [policy setup walkthrough](./optimizer.md).
-`olderThanDays` defaults to 5 (Iceberg's expire default) and must be between 1 and 36500.
-`retainLast` defaults to 1. `streamResults` defaults to false.
+Associate the policy with a tag and attach that tag to the target table, schema, or catalog.
+`olderThanDays` defaults to 5 and must be between 1 and 36500. `retainLast` defaults to 1.
+`streamResults` defaults to false. When `olderThanDays` is not 5, the adapter subtracts it from the
+current instant and emits `older_than` as an explicit UTC timestamp ending in `Z`. Each optimizer
+invocation may submit expire when the policy is attached; this does not install a periodic
+scheduler. See [Expire Snapshots](./optimizer-cli-reference.md#expire-snapshots).
-When `olderThanDays` is not the Iceberg default of 5, the adapter subtracts it
-from the current instant and emits `older_than` as an explicit UTC timestamp
-ending in `Z`. Each optimizer invocation may submit expire when the policy is
-attached (`trigger-expr` is `true`). This does not install a periodic
-scheduler, cooldown, or last-run tracking—same as orphan cleanup. Operators
-must control how often `submit-strategy-jobs` (or an external cron) runs.
+## Orphan Cleanup
-### Orphan cleanup policy integration
+Submit `builtin-iceberg-remove-orphan-files` with the shared Spark and catalog keys plus:
-Register the handler alongside the existing optimizer providers (optional; the
-Recommender also defaults this class when the property is unset):
+| Key | Meaning | Default |
+| ------------------ | ------------------------------------------------------------------------------------- | -------------------------------- |
+| `catalog_name` | Iceberg catalog registered in Spark | Required |
+| `table_identifier` | Table identifier within the catalog, such as `db.sample` | Required |
+| `older_than` | Timestamp; explicit values must be at least 24 hours old | Three days ago (Iceberg default) |
+| `location` | Scan only this directory within the table's storage location | Table location |
+| `dry_run` | `true` logs candidate paths without deleting; `false` deletes | `false` |
+| `spark_conf` | JSON string containing custom Spark settings, including the Iceberg runtime if needed | None |
+
+For direct template submission, supply `older_than: ""` and `location: ""` to use the defaults,
+`dry_run: "false"` (or `"true"` to preview), and `spark_conf: "{}"` when no overrides are needed.
+Keep the three-day default unless your workload needs a longer retention window. The 24-hour
+minimum also applies to dry runs.
+
+Register the handler (optional; the Recommender defaults this class when unset):
```properties
gravitino.optimizer.strategyHandler.iceberg-orphan-file-removal.className = org.apache.gravitino.maintenance.optimizer.recommender.handler.orphan.OrphanFileRemovalStrategyHandler
```
-The built-in job adapter is registered automatically. Keep the same Spark and
-catalog submission configuration as for direct orphan cleanup, including
-`catalog_name` (the catalog alias configured in Spark) and `spark_conf`.
-The adapter supplies `table_identifier`, `older_than`, `location`, and `dry_run`.
-These policy-derived values override shared submission defaults.
-
-Create a policy through `POST /api/metalakes/{metalake}/policies`:
+The adapter supplies `table_identifier`, `older_than`, `location`, and `dry_run`. Create a policy:
```json
{
@@ -438,36 +466,44 @@ Create a policy through `POST /api/metalakes/{metalake}/policies`:
```
Optional TMS peer fields on content (`timeTrigger`, `commitTrigger`, `minIntervalMs`, `jobOptions`,
-`updaterOptions`) are shared with compaction and other maintenance policy types. `commitTrigger` is
-not allowed for orphan cleanup. See [Iceberg compaction policy](../iceberg-compaction-policy.md) for
-peer-field semantics.
-
-Associate the policy with a tag and attach that tag to the target table, schema,
-or catalog, following the [policy setup walkthrough](./optimizer.md).
-`olderThanDays` defaults to 3 and must be between 1 and 36500 inclusive (approximately 100 years). This bound rejects impractical retention values before a policy is stored. `dryRun` defaults to false.
-
-The policy adapter subtracts `olderThanDays` from the current instant and always
-emits `older_than` as an explicit UTC timestamp ending in `Z`. Policy retention
-is therefore independent of `spark.sql.session.timeZone`. For direct job
-submission, timestamps without an offset use the Spark session time zone.
-
-Optional `location` must not have leading or trailing whitespace and must be the
-table's storage root or a descendant; submission requires the table's `location` metadata to validate a custom path. The Spark job
-rechecks containment and filesystem symlinks with its own credentials before
-listing or deleting files.
-
-The strategy operates on the whole table, including partitioned tables, and does
-not need table or partition statistics. Each explicit optimizer invocation makes
-an enabled, selected cleanup policy eligible with score 1. This does not install
-a periodic scheduler, cooldown, or last-run tracking. Because the trigger is always
-true and the score is always 1, every explicit `submit-strategy-jobs` invocation
-for an enabled, selected orphan policy submits a Spark cleanup job. Unlike
-threshold-based compaction, there is no metric gate to suppress repeated runs.
-Operators must control the invocation rate through external scheduling. Start
-with `dryRun: true` to inspect candidates; dry-run jobs still consume Spark
-resources and also need rate limiting.
-
-Use `submit-strategy-jobs --strategy-name orphan_cleanup` with the target
-identifiers. The CLI `--dry-run` previews recommendations without submitting jobs;
-the policy's `dryRun: true` submits a Spark job that lists candidates without
-deleting them. Start with that policy setting to inspect candidates.
+`updaterOptions`) are shared with other maintenance policy types. `commitTrigger` is not allowed for
+orphan cleanup. See [Iceberg compaction policy](../iceberg-compaction-policy.md) for peer-field
+semantics. `olderThanDays` defaults to 3 (1–36500). The adapter always emits `older_than` as an
+explicit UTC timestamp ending in `Z`.
+
+The strategy operates on the whole table and does not need table or partition statistics. Every
+explicit `submit-strategy-jobs` invocation for an enabled, selected orphan policy submits a Spark
+job (no metric gate). Start with `dryRun: true`. Use
+`submit-strategy-jobs --strategy-name orphan_cleanup`. See
+[Remove Orphan Files](./optimizer-cli-reference.md#remove-orphan-files).
+
+## Running Against a Local Filesystem
+
+On a machine with no HDFS, Spark still defaults to `hdfs://localhost:9000` and fails. Set the default filesystem explicitly, in `spark_conf` for job submissions and in the CLI `spark_conf` value:
+
+```properties
+spark.hadoop.fs.defaultFS=file:///
+```
+
+## Checking Your Configuration
+
+Confirm these before assuming a configuration problem is a code problem.
+
+- The built-in templates you need appear in the job template list (`update-stats`, rewrite data
+ files, rewrite manifests, expire snapshots, remove orphan files).
+- For policy-driven runs, the policy is associated with a tag assigned to the target table or one of
+ its ancestors.
+- `submit-strategy-jobs` prints `SUBMIT` lines rather than nothing when the policy should fire.
+- Compaction: rewrite log shows `Rewritten data files: N` with `N > 0` when enough small files exist
+ (`min-input-files`, default 5). `N = 0` is usually a data-shape issue.
+- Manifest rewrite: log shows rewritten/added manifest counts (both zero can be a successful no-op).
+- Snapshot expiry: log shows deleted data/manifest/manifest-list counts.
+- Orphan cleanup: dry-run log lists candidate paths before you switch `dry_run` to `false`.
+
+## Related
+
+- [Service](./service.md) for the in-process service, `timeTrigger`, and the cron path
+- [Table Maintenance Service](./optimizer.md) for the CLI walkthrough
+- [CLI Reference](./optimizer-cli-reference.md) for every command and the built-in job templates
+- [Troubleshooting](./optimizer-troubleshooting.md) when a command or job fails
+- [Extension Guide](./optimizer-extension-guide.md) for custom strategies and providers
diff --git a/docs/table-maintenance-service/optimizer-troubleshooting.md b/docs/table-maintenance-service/optimizer-troubleshooting.md
index 1176f15fd5..5581f1d4bb 100644
--- a/docs/table-maintenance-service/optimizer-troubleshooting.md
+++ b/docs/table-maintenance-service/optimizer-troubleshooting.md
@@ -75,7 +75,25 @@ spark.hadoop.fs.defaultFS=file:///
`spark.jars` in `spark_conf` replaces a `spark.jars` default of the k8s job executor, so if that
default provides the Iceberg runtime, list it in `spark_conf` as well.
-**`The provided credentials did not support` or Iceberg `Not authorized`** — a secured Gravitino endpoint needs `auth_type` / `username` / `password` (or OAuth client-credentials fields) in `updater_options` for `builtin-iceberg-update-stats`. A secured Iceberg REST catalog needs `rest.auth.*` in `spark-conf` for any built-in job that reads the table. See [Configuration](./optimizer-configuration.md).
+**`The provided credentials did not support` or Iceberg `Not authorized`** — a secured Gravitino
+endpoint needs the optimizer Gravitino client auth (`none` / `simple` / `basic` / `oauth`) in CLI
+conf and/or short names in `updater_options`. A secured Iceberg REST catalog needs `rest.auth.*` in
+`spark-conf` for any built-in job that reads the table. Object-store writes also need
+`spark.sql.catalog.<cat>.header.X-Iceberg-Access-Delegation=vended-credentials`. See
+[Gravitino client auth](./optimizer-configuration.md#gravitino-client-auth-cli-and-update-stats) and
+[Secured Gravitino and Iceberg REST](./optimizer.md#secured-gravitino-and-iceberg-rest-object-storage).
+
+**`NoSuchWarehouse` on Iceberg REST** — `warehouse_location` was set to an `s3://` (or similar)
+URI. For REST catalogs use the Gravitino **catalog name** instead.
+
+**Direct rewrite `runJob` returns HTTP 400 listing missing keys** — `where_clause` has no template
+default; pass `""` to rewrite the whole table. Shared catalog keys
+(`catalog_name`, `table_identifier`, `catalog_type`, `catalog_uri`, `warehouse_location`) are also
+required. `strategy` / `sort_order` / `options` have defaults when omitted.
+
+**Rewrite succeeds with `Rewritten data files: 0`** — Iceberg's default `min-input-files` is 5.
+One small file per partition is not enough for a non-empty rewrite. Add more small files or pass
+rewrite options that lower the threshold, then re-run.
**Built-in Iceberg jobs fail with `Missing Iceberg Spark session extensions`** —
Spark only warns when `IcebergSparkSessionExtensions` is missing, so built-in jobs check the
@@ -97,25 +115,21 @@ With the local job executor, `spark.jars` in `spark_conf` doesn't add it: the dr
Use the Spark, Scala, and Iceberg versions that match your cluster. See
[Built-in Job Templates](./optimizer-cli-reference.md#built-in-job-templates).
-**Rewrite fails on a multi-level partition** — in release `1.2.0`, rewriting a table partitioned by an identity transform combined with a time transform, such as `PARTITIONED BY (p, days(ts))`, fails with:
+**Multi-level / non-identity partition rewrite** — the rewrite **job** does not reject these
+layouts. A **direct** `builtin-iceberg-rewrite-data-files` submit with an empty `where_clause`
+rewrites the whole table and succeeds on `PARTITIONED BY (p, days(ts))` (and similar). You may
+still see `Rewritten data files: 0` when files are not rewrite-eligible (`min-input-files`).
-```text
-Cannot translate Spark expression ... day(cast(ts as date)) ... to data source filter
-```
-
-Confirm it by checking the job run at `/api/metalakes/{metalake}/jobs/runs/{job_id}` and reading `error.log` under `builtin-iceberg-rewrite-data-files`. The only workaround is to compact identity-partitioned tables and leave the rest alone.
-
-Observed in `1.2.0`:
-
-| Partitioning | Rewrite |
-|----------------------------------------------------------------|---------|
-| `p`, `p, c2` | Works |
-| `p, years(ts)`, `p, months(ts)`, `p, days(ts)`, `p, hours(ts)` | Fails |
-| `p, truncate(1, c2)`, `p, bucket(8, id)` | Fails |
+The failure mode
+`Cannot translate Spark expression ... day(...) ... to data source filter` still happens when
+the submit uses a **partition `where_clause` that applies time/bucket transforms** — the form
+the compaction adapter builds via `PartitionUtils` (for example `p = "a" AND day(ts) = 19723`).
+That is a strategy-generated filter path, not a limitation of empty-`where_clause` direct
+submits. Confirm in job run status and `error.log` under `builtin-iceberg-rewrite-data-files`.
## Related
- [Table Maintenance Service](./optimizer.md)
- [Configuration](./optimizer-configuration.md)
-- [Quick Start](./optimizer.md#walkthrough)
-- [CLI Reference](./optimizer-configuration.md)
+- [Walkthrough](./optimizer.md#walkthrough)
+- [CLI Reference](./optimizer-cli-reference.md)
diff --git a/docs/table-maintenance-service/optimizer.md b/docs/table-maintenance-service/optimizer.md
index bcf94e048a..73bc061dc8 100644
--- a/docs/table-maintenance-service/optimizer.md
+++ b/docs/table-maintenance-service/optimizer.md
@@ -21,20 +21,30 @@ The CLI binary, its configuration file, and its configuration keys carry the old
Confirm your environment matches this list before starting an evaluation against the built-ins. Anything outside it needs a custom extension, which is covered in the [Extension Guide](./optimizer-extension-guide.md).
-- Compaction and orphan file cleanup have built-in strategies. Snapshot expiration is available as a directly submitted built-in job. Scheduling and minimum run intervals remain separate from strategy evaluation. Sort and cluster maintenance also require custom strategies.
-- Compaction applies to Iceberg tables only, and only where every partition uses an identity transform.
+- Four built-in Iceberg jobs ship with policy/strategy handlers and direct `runJob` templates:
+ rewrite data files (compaction), rewrite manifests, expire snapshots, and remove orphan files.
+ Scheduling and `minIntervalMs` stay outside strategy evaluation. Sort and cluster maintenance
+ still need custom strategies.
+- Compaction's **policy/strategy** path prefers identity partitions (time/bucket filters can fail
+ Spark translation). Direct `builtin-iceberg-rewrite-data-files` with an empty `where_clause`
+ covers broader layouts such as `PARTITIONED BY (p, days(ts))`; see
+ [Troubleshooting](./optimizer-troubleshooting.md#job-execution-failures). The other three jobs
+ are not limited by that partition caveat.
- The in-process service, `timeTrigger`, and the cron path are documented in [Service](./service.md). The rest of this page is the manual CLI workflow.
## How It Works
-Maintenance runs as four steps. Each is a separate command, so you can stop after any of them, and the dry run on step two shows what would be submitted before anything runs.
+This is the shared CLI workflow for the table maintenance service, not a single job type.
+Maintenance runs as four steps. Each is a separate command, so you can stop after any of them,
+and the dry run on Evaluate shows what would be submitted before anything runs. Direct
+`POST .../jobs/runs` submissions skip Evaluate and go straight to a chosen job template.
| Step | What you run | What it produces |
-|----------|---------------------------------------------------|---------------------------------------------------------|
+| -------- | ------------------------------------------------- | ------------------------------------------------------- |
| Collect | `update-statistics`, `append-metrics` | Statistics on the table, metrics in the JDBC repository |
| Evaluate | `submit-strategy-jobs --dry-run` | Candidate actions, with nothing submitted |
| Submit | `submit-strategy-jobs`, `submit-update-stats-job` | A Spark job, tracked by job status and staging logs |
-| Observe | `monitor-metrics`, `list-table-metrics` | Before and after metrics, and rewritten data files |
+| Observe | `monitor-metrics`, `list-table-metrics` | Before and after metrics, and job staging logs |
## Execution Modes
@@ -44,43 +54,29 @@ The built-in workflow drives everything through the Gravitino server and its job
The local calculator reads a JSONL file you supply and updates statistics and metrics directly from it. Use it for testing and batch scripts, where you already have the numbers and want to feed them in without the server computing them.
-## Naming
+## Policy-driven naming
-Three identifiers look interchangeable and are not.
+These three identifiers matter for the **policy-driven** path (`submit-strategy-jobs` and
+tag-associated policies). They are not compaction-only — each policy-backed task has its own
+names — but direct `runJob` submissions do not use `--strategy-name` and do not need this
+distinction. Task sections below state which policy name / type apply when a policy path exists.
| Term | Example | Where it appears |
-|---------------|------------------------------|------------------------------------------------------------|
+| ------------- | ---------------------------- | ---------------------------------------------------------- |
| Policy name | `iceberg_compaction_default` | The policy's own name, and the CLI `--strategy-name` |
| Policy type | `system_iceberg_compaction` | The `policyType` field when creating a policy over REST |
| Strategy type | `iceberg-data-compaction` | The `strategy.type` field, and the strategy handler config |
`--strategy-name` takes the **policy name**, despite what it is called. Passing either of the other two reports no matching identifiers rather than naming the mistake.
-## Orphan File Cleanup
-
-For policy-driven submission, use `system_iceberg_orphan_file_removal` and register
-the handler described in [Orphan cleanup policy integration](./optimizer-configuration.md#orphan-cleanup-policy-integration).
-Each explicit optimizer invocation evaluates the enabled policy at table level;
-it does not require partition statistics or configure a periodic schedule.
-
-Submit `builtin-iceberg-remove-orphan-files` through the jobs REST API to reclaim
-unreferenced files. Start with `dry_run: "true"` and review the candidate paths
-in the job logs before allowing deletion. The default cutoff is three days ago;
-explicit cutoffs must be at least 24 hours old, including for dry runs. A custom
-scan location must remain within the target table's storage location.
-
-Direct submission remains available alongside policy-driven submission. See
-[Remove Orphan Files](./optimizer-cli-reference.md#remove-orphan-files) for the
-submission example and [Configuration](./optimizer-configuration.md#orphan-file-cleanup-job-configuration)
-for the per-job options.
-
## Walkthrough
-This takes one Iceberg table through the whole workflow: create it, fill it with small files, apply a compaction policy through a tag, collect statistics, and let the service decide to compact it. It runs against a local Spark and takes about fifteen minutes.
+The sections below share prerequisites and one demo table setup, then cover each built-in
+maintenance task with the same shape: what the job does, how you submit it, task-specific
+notes, and where to verify. Full REST/`jobConf` examples stay in the
+[CLI Reference](./optimizer-cli-reference.md); this page does not repeat them per task.
-Each step ends with a check. If a check fails, stop there, since every step depends on the one before it.
-
-### Prerequisites
+### Shared prerequisites
- A running Gravitino server with a metalake. The examples use `test`.
- Spark available to the job executor. The [local job executor](../local-job-executor.md) needs either `SPARK_HOME` or `gravitino.jobExecutor.local.sparkHome`, and the [Kubernetes job executor](../k8s-job-executor.md) needs a Spark image.
@@ -106,7 +102,35 @@ Each step ends with a check. If a check fails, stop there, since every step depe
If your Iceberg REST backend runs in memory, do not restart it partway through. Restarting resets both metadata and data files, and you start over.
-### Step 1: Confirm the Job Templates Exist
+#### Secured Gravitino and Iceberg REST (object storage)
+
+The local `file:///` samples below omit authentication. Against a secured cluster (Gravitino auth
+plus Iceberg REST on object storage), also set:
+
+1. **Gravitino client auth** — configure `none` / `simple` / `basic` / `oauth` for the optimizer
+ client in `gravitino-optimizer.conf`, or the matching short names in `updater_options`. See
+ [Gravitino client auth](./optimizer-configuration.md#gravitino-client-auth-cli-and-update-stats).
+ Without credentials that match the server, `submit-strategy-jobs` and update-stats callbacks
+ fail with unauthorized / “credentials did not support”.
+
+2. **REST `warehouse_location`** — for Iceberg REST catalogs this must be the **Gravitino catalog name** (for example `catalog_iceberg_s3`), not an `s3://...` URI. An object-store URI yields `NoSuchWarehouse`. Leave it empty only for local filesystem demos.
+
+3. **Object-store data plane** — Spark must reach table storage through Iceberg REST. On object
+ storage that usually means enabling Iceberg vended credentials
+ (`spark.sql.catalog.<catalog>.header.X-Iceberg-Access-Delegation=vended-credentials`) and
+ configuring IRC `rest.auth.*` for your catalog's auth mode in `spark_conf` (or the matching
+ `gravitino.maintenance.ircAuth.*` cluster settings for the in-process service). Do not copy
+ local `file:///` samples as-is. See
+ [Configuration](./optimizer-configuration.md) (IRC / `spark-conf` auth) and
+ [Troubleshooting](./optimizer-troubleshooting.md#job-execution-failures).
+
+### Demo environment
+
+Do this once. Every task below assumes metalake `test`, catalog `rest_catalog`, and table
+`rest_catalog.db.t1`.
+
+Confirm the built-in templates are registered (`gravitino-jobs` on `auxlib`, then restart if
+needed):
```bash
curl -sS "http://localhost:8090/api/metalakes/test" | jq
@@ -114,12 +138,13 @@ curl -sS "http://localhost:8090/api/metalakes/test/jobs/templates?details=true"
| jq '.jobTemplates[].name'
```
-The template list must include `builtin-iceberg-update-stats` and `builtin-iceberg-rewrite-data-files`. If it does not, the `gravitino-jobs` JAR is missing from `auxlib`. Add it and restart the server before going on.
+Expect at least `builtin-iceberg-update-stats`, `builtin-iceberg-rewrite-data-files`,
+`builtin-iceberg-rewrite-manifests`, `builtin-iceberg-expire-snapshots`, and
+`builtin-iceberg-remove-orphan-files`.
-### Step 2: Create the Demo Catalog, Schema, and Table
+Create the demo catalog, schema, and table (an “already exists” error on the catalog is fine):
```bash
-# Catalog. An "already exists" error here is fine.
curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
-H "Content-Type: application/json" \
-d '{
@@ -134,13 +159,11 @@ curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
}' \
http://localhost:8090/api/metalakes/test/catalogs
-# Schema
curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
-H "Content-Type: application/json" \
-d '{"name": "db", "comment": "maintenance demo schema", "properties": {}}' \
http://localhost:8090/api/metalakes/test/catalogs/rest_catalog/schemas
-# Table
curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
-H "Content-Type: application/json" \
-d '{
@@ -155,9 +178,9 @@ curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
http://localhost:8090/api/metalakes/test/catalogs/rest_catalog/schemas/db/tables
```
-### Step 3: Create Something Worth Compacting
-
-An empty table gives the policy nothing to react to, so write 100,000 rows capped at 1,000 rows per file. That produces the many small files compaction exists to merge.
+Seed data so maintenance has something to act on. Compaction needs many small files (Iceberg
+rewrite defaults to `min-input-files` of 5; one file per partition can finish with
+`Rewritten data files: 0`). The insert below writes 100,000 rows capped at 1,000 rows per file:
```bash
${SPARK_HOME}/bin/spark-sql \
@@ -172,13 +195,64 @@ ${SPARK_HOME}/bin/spark-sql \
```
Without `spark.hadoop.fs.defaultFS=file:///`, Spark reaches for `hdfs://localhost:9000` and fails.
+On object storage, apply the [secured settings](#secured-gravitino-and-iceberg-rest-object-storage)
+instead of the local `file:///` samples.
-### Step 4: Configure a Compaction Policy Through a Tag
+Policy-driven compaction also needs statistics. Submit `builtin-iceberg-update-stats` (see
+[Update Statistics](./optimizer-cli-reference.md#update-statistics)), wait for it to finish, and
+confirm `custom-data-file-mse` and `custom-delete-file-number` on the table. For a secured server,
+put Gravitino client auth short names in `updater_options` and set REST `warehouse_location` to
+the catalog name as in the shared prerequisites.
-Creating the policy is not enough. Associate it with a tag, then assign that tag to the table. The
-service resolves the table's effective policies from its effective tags.
+Shared CLI submitter settings used by policy-driven runs (and as a pattern for `jobSubmitterConfig`
+keys mirrored into direct `jobConf`):
```bash
+cat > /tmp/gravitino-optimizer-submit.conf <<'EOF_CONF'
+gravitino.optimizer.gravitinoUri = http://localhost:8090
+gravitino.optimizer.gravitinoMetalake = test
+gravitino.optimizer.gravitinoDefaultCatalog = rest_catalog
+gravitino.optimizer.recommender.statisticsProvider = gravitino-statistics-provider
+gravitino.optimizer.recommender.strategyProvider = gravitino-strategy-provider
+gravitino.optimizer.recommender.tableMetaProvider = gravitino-table-metadata-provider
+gravitino.optimizer.recommender.jobSubmitter = gravitino-job-submitter
+gravitino.optimizer.strategyHandler.iceberg-data-compaction.className = org.apache.gravitino.maintenance.optimizer.recommender.handler.compaction.CompactionStrategyHandler
+gravitino.optimizer.jobSubmitterConfig.catalog_name = rest_catalog
+gravitino.optimizer.jobSubmitterConfig.spark_master = local[2]
+gravitino.optimizer.jobSubmitterConfig.spark_executor_instances = 1
+gravitino.optimizer.jobSubmitterConfig.spark_executor_cores = 1
+gravitino.optimizer.jobSubmitterConfig.spark_executor_memory = 1g
+gravitino.optimizer.jobSubmitterConfig.spark_driver_memory = 1g
+gravitino.optimizer.jobSubmitterConfig.catalog_type = rest
+gravitino.optimizer.jobSubmitterConfig.catalog_uri = http://localhost:9001/iceberg
+# Local demo: leave empty. Iceberg REST: set to the Gravitino catalog name (not s3://...).
+gravitino.optimizer.jobSubmitterConfig.warehouse_location =
+gravitino.optimizer.jobSubmitterConfig.spark_conf = {"spark.hadoop.fs.defaultFS":"file:///"}
+EOF_CONF
+```
+
+On a secured cluster, add Gravitino client auth from
+[Gravitino client auth](./optimizer-configuration.md#gravitino-client-auth-cli-and-update-stats)
+and the object-store `spark_conf` keys from
+[Secured Gravitino and Iceberg REST](#secured-gravitino-and-iceberg-rest-object-storage).
+
+REST job status is polled rather than pushed, so it lags Spark by up to one
+`gravitino.job.statusPullIntervalInMs` interval. Staging logs live under
+`gravitino.job.stagingDir` (default `/tmp/gravitino/jobs/staging`).
+
+### Compaction
+
+**Job:** `builtin-iceberg-rewrite-data-files` merges small data files.
+
+**Submit**
+
+- Policy path: create policy `iceberg_compaction_default` (`policyType`
+ `system_iceberg_compaction`), associate it with a tag, assign the tag to the table, then run
+ `submit-strategy-jobs` with `--strategy-name` set to the **policy name**. Dry-run first.
+- Direct path: `POST .../jobs/runs` with `jobTemplateName` `builtin-iceberg-rewrite-data-files`.
+
+```bash
+# Policy + tag (creating the policy alone is not enough)
curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
-H "Content-Type: application/json" \
-d '{
@@ -208,138 +282,95 @@ curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
-H "Content-Type: application/json" \
-d '{"tagsToAdd": ["iceberg_compaction"]}' \
http://localhost:8090/api/metalakes/test/objects/table/rest_catalog.db.t1/tags
-```
-
-Confirm the derived policy before moving on:
-```bash
curl -sS "http://localhost:8090/api/metalakes/test/objects/table/rest_catalog.db.t1/policies?details=true" | jq
+
+./bin/gravitino-optimizer.sh \
+ --type submit-strategy-jobs \
+ --identifiers rest_catalog.db.t1 \
+ --strategy-name iceberg_compaction_default \
+ --dry-run \
+ --limit 10 \
+ --conf-path /tmp/gravitino-optimizer-submit.conf
```
-### Step 5: Collect Statistics
+`DRY-RUN` lines mean the policy fired. No output usually means statistics are still below the
+policy thresholds. Drop `--dry-run` to submit.
-```bash
-update_stats_job_id=$(curl -sS -X POST -H "Accept: application/vnd.gravitino.v1+json" \
- -H "Content-Type: application/json" \
- -d '{
- "jobTemplateName": "builtin-iceberg-update-stats",
- "jobConf": {
- "catalog_name": "rest_catalog",
- "table_identifier": "db.t1",
- "update_mode": "all",
- "updater_options": "{\"gravitino_uri\":\"http://localhost:8090\",\"metalake\":\"test\",\"statistics_updater\":\"gravitino-statistics-updater\",\"metrics_updater\":\"gravitino-metrics-updater\"}",
- "spark_conf": "{\"spark.hadoop.fs.defaultFS\":\"file:///\"}",
- "spark_master": "local[2]",
- "spark_executor_instances": "1",
- "spark_executor_cores": "1",
- "spark_executor_memory": "1g",
- "spark_driver_memory": "1g",
- "catalog_type": "rest",
- "catalog_uri": "http://localhost:9001/iceberg",
- "warehouse_location": ""
- }
- }' \
- http://localhost:8090/api/metalakes/test/jobs/runs | jq -r '.job.jobId')
+**Notes**
-echo "update-stats job id: ${update_stats_job_id}"
-```
+- Direct `runJob` requires `where_clause` in `jobConf` (pass `""` for the whole table). `strategy`
+ defaults to `binpack`; `sort_order` / `options` default to empty when omitted. Policy-driven
+ submits fill these through the adapter.
+- A successful job with `Rewritten data files: 0` usually means fewer than `min-input-files`
+ (default 5) eligible files per rewrite group.
-Wait for it to finish, then confirm the statistics landed:
+**Verify:** job run status and
+`.../builtin-iceberg-rewrite-data-files/{jobId}/output.log` for `Rewritten data files`.
+See [Rewrite Data Files](./optimizer-cli-reference.md#rewrite-data-files) and
+[Iceberg Compaction Policy](../iceberg-compaction-policy.md).
-```bash
-curl -sS "http://localhost:8090/api/metalakes/test/objects/table/rest_catalog.db.t1/statistics" | jq
-```
+### Manifest rewrite
-The response must include `custom-data-file-mse` and `custom-delete-file-number`. Those two are what the compaction policy evaluates, so if they are absent the next step has nothing to decide on.
+**Job:** `builtin-iceberg-rewrite-manifests` consolidates manifest metadata for one existing
+partition spec. It leaves data files and other specs' manifests unchanged.
-### Step 6: Evaluate and Submit
+**Submit**
-Write the CLI configuration first. `--strategy-name` takes the **policy name**, not the policy type or the strategy type.
+- Direct path: `POST .../jobs/runs` with `jobTemplateName` `builtin-iceberg-rewrite-manifests`,
+ plus `catalog_name`, `table_identifier`, and the shared Spark/catalog `jobConf` keys.
+- Policy path: `system_iceberg_rewrite_manifests` (strategy type `iceberg-rewrite-manifests`).
+ Collect manifest statistics first, then `submit-strategy-jobs` with the policy name.
-```bash
-cat > /tmp/gravitino-optimizer-submit.conf <<'EOF_CONF'
-gravitino.optimizer.gravitinoUri = http://localhost:8090
-gravitino.optimizer.gravitinoMetalake = test
-gravitino.optimizer.gravitinoDefaultCatalog = rest_catalog
-gravitino.optimizer.recommender.statisticsProvider = gravitino-statistics-provider
-gravitino.optimizer.recommender.strategyProvider = gravitino-strategy-provider
-gravitino.optimizer.recommender.tableMetaProvider = gravitino-table-metadata-provider
-gravitino.optimizer.recommender.jobSubmitter = gravitino-job-submitter
-gravitino.optimizer.strategyHandler.iceberg-data-compaction.className = org.apache.gravitino.maintenance.optimizer.recommender.handler.compaction.CompactionStrategyHandler
-gravitino.optimizer.jobSubmitterConfig.catalog_name = rest_catalog
-gravitino.optimizer.jobSubmitterConfig.spark_master = local[2]
-gravitino.optimizer.jobSubmitterConfig.spark_executor_instances = 1
-gravitino.optimizer.jobSubmitterConfig.spark_executor_cores = 1
-gravitino.optimizer.jobSubmitterConfig.spark_executor_memory = 1g
-gravitino.optimizer.jobSubmitterConfig.spark_driver_memory = 1g
-gravitino.optimizer.jobSubmitterConfig.catalog_type = rest
-gravitino.optimizer.jobSubmitterConfig.catalog_uri = http://localhost:9001/iceberg
-# Leave empty for a local filesystem; set to your warehouse URI for cloud or HDFS storage.
-gravitino.optimizer.jobSubmitterConfig.warehouse_location =
-gravitino.optimizer.jobSubmitterConfig.spark_conf = {"spark.hadoop.fs.defaultFS":"file:///"}
-EOF_CONF
-```
+**Notes**
-Preview first. A dry run evaluates the policy and prints what it would do without submitting anything.
+- Omit `spec_id` to maintain the current partition spec, or pass an existing spec ID.
+- Optional `use_caching` controls Spark caching during the rewrite.
-```bash
-./bin/gravitino-optimizer.sh \
- --type submit-strategy-jobs \
- --identifiers rest_catalog.db.t1 \
- --strategy-name iceberg_compaction_default \
- --dry-run \
- --limit 10 \
- --conf-path /tmp/gravitino-optimizer-submit.conf
-```
+**Verify:** `output.log` rewritten/added manifest counts (both zero can be a successful no-op).
+See [Rewrite Manifests](./optimizer-cli-reference.md#rewrite-manifests) and
+[configuration](./optimizer-configuration.md#rewrite-manifests).
-`DRY-RUN` lines mean the policy fired. No output at all means it did not, which usually means the statistics from step 5 are below the policy thresholds rather than that anything is broken.
+### Snapshot expiry
-Then submit for real:
+**Job:** `builtin-iceberg-expire-snapshots` removes old snapshots and related metadata.
+Compaction and other rewrites create snapshots; without expiry, metadata accumulates.
-```bash
-submit_output=$(./bin/gravitino-optimizer.sh \
- --type submit-strategy-jobs \
- --identifiers rest_catalog.db.t1 \
- --strategy-name iceberg_compaction_default \
- --limit 10 \
- --conf-path /tmp/gravitino-optimizer-submit.conf)
-echo "${submit_output}"
+**Submit**
-strategy_job_id=$(echo "${submit_output}" | sed -n 's/.*jobId=\([^[:space:]]*\).*/\1/p')
-[[ -z "${strategy_job_id}" ]] && echo 'ERROR: failed to extract strategy job ID' && exit 1
-echo "strategy rewrite job id: ${strategy_job_id}"
-```
+- Direct path: `POST .../jobs/runs` with `jobTemplateName` `builtin-iceberg-expire-snapshots`,
+ plus `catalog_name`, `table_identifier`, and the shared Spark/catalog `jobConf` keys.
+- Policy handler wiring:
+ [Snapshot expiration](./optimizer-configuration.md#snapshot-expiration).
-### Step 7: Verify the Rewrite
+**Notes**
-```bash
-curl -sS "http://localhost:8090/api/metalakes/test/jobs/runs/${update_stats_job_id}" | jq
-curl -sS "http://localhost:8090/api/metalakes/test/jobs/runs/${strategy_job_id}" | jq
+- Prefer starting with `retain_last` alone before combining it with `older_than`.
-log_dir="/tmp/gravitino/jobs/staging/test/builtin-iceberg-rewrite-data-files/${strategy_job_id}"
-grep -E "Rewritten data files|Added data files|completed successfully" "${log_dir}/output.log"
-```
+**Verify:** deleted data/manifest counts in `output.log`.
+See [Expire Snapshots](./optimizer-cli-reference.md#expire-snapshots).
+
+### Orphan file cleanup
-`Rewritten data files: N` with `N` greater than zero means the workflow worked end to end. The staging path comes from `gravitino.job.stagingDir`, which defaults to `/tmp/gravitino/jobs/staging`.
+**Job:** `builtin-iceberg-remove-orphan-files` reclaims unreferenced files.
-REST job status is polled rather than pushed, so it lags the real Spark process by up to one poll interval. That is why the prerequisites lower it to ten seconds.
+**Submit**
-## Rewriting Iceberg Manifests
+- Policy path: `system_iceberg_orphan_file_removal` and the handler in
+ [Orphan cleanup](./optimizer-configuration.md#orphan-cleanup).
+ Each explicit optimizer invocation evaluates the enabled policy at table level; it does not
+ require partition statistics or configure a periodic schedule.
+- Direct path: `POST .../jobs/runs` with `jobTemplateName` `builtin-iceberg-remove-orphan-files`.
-`builtin-iceberg-rewrite-manifests` consolidates manifest metadata for one existing partition
-spec to improve scan planning. It leaves data files and other specs' manifests unchanged.
-Submit it directly with `POST /api/metalakes/{metalake}/jobs/runs`, setting
-`jobTemplateName` to `builtin-iceberg-rewrite-manifests` and providing `catalog_name`,
-`table_identifier`, and the Spark/catalog settings in `jobConf`.
+**Notes**
-Omit `spec_id` to maintain the current partition spec, or supply an existing spec ID to
-maintain that spec. Optional `use_caching` controls Spark caching during the rewrite.
-See [Rewrite Manifests](./optimizer-cli-reference.md#rewrite-manifests) for the complete
-submission example and result checks, and [configuration](./optimizer-configuration.md#rewrite-manifests-job)
-for the job keys. Results appear in the job's `output.log`.
+- Start with `dry_run: "true"` and review candidate paths before deletion.
+- Default cutoff is three days ago; explicit cutoffs must be at least 24 hours old (including dry
+ runs). A custom scan location must stay within the table's storage location.
-Policy-driven manifest maintenance through Policy -> Strategy -> Adapter is a follow-up;
-`submit-strategy-jobs` does not yet select this job automatically.
+**Verify:** candidate or deleted paths in `output.log`.
+See [Remove Orphan Files](./optimizer-cli-reference.md#remove-orphan-files) and
+[Configuration](./optimizer-configuration.md#orphan-cleanup).
## Related