Skip to content

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

43.9 KB
Raw Blame

title: "CLI Reference" slug: "/table-maintenance-service/optimizer-cli-reference" keywords: - table maintenance - cli - job template license: "This software is licensed under the Apache License version 2."

Introduction

Use --help to list all commands, or --help --type <command> for command-specific help.

By default, optimizer CLI loads conf/gravitino-optimizer.conf from the current working 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
monitor-metrics --identifiers, --action-time --range-seconds, --partition-path Evaluate rules with before/after metrics
list-table-metrics --identifiers --partition-path Query stored table or partition metrics
list-job-metrics --identifiers None Query stored job metrics
submit-update-stats-job --identifiers --dry-run, --update-mode, --updater-options, --spark-conf Submit built-in Iceberg update stats/metrics Spark jobs

Option Field Meanings

Option Meaning Used by
--identifiers Comma-separated identifiers. See 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
--limit Maximum number of strategy jobs to process. Must be > 0. submit-strategy-jobs
--calculator-name Statistics/metrics calculator implementation name (for example local-stats-calculator). update-statistics, append-metrics
--statistics-payload Inline JSON Lines content as input. Mutually exclusive with --file-path. update-statistics, append-metrics
--file-path Path to JSON Lines input file. Mutually exclusive with --statistics-payload. update-statistics, append-metrics
--action-time Action timestamp in epoch seconds used as evaluation anchor. monitor-metrics
--range-seconds Time window (seconds) for monitor evaluation. Default is 86400 (24h). monitor-metrics
--partition-path Partition path JSON array, for example '[{"dt":"2026-01-01"}]'. Requires exactly one identifier. monitor-metrics, list-table-metrics
--update-mode Controls what built-in update job updates: stats, metrics, or all (default). submit-update-stats-job
--updater-options Flat JSON for updater logic; see submit-update-stats-job. submit-update-stats-job
--spark-conf Flat JSON map of Spark and Iceberg catalog configs used by the job. submit-update-stats-job

Global option:

  • --conf-path: Optional custom config file path. If omitted, CLI uses conf/gravitino-optimizer.conf.

Input Format for local-stats-calculator

local-stats-calculator reads JSON Lines (one JSON object per line).

Reserved Fields

  • stats-type: table, partition, or job
  • identifier: object identifier
  • partition-path: only for partition data, for example {"dt":"2026-01-01"}
  • timestamp: optional epoch seconds (record-level default timestamp for metric points)

All other fields are treated as metric or statistic values.

Supported Examples by Scope

Use JSON Lines (one JSON object per line). The following examples focus on table, partition, and job scopes with multiple metric/statistic fields:

{"stats-type":"table","identifier":"catalog.db.t1","timestamp":1735689600,"row_count":100}
{"stats-type":"table","identifier":"catalog.db.t1","row_count":100,"total_file_size":1048576}
{"stats-type":"table","identifier":"catalog.db.t1","timestamp":1735689660,"row_count":120,"file_count":24,"avg_file_size":10485.76}
{"stats-type":"partition","identifier":"catalog.db.t1","timestamp":1735689720,"partition-path":{"dt":"2026-01-01"},"row_count":20}
{"stats-type":"partition","identifier":"catalog.db.t1","partition-path":{"dt":"2026-01-01","region":"us"},"row_count":12,"file_count":3}
{"stats-type":"job","identifier":"job-1","timestamp":1735689800,"duration_ms":12500,"rewritten_files":18}

Identifier Rules

  • Table and partition records: catalog.schema.table
  • If gravitino.optimizer.gravitinoDefaultCatalog is set, schema.table is also accepted by submit-strategy-jobs, update-statistics, monitor-metrics, list-table-metrics, and submit-update-stats-job
  • append-metrics accepts both table and job identifiers, so it does not apply the default catalog
  • Job records: parsed as a regular Gravitino NameIdentifier
  • For submit-update-stats-job with hierarchical schemas:
    • Gravitino form: catalog.a|b.events (schema may contain gravitino.schema.separator, default :)
    • Spark-physical form: catalog.a.b.events (4+ dotted levels; the CLI joins intermediate levels with the separator from GET /configs)
    • With a default catalog, prefer Gravitino a|b.events (2 levels), or include the catalog in the Spark-physical form (catalog.a.b.events)

CLI Workflow Examples

Batch Statistics Update

Calculate and persist table or partition statistics from JSONL input.

./bin/gravitino-optimizer.sh \
  --type update-statistics \
  --calculator-name local-stats-calculator \
  --file-path ./table-stats.jsonl

Batch Metrics Append

Calculate and append table or job metrics from JSONL input.

./bin/gravitino-optimizer.sh \
  --type append-metrics \
  --calculator-name local-stats-calculator \
  --file-path ./table-stats.jsonl

Dry-Run Strategy Submission

Preview recommendations without actually submitting jobs.

./bin/gravitino-optimizer.sh \
  --type submit-strategy-jobs \
  --identifiers rest_catalog.db.t1 \
  --strategy-name iceberg_compaction_default \
  --dry-run \
  --limit 10

Submit Strategy Jobs

Submit jobs for identifiers that match the given policy name.

./bin/gravitino-optimizer.sh \
  --type submit-strategy-jobs \
  --identifiers rest_catalog.db.t1 \
  --strategy-name iceberg_compaction_default \
  --limit 10

Monitor Metrics

Evaluate monitor rules around an action time.

./bin/gravitino-optimizer.sh \
  --type monitor-metrics \
  --identifiers catalog.db.sales \
  --action-time 1735689600 \
  --range-seconds 86400

Configure evaluator rules in gravitino-optimizer.conf:

gravitino.optimizer.monitor.gravitinoMetricsEvaluator.rules = table:row_count:avg:le,job:duration:latest:le

Rule format is scope:metricName:aggregation:comparison:

  • scope: table or job (table rules also apply to partition scope)
  • aggregation: max|min|avg|latest
  • comparison: lt|le|gt|ge|eq|ne

When metrics are produced by submit-update-stats-job --update-mode metrics, metric names are often custom-* (for example custom-data-file-mse). Use list-table-metrics first and configure rules with the exact metric names returned by your environment.

Submit Built-In Update Stats Jobs

Submit built-in Iceberg update stats/metrics Spark jobs directly.

./bin/gravitino-optimizer.sh \
  --type submit-update-stats-job \
  --identifiers rest_catalog.db.t1 \
  --update-mode all \
  --updater-options '{"gravitino_uri":"http://localhost:8090","metalake":"test","gravitino.optimizer.jdbcMetrics.jdbcUrl":"jdbc:postgresql://localhost:5432/optimizer","gravitino.optimizer.jdbcMetrics.jdbcUser":"postgres","gravitino.optimizer.jdbcMetrics.jdbcPassword":"postgres","gravitino.optimizer.jdbcMetrics.jdbcDriver":"org.postgresql.Driver"}' \
  --spark-conf '{"spark.sql.catalog.rest_catalog.type":"rest","spark.sql.catalog.rest_catalog.uri":"http://localhost:9001/iceberg","spark.hadoop.fs.defaultFS":"file:///"}'

Notes:

  • --identifiers supports catalog.schema.table, schema.table (when default catalog is configured), and for hierarchical schemas also Spark-physical catalog.ns...table (see Identifier Rules).
  • --update-mode supports stats|metrics|all (default all).
  • --updater-options must always include gravitino_uri. The CLI and the Spark job both load gravitino.schema.separator from that server's unauthenticated GET /configs endpoint (including --dry-run, which does not submit a job but still needs a reachable URI). For stats or all, also include metalake. For metrics or all, also include non-blank gravitino.optimizer.jdbcMetrics.jdbcUrl, gravitino.optimizer.jdbcMetrics.jdbcUser, and gravitino.optimizer.jdbcMetrics.jdbcDriver (jdbcPassword may be empty). There is no embedded H2 fallback on that path.
  • When JDBC metrics settings are present, ensure the JDBC driver JAR is available to the Spark runtime classpath of the driver: with the k8s job executor, for example via spark.jars in --spark-conf, which replaces a spark.jars default of the k8s job executor, so list the Iceberg runtime there too if that default provides it; with the local job executor, by installing it into SPARK_HOME/jars, as the driver applies --spark-conf only after it starts.
  • --spark-conf and --updater-options are flat JSON maps.

List Table Metrics

Query stored metrics at table scope.

./bin/gravitino-optimizer.sh \
  --type list-table-metrics \
  --identifiers catalog.db.sales

For partition scope, provide a partition path JSON array:

./bin/gravitino-optimizer.sh \
  --type list-table-metrics \
  --identifiers catalog.db.sales \
  --partition-path '[{"dt":"2026-01-01"}]'

List Job Metrics

Query stored metrics at job scope.

./bin/gravitino-optimizer.sh \
  --type list-job-metrics \
  --identifiers catalog.db.optimizer_job

Output Guide

  • SUMMARY: ...: summary for update-statistics and append-metrics
  • DRY-RUN: ...: recommendation preview without job submission
  • SUBMIT: ...: strategy job or built-in update-stats job submitted successfully
  • SUMMARY: submit-update-stats-job ...: summary for built-in update-stats submission
  • MetricsResult{...}: returned by list commands
  • EvaluationResult{...}: returned by monitor command

Examples:

SUMMARY: statistics totalRecords=3 tableRecords=2 partitionRecords=1 jobRecords=0
DRY-RUN: strategy=iceberg-data-compaction identifier=rest_catalog.db.t1 score=95 jobTemplate=builtin-iceberg-rewrite-data-files jobOptions={catalog_name=rest_catalog, table_identifier=db.t1}
SUBMIT: strategy=iceberg-data-compaction identifier=rest_catalog.db.t1 score=95 jobTemplate=builtin-iceberg-rewrite-data-files jobOptions={catalog_name=rest_catalog, table_identifier=db.t1} jobId=1f54c6d3-4e27-4cc8-bdfa-b05ecf59a4c2
DRY-RUN: identifier=rest_catalog.db.t1 jobTemplate=builtin-iceberg-update-stats jobConfig={catalog_name=rest_catalog, table_identifier=db.t1, update_mode=all, updater_options={"gravitino_uri":"http://localhost:8090","metalake":"test","gravitino.optimizer.jdbcMetrics.jdbcUrl":"jdbc:postgresql://localhost:5432/optimizer","gravitino.optimizer.jdbcMetrics.jdbcUser":"postgres","gravitino.optimizer.jdbcMetrics.jdbcPassword":"******","gravitino.optimizer.jdbcMetrics.jdbcDriver":"org.postgresql.Driver"}, spark_conf={"spark.hadoop.fs.defaultFS":"file:///"}}
SUMMARY: submit-update-stats-job total=1 submitted=1 dryRun=false
MetricsResult{scopeType=TABLE, identifier=rest_catalog.db.t1, partitionPath=<table-or-job-scope>, metrics={row_count=[{timestamp=1735689600, value=100}]}}
EvaluationResult{scopeType=TABLE, identifier=rest_catalog.db.t1, partitionPath=<table-or-job-scope>, evaluation=true, evaluatorName=gravitino-metrics-evaluator, actionTimeSeconds=1735689600, rangeSeconds=86400, beforeMetrics={row_count=[MetricSample{timestampSeconds=1735686000, value=120}]}, afterMetrics={row_count=[MetricSample{timestampSeconds=1735689600, value=100}]}}

Built-in Job Templates

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
builtin-iceberg-remove-orphan-files Removes unreferenced files from storage
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. Compaction, manifest rewrite, snapshot expiry, and orphan cleanup also have policy-driven paths through submit-strategy-jobs. See 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 that runs with your Spark cluster is yours to supply. Provide a matching iceberg-spark-runtime-<sparkMajor>_<scala> JAR on the Spark classpath used by the job executor — commonly by installing it into SPARK_HOME or the Spark image, or, with the k8s job executor, through spark.jars in spark_conf, which the k8s job executor sets when it submits the job. It replaces a spark.jars default of the k8s job executor rather than adding to it, so list every jar the job needs there. With the local job executor, spark.jars in spark_conf doesn't add it, as the driver applies spark_conf only after spark-submit has built its classpath. Align the artifact with the Spark, Scala, and Iceberg versions you actually run. A reference coordinate used in Gravitino's own jobs tests is org.apache.iceberg:iceberg-spark-runtime-3.5_2.12:1.11.0. Without that runtime, built-in Iceberg jobs fail after Spark starts instead of continuing without Iceberg support.

jobConf only needs the required keys below. Optional keys fall back to the template default when left out, and a submission that misses a required key is rejected with an error that lists the missing keys. An empty string is a value, not an omission: it overrides the default and means "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). metrics/all JDBC: Update Statistics.
builtin-iceberg-rewrite-data-files where_clause (pass "" to rewrite the whole table) strategy (binpack), sort_order (empty), options (empty)
builtin-iceberg-expire-snapshots — older_than (empty), retain_last (empty), stream_results (false)
builtin-iceberg-remove-orphan-files — older_than (empty), location (empty), dry_run (false)
builtin-iceberg-rewrite-manifests — use_caching (empty), spec_id (empty)

where_clause has no default on purpose: an empty where clause compacts every data file in the table, so it must be asked for explicitly.

An empty spark_master leaves the master to the job executor: the local job executor runs the job with the spark-submit default local[*], and the k8s job executor rejects any other master than a Kubernetes one. spark.master and spark.submit.deployMode in spark_conf are ignored, as the job is submitted with them already set. So are the spark.kubernetes.* configurations in spark_conf, such as the namespace, the image, the service account, Secrets, and volumes: whoever runs a job sets spark_conf, so only the job executor configurations and job templates may set them.

Update Statistics

builtin-iceberg-update-stats reads a table and writes back the statistics and metrics that policies evaluate. Compaction policies read custom-data-file-mse and custom-delete-file-number, so nothing else will fire until this job has run at least once.

updater_options must include gravitino_uri for every update_mode (including metrics): the job loads gravitino.schema.separator from that server's GET /configs and maps Spark table_identifier values (such as a.b.events) back to Gravitino hierarchical names (such as a|b.events). For stats or all, also include metalake. For metrics or all, also include non-blank gravitino.optimizer.jdbcMetrics.jdbcUrl, jdbcUser, and jdbcDriver (jdbcPassword may be empty). Metrics are written over JDBC to that repository; there is no embedded H2 fallback.

Its jobConf is documented in Configuration.

Update Manifest Statistics

builtin-iceberg-update-manifest-stats is a separate Spark job that collects two table-level 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

The job reads manifest metadata without scanning file statistics. It works after partition evolution, including for specs whose partition fields are absent from older files. builtin-iceberg-update-stats and the submit-update-stats-job CLI retain their existing behavior; they do not collect manifest statistics. Submit the new template directly through the jobs API.

Each table cycle pins one current snapshot, calls allManifests once, and groups data and delete manifests by partitionSpecId. Every defined spec is included. A spec with no manifests, including a table without a snapshot, produces count 0 and average 0.0. The job also publishes custom-manifest-snapshot-id in the same update (-1 without a snapshot). Snapshot IDs identify measurements; they are not monotonically increasing version numbers.

The template accepts catalog_name, table_identifier, updater_options, and optional coordination_directory and spark_conf, alongside the standard Spark template settings. There is no spec_id filter: collection always replaces the complete maps for the table. updater_options is a JSON string that must include gravitino_uri (the job loads gravitino.schema.separator from that server's GET /configs) and metalake; it can also select a statistics_updater implementing the existing table statistics update operation. For example:

curl -X POST http://localhost:8090/api/metalakes/test/jobs/runs \
  -H 'Content-Type: application/json' \
  -d '{
    "jobTemplateName": "builtin-iceberg-update-manifest-stats",
    "jobConf": {
      "catalog_name": "rest_catalog",
      "table_identifier": "db.t1",
      "updater_options": "{\"gravitino_uri\":\"http://localhost:8090\",\"metalake\":\"test\"}",
      "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": ""
    }
  }'

For example, one collection can produce complete maps {"0": 620, "1": 120} and {"0": 10485760.0, "1": 4194304.0}. The collector owns both statistic names and publishes them together with the snapshot ID in one existing PUT/update call. Old map entries are replaced, not merged. Other statistic names are unchanged. No PATCH or merge API is needed.

By default, coordination_directory is omitted or blank and publications use last-write-wins semantics. Each update contains the complete maps and snapshot ID; a concurrent older collection may overwrite newer measurements. Failed jobs can simply be rerun, with no lock files or recovery. Consumers requiring fresh statistics must compare custom-manifest-snapshot-id with the table's current snapshot ID (-1 if none) and skip/recollect on a mismatch. This is a consumer requirement, not a freshness check enforced by this collector. Snapshot IDs must be compared for equality, not numerical ordering.

Optional shared coordination and recovery

For stricter serialization, provision coordination_directory (--coordination-dir for direct Spark invocation) as an existing absolute directory on a shared filesystem that supports durable files and cross-host Java/POSIX file locks. Every runner for a destination table must use the same shared directory, metalake, and canonical catalog/schema/table names. A host-local directory, object-store mount, or filesystem without reliable cross-host locking does not satisfy this requirement. All writers of these statistic names must opt into this mode and use the same directory; mixing coordinated and uncoordinated writers does not provide serialization.

The job locks a persistent file keyed by metalake and table before refreshing the Iceberg table or choosing a snapshot, and holds it through the PUT. Concurrent runs for that table fail; other tables can proceed. Snapshot IDs are recorded for provenance, not compared numerically. The job forces gravitino.client.retryTimes=0 for its Gravitino client. Custom statistics updaters and any intervening proxies must likewise avoid retrying PUT requests; an automatic resend could hide an original request that is still executing. There are no expiring leases, automatic retries, scheduling, or cooldowns.

Collection failures can be rerun normally: the lock is released without leaving a recovery marker. After collection and immediately before calling the updater, the job durably writes an in-progress marker. It clears the marker only after a successful update. A crash after the marker is written or an update failure leaves the marker in place, even after the operating system releases the lock. The updater interface cannot distinguish a failed request from a request still executing on the server, so these failures require recovery. The error reports the recovery file path.

For example, run A sends a PUT and loses its connection while the server is still processing it. An immediate rerun B could publish newer measurements before A's delayed PUT overwrites them. The file lock prevents concurrent collection across hosts; the marker prevents this overlap after an ambiguous failure. Snapshot IDs provide provenance, but the existing PUT does not enforce snapshot ordering or fencing. Automatic reruns after ambiguous writes would require server-side conditional publication or an equivalent guarantee that the earlier request has ended.

For recovery, stop all runners for that table and verify the previous process has terminated and any outstanding Gravitino PUT has completed or been definitively cancelled. While holding an exclusive lock on the reported file, truncate it to zero bytes and flush it to durable storage, then resume collection. Never delete or replace the file: a new inode can permit two independent locks. If the previous PUT outcome cannot be established, leave the marker intact.

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. After collection, evaluate and submit with a system_iceberg_rewrite_manifests policy through submit-strategy-jobs (see Rewrite Manifests).

Rewrite Data Files

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.

Property Value
Name builtin-iceberg-rewrite-data-files
Type Spark
Version v1
Main class org.apache.gravitino.maintenance.jobs.iceberg.IcebergRewriteDataFilesJob

Parameters

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. 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.

Submitting the Job

curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
  -H "Content-Type: application/json" \
  -d '{
    "jobTemplateName": "builtin-iceberg-rewrite-data-files",
    "jobConf": {
      "catalog_name": "rest_catalog",
      "table_identifier": "db.t1",
      "strategy": "binpack",
      "sort_order": "",
      "where_clause": "",
      "options": "",
      "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": "",
      "spark_conf": "{\"spark.hadoop.fs.defaultFS\":\"file:///\"}"
    }
  }' \
  http://localhost:8090/api/metalakes/test/jobs/runs

Policy-driven submission uses submit-strategy-jobs with a compaction policy name. For threshold tuning see Iceberg Compaction Policy.

Verifying the Result

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 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.

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. Omitted or blank optional argument values use the defaults below; unresolved optional template placeholders are 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.

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:

SELECT DISTINCT partition_spec_id
FROM rest_catalog.db.t1.manifests;

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 and Configuration.

Submitting the Job

curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
  -H "Content-Type: application/json" \
  -d '{
    "jobTemplateName": "builtin-iceberg-rewrite-manifests",
    "jobConf": {
      "catalog_name": "rest_catalog",
      "table_identifier": "db.t1",
      "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

Adding "use_caching": "false" and "spec_id": "2" to jobConf produces:

CALL `rest_catalog`.system.rewrite_manifests(
  table => 'db.t1',
  use_caching => false,
  spec_id => 2
)

Verifying the Result

curl -sS "http://localhost:8090/api/metalakes/test/jobs/runs/{job_id}" | jq '.job.status'
cat /tmp/gravitino/jobs/staging/test/builtin-iceberg-rewrite-manifests/{job_id}/output.log

A successful run reports SUCCEEDED and logs how many manifests it replaced:

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.

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, which slows table operations and wastes storage. Compaction and other rewrites create snapshots; expire cleans them up.

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

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:

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.

Verifying the Result

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:

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. 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
catalog_name Iceberg catalog registered in Spark Required
table_identifier Table identifier within that catalog, such as db.sample Required
older_than Cutoff timestamp in the Spark session time zone; 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 map of custom Spark configuration None

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.

Submitting the Job

Start with dry_run: "true" and review candidate paths before deleting:

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

Policy-driven submission uses system_iceberg_orphan_file_removal; see Orphan cleanup. CLI equivalents for direct Spark invocation are --catalog, --table, --older-than, --location, --dry-run true|false, and --spark-conf.

Verifying the Result

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