Skip to content

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

[#15158] improvement(maintenance): Complete TMS Validation before/after metrics (#15160)

MaSai79eea049bd4b
diff --git a/api/src/main/java/org/apache/gravitino/policy/IcebergDataCompactionContent.java b/api/src/main/java/org/apache/gravitino/policy/IcebergDataCompactionContent.java
index 61aeccf7f2..54eab4584d 100644
--- a/api/src/main/java/org/apache/gravitino/policy/IcebergDataCompactionContent.java
+++ b/api/src/main/java/org/apache/gravitino/policy/IcebergDataCompactionContent.java
@@ -82,6 +82,14 @@ public class IcebergDataCompactionContent extends AbstractExecutablePolicyConten
public static final String TOTAL_FILE_SIZE_METRIC = "custom-total-file-size";
/** TMS S0/S1 metric: total file count. */
public static final String FILE_NUMBER_METRIC = "custom-file-number";
+ /** TMS S0/S1 metric: count of files smaller than 32 MiB. */
+ public static final String SMALL_FILE_NUMBER_METRIC = "custom-small-file-number";
+ /**
+ * TMS S0/S1 display metric: {@value DATA_FILE_MSE_METRIC} divided by policy {@value
+ * MIN_DATA_FILE_MSE_KEY} (Fragmentation multiple). Enriched by the TMS orchestrator from task
+ * rules; not produced by inventory SQL alone.
+ */
+ public static final String DATA_MSE_RATIO_METRIC = "custom-data-mse-ratio";
/** Default minimum threshold for data file MSE metric, equals (128 MiB * 0.15)^2. */
public static final long DEFAULT_MIN_DATA_FILE_MSE = 405323966463344L;
/** Default minimum threshold for delete file number metric. */
diff --git a/docs/iceberg-compaction-policy.md b/docs/iceberg-compaction-policy.md
index 5c78c22621..d36aa266fc 100644
--- a/docs/iceberg-compaction-policy.md
+++ b/docs/iceberg-compaction-policy.md
@@ -19,16 +19,16 @@ This policy supports `CATALOG`, `SCHEMA`, and `TABLE` metadata objects.
The typed content for `system_iceberg_compaction` supports the following fields:
-| Field | Required | Default | Description |
-| ------------------------ | -------- | ------------------- | ------------------------------------------------------------------------------------------------------------- |
-| `minDataFileMse` | No | `405323966463344` | Minimum threshold for metric `custom-data-file-mse`. Must be `>= 0`. |
-| `minDeleteFileNumber` | No | `1` | Minimum threshold for metric `custom-delete-file-number`. Must be `>= 0`. |
-| `dataFileMseWeight` | No | `1` | Score weight of `custom-data-file-mse`. Must be `>= 0`. |
-| `deleteFileNumberWeight` | No | `100` | Score weight of `custom-delete-file-number`. Must be `>= 0`. |
-| `maxPartitionNum` | No | `50` | Maximum number of partitions selected by optimizer. Must be `> 0`. |
-| `rewriteStrategy` | No | `binpack` | Iceberg `rewrite_data_files` top-level `strategy`. Supported values: `binpack`, `sort`. |
-| `sortOrder` | No | `""` | Iceberg `rewrite_data_files` top-level `sort_order`. Required for `sort`; must be empty for `binpack`. |
-| `rewriteOptions` | No | `{}` | Iceberg `rewrite_data_files` `options` map entries, expanded as `job.options.*` rules. |
+| Field | Required | Default | Description |
+| ------------------------ | -------- | ----------------- | ------------------------------------------------------------------------------------------------------ |
+| `minDataFileMse` | No | `405323966463344` | Minimum threshold for metric `custom-data-file-mse`. Must be `>= 0`. |
+| `minDeleteFileNumber` | No | `1` | Minimum threshold for metric `custom-delete-file-number`. Must be `>= 0`. |
+| `dataFileMseWeight` | No | `1` | Score weight of `custom-data-file-mse`. Must be `>= 0`. |
+| `deleteFileNumberWeight` | No | `100` | Score weight of `custom-delete-file-number`. Must be `>= 0`. |
+| `maxPartitionNum` | No | `50` | Maximum number of partitions selected by optimizer. Must be `> 0`. |
+| `rewriteStrategy` | No | `binpack` | Iceberg `rewrite_data_files` top-level `strategy`. Supported values: `binpack`, `sort`. |
+| `sortOrder` | No | `""` | Iceberg `rewrite_data_files` top-level `sort_order`. Required for `sort`; must be empty for `binpack`. |
+| `rewriteOptions` | No | `{}` | Iceberg `rewrite_data_files` `options` map entries, expanded as `job.options.*` rules. |
`rewriteStrategy` and `sortOrder` are **not** part of `rewriteOptions`. Iceberg treats them as procedure
parameters separate from the `options` map.
diff --git a/docs/iceberg-orphan-file-removal-policy.md b/docs/iceberg-orphan-file-removal-policy.md
new file mode 100644
index 0000000000..5401b2be30
--- /dev/null
+++ b/docs/iceberg-orphan-file-removal-policy.md
@@ -0,0 +1,91 @@
+---
+title: "Iceberg Orphan File Removal Policy"
+slug: "/iceberg-orphan-file-removal-policy"
+keyword: "iceberg, orphan, cleanup, policy, optimizer, Gravitino"
+license: "This software is licensed under the Apache License version 2."
+---
+
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+## Overview
+
+`system_iceberg_orphan_file_removal` is a built-in policy type used by the optimizer and the
+Table Maintenance Service to remove unreferenced Iceberg files through
+`builtin-iceberg-remove-orphan-files`.
+
+This policy supports `CATALOG`, `SCHEMA`, and `TABLE` metadata objects. It accepts time triggers
+only; `commitTrigger=true` is rejected.
+
+## Policy Content
+
+The typed content for `system_iceberg_orphan_file_removal` supports the following fields:
+
+| Field | Required | Default | Description |
+| --------------- | -------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
+| `olderThanDays` | No | `3` | Minimum age of orphan files eligible for removal, in days. Must be between `1` and `36500`. |
+| `location` | No | Table location | Optional absolute scan path within the table. Must be a valid absolute URI path without query, fragment, `..`, `\`, or percent-encoding. |
+| `dryRun` | No | `false` | When `true`, list candidates without deleting. JSON boolean only. |
+
+## Generated Rules and Properties
+
+The policy content is converted to:
+
+- Properties:
+ - `strategy.type=iceberg-orphan-file-removal`
+ - `job.template-name=builtin-iceberg-remove-orphan-files`
+- Rules:
+ - `trigger-expr=true`
+ - `score-expr=1`
+ - `job.options.olderThanDays=<olderThanDays>`
+ - `job.options.dryRun=<dryRun>`
+ - `job.options.location=<location>` when `location` is set
+
+The optimizer or TMS schedule decides when to submit the job. Once the Spark job starts, it
+always runs the orphan-cleanup procedure (`trigger-expr=true`); there is no extra metric gate
+inside Spark.
+
+## Policy Examples
+
+<Tabs groupId='language' queryString>
+<TabItem value="shell" label="Shell">
+
+```shell
+curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "name": "iceberg_orphan_cleanup_default",
+ "comment": "Built-in iceberg orphan file removal policy",
+ "policyType": "system_iceberg_orphan_file_removal",
+ "enabled": true,
+ "content": {}
+ }' \
+ http://localhost:8090/api/metalakes/test/policies
+```
+
+</TabItem>
+<TabItem value="java" label="Java">
+
+```java
+GravitinoClient client = ...;
+
+PolicyContent content = PolicyContents.icebergOrphanFileRemoval();
+
+Policy policy =
+ client.createPolicy(
+ "iceberg_orphan_cleanup_default",
+ "system_iceberg_orphan_file_removal",
+ "Built-in iceberg orphan file removal policy",
+ true,
+ content);
+```
+
+</TabItem>
+</Tabs>
+
+## Apply the Policy Through a Tag
+
+After creating the policy, create or reuse a tag, associate the policy with that tag using the
+`ALL_VALUES` selector, and assign the tag to a table or one of its ancestors. See
+[Manage Policies](./manage-policies-in-gravitino.md#policy-to-tag-associations) and
+[Remove Orphan Files](./table-maintenance-service/optimizer-cli-reference.md#remove-orphan-files).
diff --git a/docs/iceberg-rewrite-manifests-policy.md b/docs/iceberg-rewrite-manifests-policy.md
index 2e128923a9..22a73f1f6c 100644
--- a/docs/iceberg-rewrite-manifests-policy.md
+++ b/docs/iceberg-rewrite-manifests-policy.md
@@ -5,27 +5,42 @@ keyword: "iceberg, manifests, policy, optimizer, Gravitino"
license: "This software is licensed under the Apache License version 2."
---
-## Behavior
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+## Overview
`system_iceberg_rewrite_manifests` evaluates manifest statistics for one resolved partition
-spec and submits `builtin-iceberg-rewrite-manifests`. Associate the policy with a tag and
-assign that tag to a catalog, schema, or table through the existing
-[policy API](./manage-policies-in-gravitino.md). Tables inherit tags from their ancestors.
-The strategy type is `iceberg-rewrite-manifests`; its handler and job adapter are built in.
+spec and submits `builtin-iceberg-rewrite-manifests`. The strategy type is
+`iceberg-rewrite-manifests`; its handler and job adapter are built in.
+
+This policy supports `CATALOG`, `SCHEMA`, and `TABLE` metadata objects.
+
+## Policy Content
-| Content field | Default | Meaning |
-| --- | --- | --- |
-| `manifest_count_threshold` | `100` | Trigger when manifest count is at least this value. Aligns with Iceberg `commit.manifest.min-count-to-merge`. Must be positive. |
-| `spec_id` | Iceberg's current default | Existing partition spec to evaluate. Omission resolves the current default from Iceberg metadata. |
-| `use_caching` | Omitted | Optional boolean forwarded to Iceberg; omission preserves the runtime default. |
+The typed content for `system_iceberg_rewrite_manifests` supports the following fields:
+
+| Field | Required | Default | Description |
+| -------------------------- | -------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
+| `manifest_count_threshold` | No | `100` | Trigger when manifest count is at least this value. Aligns with Iceberg `commit.manifest.min-count-to-merge`. Must be positive. |
+| `spec_id` | No | Iceberg's current default | Existing partition spec to evaluate. Omission resolves the current default from Iceberg metadata. |
+| `use_caching` | No | Omitted | Optional boolean forwarded to Iceberg; omission preserves the runtime default. JSON booleans only. |
Spec IDs must be non-negative 32-bit integers. Recommendations are ranked by the selected
-spec's manifest count. Average manifest size is still collected for observability but does
-not affect the trigger. The policy API accepts only JSON booleans for `use_caching`; numbers
-and strings are rejected.
+spec's manifest count. Average manifest size is collected for observability but does not
+affect the trigger. At the default threshold, 99 manifests never trigger and 100 or more
+trigger regardless of average manifest size.
+
+## Generated Rules and Properties
+
+The policy content is converted to:
-At the default threshold, 99 manifests never trigger and 100 or more trigger regardless of
-average manifest size.
+- Properties:
+ - `strategy.type=iceberg-rewrite-manifests`
+ - `job.template-name=builtin-iceberg-rewrite-manifests`
+- Rules:
+ - `trigger-expr=custom-manifest-number >= manifest_count_threshold`
+ - optional `spec_id` and `use_caching` job options when set
## Collect, evaluate, and submit
@@ -39,22 +54,34 @@ metadata supplied by the optimizer's table metadata provider. Missing, malformed
mismatched snapshot IDs produce no recommendation; recollect before evaluating again.
For a table without a snapshot, the collector publishes `-1` and Iceberg table metadata
reports `none`. The provider must expose this metadata property to verify freshness.
-The recommender reads metadata after statistics to detect snapshot changes during collection
-of its inputs. This freshness check is not transactional with job submission; the table may
-still change after evaluation.
The handler reads the chosen spec's count and average from the same statistics response.
A missing map or key produces no recommendation. An empty spec has count and average zero.
Invalid policy rules or malformed measurements are logged and skipped for that table without
aborting recommendations for other tables. Counts from other specs are ignored.
-The recommender and CLI use the table's current default partition spec when `spec_id` is
-omitted. The following example uses default thresholds and assumes statistics have been collected:
+When `spec_id` is omitted, the recommender resolves Iceberg's current `default-spec-id` from
+table metadata and retains that value through job submission. The maintenance job leaves an
+omitted `spec_id` unset at schedule time and resolves the table's current default when the
+Spark job runs. Set `spec_id` explicitly to target another existing spec after partition
+evolution.
+
+Rewriting reorganizes manifests within the selected spec and does not migrate data files
+between specs. Recollect statistics after a successful rewrite before evaluating again.
+For runtime requirements and direct job submission, see the
+[rewrite-manifests job reference](./table-maintenance-service/optimizer-cli-reference.md).
+
+## Policy Examples
+
+<Tabs groupId='language' queryString>
+<TabItem value="shell" label="Shell">
```shell
-curl -X POST -H 'Content-Type: application/json' \
+curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
+ -H "Content-Type: application/json" \
-d '{
"name": "rewrite_manifests",
+ "comment": "Built-in iceberg rewrite manifests policy",
"policyType": "system_iceberg_rewrite_manifests",
"enabled": true,
"content": {}
@@ -62,44 +89,29 @@ curl -X POST -H 'Content-Type: application/json' \
http://localhost:8090/api/metalakes/test/policies
```
-Associate `rewrite_manifests` with a tag using the `ALL_VALUES` selector, then assign that tag
-to the table. Configure the optimizer's Gravitino providers and Spark submission settings as described in
-[Optimizer configuration](./table-maintenance-service/optimizer-configuration.md), then preview:
+</TabItem>
+<TabItem value="java" label="Java">
-```shell
-./bin/gravitino-optimizer.sh --type submit-strategy-jobs \
- --identifiers rest_catalog.db.t1 --strategy-name rewrite_manifests --dry-run
-```
+```java
+GravitinoClient client = ...;
+
+PolicyContent content = PolicyContents.icebergRewriteManifests();
-Remove `--dry-run` to submit the recommendations. The adapter supplies `catalog_name`,
-`table_identifier`, the exact evaluated `spec_id`, and optional `use_caching`.
-Its catalog, table, spec, and caching values override shared job-submitter configuration.
-When the policy omits `use_caching`, the adapter supplies an empty option to clear any shared
-caching setting and leave the Iceberg runtime default in effect.
-Recollect statistics after a successful rewrite before evaluating again.
+Policy policy =
+ client.createPolicy(
+ "rewrite_manifests",
+ "system_iceberg_rewrite_manifests",
+ "Built-in iceberg rewrite manifests policy",
+ true,
+ content);
+```
-## Selecting a partition spec
+</TabItem>
+</Tabs>
-When `spec_id` is omitted, the recommender resolves Iceberg's current `default-spec-id` from
-table metadata and retains that value through job submission. TMS leaves an omitted
-`spec_id` unset at schedule time and resolves the table's current default when the Spark job
-runs. Empty policy content therefore targets the current default spec with the default
-thresholds. Set `spec_id` explicitly to target another existing spec, such as an older spec
-after partition evolution.
-
-The Iceberg catalog projects `TableMetadata.defaultSpecId()` as the reserved, read-only table
-property `default-spec-id`. This is metadata, not an operator setting; it cannot be set or
-removed through Gravitino table-property changes. Custom metadata providers must expose the
-same value from Iceberg metadata. If an omitted target cannot be resolved because metadata is
-missing or invalid, the recommender warns and skips that table without aborting the batch.
-
-The resolved ID is used for both statistics lookup and job submission. Partition evolution
-after evaluation cannot retarget an already-created job context. A later evaluation with an
-omitted `spec_id` resolves the new default; an explicit policy target remains unchanged.
-The handler never infers a spec from statistics map keys. After a snapshot change, recollect
-statistics before evaluating again.
+## Apply the Policy Through a Tag
-Rewriting reorganizes manifests within the selected spec and does not migrate data files
-between specs. This policy introduces no scheduling, cooldown, or last-success statistic.
-For runtime requirements and direct job submission, see the
-[rewrite-manifests job reference](./table-maintenance-service/optimizer-cli-reference.md).
+After creating the policy, create or reuse a tag, associate the policy with that tag using the
+`ALL_VALUES` selector, and assign the tag to a table or one of its ancestors. See
+[Manage Policies](./manage-policies-in-gravitino.md#policy-to-tag-associations) and
+[Optimizer configuration](./table-maintenance-service/optimizer-configuration.md).
diff --git a/docs/iceberg-snapshot-expiration-policy.md b/docs/iceberg-snapshot-expiration-policy.md
new file mode 100644
index 0000000000..de869c587d
--- /dev/null
+++ b/docs/iceberg-snapshot-expiration-policy.md
@@ -0,0 +1,90 @@
+---
+title: "Iceberg Snapshot Expiration Policy"
+slug: "/iceberg-snapshot-expiration-policy"
+keyword: "iceberg, snapshot, expiration, policy, optimizer, Gravitino"
+license: "This software is licensed under the Apache License version 2."
+---
+
+import Tabs from '@theme/Tabs';
+import TabItem from '@theme/TabItem';
+
+## Overview
+
+`system_iceberg_snapshot_expiration` is a built-in policy type used by the optimizer and the
+Table Maintenance Service to expire old Iceberg snapshots through
+`builtin-iceberg-expire-snapshots`.
+
+This policy supports `CATALOG`, `SCHEMA`, and `TABLE` metadata objects.
+
+## Policy Content
+
+The typed content for `system_iceberg_snapshot_expiration` supports the following fields:
+
+| Field | Required | Default | Description |
+| --------------- | -------- | ------- | ------------------------------------------------------------------------------------------- |
+| `olderThanDays` | No | `5` | Minimum age of snapshots eligible for expiration, in days. Must be between `1` and `36500`. |
+| `retainLast` | No | `1` | Minimum number of recent snapshots to keep regardless of age. Must be `>= 1`. |
+| `streamResults` | No | `false` | Whether the expire job should stream intermediate delete results. JSON boolean only. |
+
+## Generated Rules and Properties
+
+The policy content is converted to:
+
+- Properties:
+ - `strategy.type=iceberg-snapshot-expiration`
+ - `job.template-name=builtin-iceberg-expire-snapshots`
+- Rules:
+ - `trigger-expr=true`
+ - `score-expr=1`
+ - `job.options.olderThanDays=<olderThanDays>`
+ - `job.options.retainLast=<retainLast>`
+ - `job.options.streamResults=<streamResults>`
+
+The optimizer or TMS schedule decides when to submit the job. Once the Spark job starts, it
+always runs the expire procedure (`trigger-expr=true`); there is no extra metric gate inside
+Spark.
+
+## Policy Examples
+
+<Tabs groupId='language' queryString>
+<TabItem value="shell" label="Shell">
+
+```shell
+curl -X POST -H "Accept: application/vnd.gravitino.v1+json" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "name": "iceberg_snapshot_expiration_default",
+ "comment": "Built-in iceberg snapshot expiration policy",
+ "policyType": "system_iceberg_snapshot_expiration",
+ "enabled": true,
+ "content": {}
+ }' \
+ http://localhost:8090/api/metalakes/test/policies
+```
+
+</TabItem>
+<TabItem value="java" label="Java">
+
+```java
+GravitinoClient client = ...;
+
+PolicyContent content = PolicyContents.icebergSnapshotExpiration();
+
+Policy policy =
+ client.createPolicy(
+ "iceberg_snapshot_expiration_default",
+ "system_iceberg_snapshot_expiration",
+ "Built-in iceberg snapshot expiration policy",
+ true,
+ content);
+```
+
+</TabItem>
+</Tabs>
+
+## Apply the Policy Through a Tag
+
+After creating the policy, create or reuse a tag, associate the policy with that tag using the
+`ALL_VALUES` selector, and assign the tag to a table or one of its ancestors. See
+[Manage Policies](./manage-policies-in-gravitino.md#policy-to-tag-associations) and
+[Snapshot expiration](./table-maintenance-service/optimizer-configuration.md#snapshot-expiration).
diff --git a/docs/manage-policies-in-gravitino.md b/docs/manage-policies-in-gravitino.md
index 6028867390..e500007e8b 100644
--- a/docs/manage-policies-in-gravitino.md
+++ b/docs/manage-policies-in-gravitino.md
@@ -91,9 +91,12 @@ policy = client.create_policy(
</TabItem>
</Tabs>
-The built-in compaction policy has a fixed content shape, documented in
-[Iceberg compaction policy](./iceberg-compaction-policy.md), and a helper that builds it with
-defaults.
+Built-in Iceberg maintenance policies have fixed content shapes. See
+[Iceberg compaction policy](./iceberg-compaction-policy.md),
+[Iceberg rewrite manifests policy](./iceberg-rewrite-manifests-policy.md),
+[Iceberg snapshot expiration policy](./iceberg-snapshot-expiration-policy.md), and
+[Iceberg orphan file removal policy](./iceberg-orphan-file-removal-policy.md). Compaction also has
+a helper that builds defaults:
```java
Policy policy = client.createPolicy(
diff --git a/docs/open-api/maintenance/maintenance.yaml b/docs/open-api/maintenance/maintenance.yaml
index 8ada6d5d59..0fd9017535 100644
--- a/docs/open-api/maintenance/maintenance.yaml
+++ b/docs/open-api/maintenance/maintenance.yaml
@@ -182,7 +182,10 @@ components:
description: Iceberg snapshot id stored on the new table_snapshot_metrics row
metricsJson:
type: string
- description: Serialized metrics JSON for table_snapshot_metrics.metrics_value
+ description: >
+ Serialized metrics JSON for table_snapshot_metrics.metrics_value. Contains only
+ metric fields (for example custom-* keys); policy type and snapshot id are not
+ embedded here. Key sets differ by maintenance policy type.
MaintenanceActionFinishRequest:
type: object
required:
@@ -204,14 +207,14 @@ components:
"tableId": 10,
"policyId": 20,
"snapshotId": 9001,
- "metricsJson": "{\"maintenanceType\":\"rewrite_data_files\",\"snapshotId\":9001,\"custom-data-file-mse\":1.5}"
+ "metricsJson": "{\"custom-data-file-mse\":1.5,\"custom-delete-file-number\":0,\"custom-avg-file-size\":1048576,\"custom-total-file-size\":3145728,\"custom-file-number\":3,\"custom-small-file-number\":3,\"custom-data-mse-ratio\":3.7}"
}
MaintenanceActionAfterMetricsRequest:
value: {
"tableId": 10,
"policyId": 20,
"snapshotId": 9002,
- "metricsJson": "{\"maintenanceType\":\"rewrite_data_files\",\"snapshotId\":9002,\"custom-data-file-mse\":0.2}"
+ "metricsJson": "{\"custom-data-file-mse\":0.2,\"custom-delete-file-number\":0,\"custom-avg-file-size\":134217728,\"custom-total-file-size\":134217728,\"custom-file-number\":1,\"custom-small-file-number\":0,\"custom-data-mse-ratio\":0.49}"
}
MaintenanceActionFinishRequest:
value: {
diff --git a/docs/policies.md b/docs/policies.md
index 759fb66cdb..4eca76b77e 100644
--- a/docs/policies.md
+++ b/docs/policies.md
@@ -35,15 +35,24 @@ policy. A table with only `data_domain=risk` does not.
### Policy Types and Content
-| Type | Rules | Consumer |
-| ------------------------------------ | ------------------------------------------ | ------------------------- |
-| `system_iceberg_compaction` | Compaction thresholds and scheduling | Table maintenance service |
-| `system_iceberg_rewrite_manifests` | Manifest count and average-size thresholds | Table maintenance service |
-| `system_iceberg_orphan_file_removal` | Orphan-file cleanup options | Table maintenance service |
-| `system_row_filter` | Row-filter expression | Experimental Iceberg REST |
-| `system_column_mask` | Column-mask expression | Experimental Iceberg REST |
-| `system_access_control` | Privileges and applicable roles | Not enforced yet |
-| `custom` | A free-form map that you define | A system that you provide |
+| Type | Rules | Consumer |
+| ------------------------------------ | ---------------------------------------- | ------------------------- |
+| `system_iceberg_compaction` | Compaction thresholds and scheduling | Table maintenance service |
+| `system_iceberg_rewrite_manifests` | Manifest count threshold and target spec | Table maintenance service |
+| `system_iceberg_snapshot_expiration` | Snapshot retention age and retain-last | Table maintenance service |
+| `system_iceberg_orphan_file_removal` | Orphan-file cleanup options | Table maintenance service |
+| `system_row_filter` | Row-filter expression | Experimental Iceberg REST |
+| `system_column_mask` | Column-mask expression | Experimental Iceberg REST |
+| `system_access_control` | Privileges and applicable roles | Not enforced yet |
+| `custom` | A free-form map that you define | A system that you provide |
+
+Iceberg maintenance policy fields are documented in
+[Iceberg compaction policy](./iceberg-compaction-policy.md),
+[Iceberg rewrite manifests policy](./iceberg-rewrite-manifests-policy.md),
+[Iceberg snapshot expiration policy](./iceberg-snapshot-expiration-policy.md), and
+[Iceberg orphan file removal policy](./iceberg-orphan-file-removal-policy.md).
+Before and after Validation metrics reported by the Table Maintenance Service are listed in
+[Service](./table-maintenance-service/service.md#validation-before-and-after-metrics).
Row-filter and column-mask policies can be associated with tags and returned as read restrictions
by the experimental Iceberg REST service. Compatible readers enforce those restrictions. The
@@ -143,10 +152,11 @@ orExpr := andExpr (OR andExpr)*
andExpr := notExpr (AND notExpr)*
notExpr := NOT* predicate
predicate := scalar (compareOp scalar
- | IS NOT? NULL
- | NOT? IN "(" literal ("," literal)* ")"
- | NOT? BETWEEN scalar AND scalar
- | NOT? LIKE string)?
+| IS NOT? NULL |
+| -------------------------------------- |
+| NOT? IN "(" literal ("," literal)* ")" |
+| NOT? BETWEEN scalar AND scalar |
+| NOT? LIKE string)? |
scalar := identifier | literal | functionCall | caseExpr | "(" expr ")"
functionCall := identifier "(" (expr ("," expr)*)? ")"
caseExpr := CASE expr? (WHEN expr THEN expr)+ (ELSE expr)? END
diff --git a/docs/table-maintenance-service/optimizer-configuration.md b/docs/table-maintenance-service/optimizer-configuration.md
index 283565f195..b83cc14c77 100644
--- a/docs/table-maintenance-service/optimizer-configuration.md
+++ b/docs/table-maintenance-service/optimizer-configuration.md
@@ -467,7 +467,9 @@ The adapter supplies `table_identifier`, `older_than`, `location`, and `dry_run`
Optional TMS peer fields on content (`timeTrigger`, `commitTrigger`, `minIntervalMs`, `jobOptions`,
`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
+orphan cleanup. See [Iceberg compaction policy](../iceberg-compaction-policy.md),
+[Iceberg snapshot expiration policy](../iceberg-snapshot-expiration-policy.md), and
+[Iceberg orphan file removal policy](../iceberg-orphan-file-removal-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`.
diff --git a/docs/table-maintenance-service/optimizer.md b/docs/table-maintenance-service/optimizer.md
index c9fc7f53a3..e39c03bbf7 100644
--- a/docs/table-maintenance-service/optimizer.md
+++ b/docs/table-maintenance-service/optimizer.md
@@ -345,6 +345,8 @@ Compaction and other rewrites create snapshots; without expiry, metadata accumul
- Direct path: `POST .../jobs/runs` with `jobTemplateName` `builtin-iceberg-expire-snapshots`,
plus `catalog_name`, `table_identifier`, and the shared Spark/catalog `jobConf` keys.
+- Policy path: `system_iceberg_snapshot_expiration`
+ ([Iceberg snapshot expiration policy](../iceberg-snapshot-expiration-policy.md)).
- Policy handler wiring:
[Snapshot expiration](./optimizer-configuration.md#snapshot-expiration).
@@ -361,8 +363,9 @@ See [Expire Snapshots](./optimizer-cli-reference.md#expire-snapshots).
**Submit**
-- Policy path: `system_iceberg_orphan_file_removal` and the handler in
- [Orphan cleanup](./optimizer-configuration.md#orphan-cleanup).
+- Policy path: `system_iceberg_orphan_file_removal`
+ ([Iceberg orphan file removal policy](../iceberg-orphan-file-removal-policy.md)) 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`.
@@ -384,4 +387,7 @@ See [Remove Orphan Files](./optimizer-cli-reference.md#remove-orphan-files) and
- [CLI Reference](./optimizer-cli-reference.md) for every command and the built-in job templates
- [Troubleshooting](./optimizer-troubleshooting.md) when something above does not behave
- [Extension Guide](./optimizer-extension-guide.md) for custom strategies and providers
-- [Iceberg Compaction Policy](../iceberg-compaction-policy.md) for tuning the built-in strategy
+- [Iceberg Compaction Policy](../iceberg-compaction-policy.md)
+- [Iceberg Manifest Rewrite Policy](../iceberg-rewrite-manifests-policy.md)
+- [Iceberg Snapshot Expiration Policy](../iceberg-snapshot-expiration-policy.md)
+- [Iceberg Orphan File Removal Policy](../iceberg-orphan-file-removal-policy.md)
diff --git a/docs/table-maintenance-service/service.md b/docs/table-maintenance-service/service.md
index bc63106e45..c56b147bf7 100644
--- a/docs/table-maintenance-service/service.md
+++ b/docs/table-maintenance-service/service.md
@@ -80,7 +80,7 @@ After the trigger is due, list job runs and look for template `builtin-iceberg-m
Set the maintenance REST extension in `gravitino.conf`. Client authentication, Iceberg REST auth, and the job executor are in [Configuration](./optimizer-configuration.md#tms-cluster-static-client-auth).
| Configuration item | Description |
-|-------------------------------------------|------------------------------------------------------------------------------------------------------|
+| ----------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `gravitino.server.rest.extensionPackages` | Register the maintenance REST callbacks. Set to `org.apache.gravitino.maintenance.web.rest.feature`. |
A policy `updaterOptions.gravitino_uri` overrides the cluster callback URI. Every other `gravitinoAuth` key from the cluster wins over the same key in the policy.
@@ -88,16 +88,16 @@ A policy `updaterOptions.gravitino_uri` overrides the cluster callback URI. Ever
Scheduler pool sizes have these defaults:
| Configuration item | Default |
-|-------------------------------------------------|---------|
+| ----------------------------------------------- | ------- |
| `gravitino.maintenance.scheduler.expandThreads` | `4` |
| `gravitino.maintenance.scheduler.cronThreads` | `8` |
| `gravitino.maintenance.scheduler.commitThreads` | `4` |
When `gravitino.authorization.enable=true`, set a TMS submit identity:
-| Configuration item | Default | Description |
-|-------------------------------------------------|---------|----------------------------------------------------|
-| `gravitino.maintenance.jobSubmitter` | (none) | USER principal TMS uses to submit maintenance jobs |
+| Configuration item | Default | Description |
+| ------------------------------------ | ------- | -------------------------------------------------- |
+| `gravitino.maintenance.jobSubmitter` | (none) | USER principal TMS uses to submit maintenance jobs |
Create that user under every metalake that runs maintenance jobs. Grant the user metalake `RUN_JOB` and `USE_JOB_TEMPLATE` on the Iceberg maintenance job template so `runJob` can succeed; grant any further table or catalog privileges your maintenance Spark jobs need when they call back into Gravitino.
@@ -108,7 +108,7 @@ Create that user under every metalake that runs maintenance jobs. Grant the user
Three objects decide which tables run:
| Object | What to set |
-|-----------------|----------------------------------------------------------------------------------------------------------|
+| --------------- | -------------------------------------------------------------------------------------------------------- |
| Policy | `policyType`, `enabled`, and content fields `timeTrigger`, `commitTrigger`, and `minIntervalMs`. |
| Tag association | `POST /api/metalakes/{metalake}/tags/{tag}/policies/{policy}` with selector `ALL_VALUES` or `TAG_VALUE`. |
| Tag assignment | Assign the tag to the table, or to a catalog or schema ancestor. |
@@ -118,13 +118,17 @@ Three objects decide which tables run:
Built-in content types:
| `policyType` | Time trigger | Commit trigger |
-|--------------------------------------|--------------|----------------|
+| ------------------------------------ | ------------ | -------------- |
| `system_iceberg_compaction` | Yes | Yes |
| `system_iceberg_rewrite_manifests` | Yes | Yes |
| `system_iceberg_snapshot_expiration` | Yes | Yes |
| `system_iceberg_orphan_file_removal` | Yes | No |
-Field lists for each type are in [Iceberg compaction policy](../iceberg-compaction-policy.md), [Iceberg rewrite manifests policy](../iceberg-rewrite-manifests-policy.md), and [Manage policies](../manage-policies-in-gravitino.md).
+Field lists for each type are in [Iceberg compaction policy](../iceberg-compaction-policy.md),
+[Iceberg rewrite manifests policy](../iceberg-rewrite-manifests-policy.md),
+[Iceberg snapshot expiration policy](../iceberg-snapshot-expiration-policy.md),
+[Iceberg orphan file removal policy](../iceberg-orphan-file-removal-policy.md), and
+[Manage policies](../manage-policies-in-gravitino.md).
## Cron Path
@@ -147,11 +151,71 @@ On Kubernetes, leave `spark_master` empty. See [Built-in jobs](../k8s-job-execut
These endpoints are for the Spark job, not for operators. Schemas are in the [maintenance OpenAPI definition](../open-api/maintenance/maintenance.yaml). The commit path uses the same callbacks.
-| Callback | Method and path |
-|-----------------------------|-----------------------------------------------------------------------------|
-| Before-maintenance metrics | `POST /api/metalakes/{metalake}/maintenance/actions/{jobId}/metrics/before` |
-| Finish and release the slot | `POST /api/metalakes/{metalake}/maintenance/actions/{jobId}/finish` |
-| After-maintenance metrics | `POST /api/metalakes/{metalake}/maintenance/actions/{jobId}/metrics/after` |
+| Callback | Method and path |
+| --------------------------- | ------------------------------------------------------------------------------ |
+| Before-maintenance metrics | `POST /api/metalakes/{metalake}/maintenance/actions/{actionId}/metrics/before` |
+| After-maintenance metrics | `POST /api/metalakes/{metalake}/maintenance/actions/{actionId}/metrics/after` |
+| Finish and release the slot | `POST /api/metalakes/{metalake}/maintenance/actions/{actionId}/finish` |
+
+### Validation before and after metrics
+
+Cron and commit paths submit `builtin-iceberg-maintenance-task`, which posts before and after
+metrics through the callbacks above. The UI can show Before, After, and Change (After minus
+Before when both exist). Standalone procedure templates used by the CLI or optimizer
+(`builtin-iceberg-rewrite-data-files`, `builtin-iceberg-rewrite-manifests`,
+`builtin-iceberg-expire-snapshots`, `builtin-iceberg-remove-orphan-files`) do not report these
+metrics.
+
+#### Compaction (`system_iceberg_compaction`)
+
+Before and after inventory comes from Spark SQL on the Iceberg `files` metadata table.
+`custom-data-mse-ratio` is computed in the job as
+`custom-data-file-mse / minDataFileMse` (policy field). It is stored as a JSON number
+(`double`) for display; `minDataFileMse` itself is not stored as a metric.
+
+| Phase | Key | Source |
+| ---------------- | --------------------------- | ------------------------------------------- |
+| Before and After | `custom-data-file-mse` | File inventory (also drives `trigger-expr`) |
+| Before and After | `custom-delete-file-number` | File inventory |
+| Before and After | `custom-avg-file-size` | File inventory |
+| Before and After | `custom-total-file-size` | File inventory |
+| Before and After | `custom-file-number` | File inventory |
+| Before and After | `custom-small-file-number` | File inventory (files smaller than 32 MiB) |
+| Before and After | `custom-data-mse-ratio` | `custom-data-file-mse / minDataFileMse` |
+
+#### Manifest rewrite (`system_iceberg_rewrite_manifests`)
+
+Before and after inventory comes from the Iceberg Java API (`snapshot.allManifests`) for the
+resolved partition spec, not from Spark SQL.
+
+| Phase | Key | Source |
+| ------ | ---------------------------------- | ------------------------------------------------------------------------------- |
+| Before | `custom-manifest-number` | Manifest inventory for the resolved partition spec (also drives `trigger-expr`) |
+| Before | `custom-avg-manifest-size` | Manifest inventory for the resolved partition spec |
+| Before | `custom-manifest-spec-id` | Spec id when the table is partitioned (diagnostic only) |
+| Before | `custom-manifest-partition-spec` | Partition fields when the table is partitioned (diagnostic) |
+| After | `custom-manifest-number` | Manifest inventory re-collected after rewrite |
+| After | `custom-avg-manifest-size` | Manifest inventory re-collected after rewrite |
+| After | `custom-rewritten-manifest-number` | Count returned by the Iceberg `rewrite_manifests` procedure |
+| After | `custom-manifest-spec-id` | Spec id when the table is partitioned (diagnostic only) |
+| After | `custom-manifest-partition-spec` | Partition fields when the table is partitioned (diagnostic) |
+
+#### Snapshot expiration (`system_iceberg_snapshot_expiration`)
+
+| Phase | Key | Source |
+| ------ | -------------------------------- | ------------------------------------------------------------------------ |
+| Before | `custom-snapshot-number` | Snapshot count before expire |
+| After | `custom-snapshot-number` | Snapshot count after expire (re-counted, not before minus expired) |
+| After | `custom-expired-snapshot-number` | Snapshots that existed before expire and are gone afterward |
+| After | `custom-expired-file-size` | Bytes of content files that existed before expire and are gone afterward |
+
+#### Orphan file removal (`system_iceberg_orphan_file_removal`)
+
+| Phase | Key | Source |
+| ------ | ---------------------------- | -------------------------------------------- |
+| Before | — | Not collected |
+| After | `custom-removed-file-number` | Removed-file count from the procedure result |
+| After | `custom-removed-file-size` | Removed-file bytes measured with FileIO |
## Commit Trigger
@@ -178,4 +242,7 @@ Without the listener, time triggers still run. Commit-triggered maintenance does
- [Configuration](./optimizer-configuration.md) for client authentication, Iceberg REST auth, and the job executor
- [Table Maintenance Service](./optimizer.md) for the manual CLI workflow
- [CLI Reference](./optimizer-cli-reference.md) for every command and the built-in job templates
-- [Iceberg Compaction Policy](../iceberg-compaction-policy.md) for tuning the built-in compaction strategy
+- [Iceberg Compaction Policy](../iceberg-compaction-policy.md)
+- [Iceberg Manifest Rewrite Policy](../iceberg-rewrite-manifests-policy.md)
+- [Iceberg Snapshot Expiration Policy](../iceberg-snapshot-expiration-policy.md)
+- [Iceberg Orphan File Removal Policy](../iceberg-orphan-file-removal-policy.md)
diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.java
index 4c7d89a767..c664daff2d 100644
--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.java
+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.java
@@ -259,6 +259,7 @@ public class IcebergExpireSnapshotsJob implements BuiltInJob, IcebergMaintenance
PreExpireData beforeData = preExpireData == null ? after : preExpireData;
preExpireData = null;
Map<String, Object> metrics = new HashMap<>();
+ metrics.put(IcebergSnapshotExpirationContent.SNAPSHOT_NUMBER_METRIC, after.snapshotCount());
metrics.put(
IcebergSnapshotExpirationContent.EXPIRED_SNAPSHOT_NUMBER_METRIC,
snapshotsCleared(beforeData.snapshotIds(), after.snapshotIds()));
diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceJob.java
index 09d2acbff8..63edd9d75a 100644
--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceJob.java
+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceJob.java
@@ -21,6 +21,7 @@ package org.apache.gravitino.maintenance.jobs.iceberg;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -39,7 +40,9 @@ import org.apache.gravitino.maintenance.dto.requests.MaintenanceActionMetricsReq
import org.apache.gravitino.maintenance.jobs.BuiltInJob;
import org.apache.gravitino.maintenance.jobs.MaintenanceActionHttpClient;
import org.apache.gravitino.maintenance.optimizer.common.util.IcebergSparkConfigUtils;
+import org.apache.gravitino.policy.IcebergDataCompactionContent;
import org.apache.gravitino.policy.Policy;
+import org.apache.gravitino.policy.PolicyContents;
import org.apache.spark.sql.SparkSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -264,6 +267,7 @@ public class IcebergMaintenanceJob implements BuiltInJob {
task.policyId);
return;
}
+ before = withCompactionDataMseRatio(before, task.policyType, task.rules);
try {
client.reportBeforeMetrics(
task.actionId,
@@ -324,6 +328,7 @@ public class IcebergMaintenanceJob implements BuiltInJob {
task.policyId);
return;
}
+ after = withCompactionDataMseRatio(after, task.policyType, task.rules);
try {
client.reportAfterMetrics(
task.actionId,
@@ -443,6 +448,53 @@ public class IcebergMaintenanceJob implements BuiltInJob {
}
}
+ /**
+ * Adds compaction Fragmentation display metric {@code custom-data-mse-ratio} from measured MSE
+ * and policy {@code minDataFileMse}. No-op for other types. Does not persist the threshold
+ * itself.
+ */
+ static TableSnapshotMetrics withCompactionDataMseRatio(
+ TableSnapshotMetrics sample,
+ Policy.BuiltInType policyType,
+ @Nullable Map<String, Object> rules) {
+ if (policyType != Policy.BuiltInType.ICEBERG_COMPACTION
+ || sample == null
+ || sample.metricsJson() == null
+ || sample.metricsJson().trim().isEmpty()) {
+ return sample;
+ }
+ try {
+ Map<String, Object> metrics =
+ JsonUtils.anyFieldMapper()
+ .readValue(sample.metricsJson(), new TypeReference<Map<String, Object>>() {});
+ if (metrics == null) {
+ return sample;
+ }
+ Object mseRaw = metrics.get(IcebergDataCompactionContent.DATA_FILE_MSE_METRIC);
+ if (!(mseRaw instanceof Number)) {
+ return sample;
+ }
+ long threshold = compactionMinDataFileMse(rules);
+ double ratio = threshold > 0L ? ((Number) mseRaw).doubleValue() / (double) threshold : 0D;
+ metrics.put(IcebergDataCompactionContent.DATA_MSE_RATIO_METRIC, ratio);
+ return TableSnapshotMetrics.of(sample.snapshotId(), metrics);
+ } catch (IOException | RuntimeException e) {
+ LOG.warn(
+ "Failed to add {}: {}", IcebergDataCompactionContent.DATA_MSE_RATIO_METRIC, e.toString());
+ return sample;
+ }
+ }
+
+ static long compactionMinDataFileMse(@Nullable Map<String, Object> rules) {
+ Map<String, Object> effective =
+ rules == null || rules.isEmpty() ? PolicyContents.icebergDataCompaction().rules() : rules;
+ Object raw = effective.get(IcebergDataCompactionContent.MIN_DATA_FILE_MSE_KEY);
+ if (raw instanceof Number) {
+ return ((Number) raw).longValue();
+ }
+ return IcebergDataCompactionContent.DEFAULT_MIN_DATA_FILE_MSE;
+ }
+
private static long requirePositiveLong(@Nullable Object value, String field) {
if (value == null) {
throw new IllegalArgumentException(field + " is required");
diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java
index 18824da6ec..bc9036977a 100644
--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java
+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java
@@ -437,7 +437,7 @@ public class IcebergRewriteDataFilesJob implements BuiltInJob, IcebergMaintenanc
/**
* Collects compaction inventory metrics for TMS before/after reporting. Uses the same {@code
* files} metadata SQL as {@link IcebergUpdateStatsAndMetricsJob}. CLI entry points never call
- * this.
+ * this. Fragmentation ratio is added by {@link IcebergMaintenanceJob} from policy rules.
*/
@VisibleForTesting
static Map<String, Object> collectCompactionMetrics(
@@ -454,7 +454,7 @@ public class IcebergRewriteDataFilesJob implements BuiltInJob, IcebergMaintenanc
String sql = IcebergUpdateStatsAndMetricsJob.buildTableStatsSql(catalogName, tableIdentifier);
Row[] rows = (Row[]) spark.sql(sql).collect();
if (rows.length == 0) {
- return compactionMetrics(0D, 0L, 0D, 0L, 0L);
+ return compactionMetrics(0D, 0L, 0D, 0L, 0L, 0L);
}
Row row = rows[0];
return compactionMetrics(
@@ -462,7 +462,8 @@ public class IcebergRewriteDataFilesJob implements BuiltInJob, IcebergMaintenanc
numberAsLong(row, "delete-file-number"),
numberAsDouble(row, "avg-file-size"),
numberAsLong(row, "total-file-size"),
- numberAsLong(row, "file-number"));
+ numberAsLong(row, "file-number"),
+ numberAsLong(row, "small-file-number"));
}
@VisibleForTesting
@@ -470,6 +471,7 @@ public class IcebergRewriteDataFilesJob implements BuiltInJob, IcebergMaintenanc
double maxMse = 0D;
long deleteFiles = 0L;
long fileNumber = 0L;
+ long smallFileNumber = 0L;
long totalFileSize = 0L;
double weightedAvgNumerator = 0D;
for (Row row : rows) {
@@ -477,11 +479,13 @@ public class IcebergRewriteDataFilesJob implements BuiltInJob, IcebergMaintenanc
deleteFiles += numberAsLong(row, "delete-file-number");
long partitionFiles = numberAsLong(row, "file-number");
fileNumber += partitionFiles;
+ smallFileNumber += numberAsLong(row, "small-file-number");
totalFileSize += numberAsLong(row, "total-file-size");
weightedAvgNumerator += numberAsDouble(row, "avg-file-size") * partitionFiles;
}
double avgFileSize = fileNumber == 0L ? 0D : weightedAvgNumerator / fileNumber;
- return compactionMetrics(maxMse, deleteFiles, avgFileSize, totalFileSize, fileNumber);
+ return compactionMetrics(
+ maxMse, deleteFiles, avgFileSize, totalFileSize, fileNumber, smallFileNumber);
}
private static Map<String, Object> compactionMetrics(
@@ -489,13 +493,15 @@ public class IcebergRewriteDataFilesJob implements BuiltInJob, IcebergMaintenanc
long deleteFileNumber,
double avgFileSize,
long totalFileSize,
- long fileNumber) {
+ long fileNumber,
+ long smallFileNumber) {
Map<String, Object> metrics = new HashMap<>();
metrics.put(IcebergDataCompactionContent.DATA_FILE_MSE_METRIC, dataFileMse);
metrics.put(IcebergDataCompactionContent.DELETE_FILE_NUMBER_METRIC, deleteFileNumber);
metrics.put(IcebergDataCompactionContent.AVG_FILE_SIZE_METRIC, avgFileSize);
metrics.put(IcebergDataCompactionContent.TOTAL_FILE_SIZE_METRIC, totalFileSize);
metrics.put(IcebergDataCompactionContent.FILE_NUMBER_METRIC, fileNumber);
+ metrics.put(IcebergDataCompactionContent.SMALL_FILE_NUMBER_METRIC, smallFileNumber);
return metrics;
}
diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.java
index 0011877744..45bd503179 100644
--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.java
+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.java
@@ -313,7 +313,8 @@ public class IcebergRewriteManifestsJob implements BuiltInJob, IcebergMaintenanc
}
Table table = IcebergJobUtils.loadIcebergTable(spark, catalogName, tableIdentifier);
int resolvedSpec = Integer.parseInt(specId);
- Map<String, Object> metrics = new HashMap<>();
+ Map<String, Object> metrics =
+ new HashMap<>(collectManifestBeforeMetrics(spark, catalogName, tableIdentifier, specId));
metrics.put(IcebergRewriteManifestsContent.REWRITTEN_MANIFEST_NUMBER_METRIC, rewritten);
putPartitionSpecContext(metrics, table, resolvedSpec);
return TableSnapshotMetrics.of(
diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergMaintenanceJob.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergMaintenanceJob.java
index 4c4ff41620..da67b21d38 100644
--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergMaintenanceJob.java
+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergMaintenanceJob.java
@@ -22,8 +22,15 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import com.fasterxml.jackson.core.type.TypeReference;
+import java.util.Collections;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import org.apache.gravitino.job.SparkJobTemplate;
+import org.apache.gravitino.json.JsonUtils;
+import org.apache.gravitino.policy.IcebergDataCompactionContent;
+import org.apache.gravitino.policy.Policy;
import org.junit.jupiter.api.Test;
/** Unit tests for {@link IcebergMaintenanceJob} orchestration. */
@@ -68,4 +75,46 @@ public class TestIcebergMaintenanceJob {
+ "\"table_identifier\":\"db.t\"}}]"
}));
}
+
+ @Test
+ public void testCompactionMinDataFileMseFromRules() {
+ assertEquals(
+ IcebergDataCompactionContent.DEFAULT_MIN_DATA_FILE_MSE,
+ IcebergMaintenanceJob.compactionMinDataFileMse(null));
+ assertEquals(
+ IcebergDataCompactionContent.DEFAULT_MIN_DATA_FILE_MSE,
+ IcebergMaintenanceJob.compactionMinDataFileMse(Collections.emptyMap()));
+ assertEquals(
+ 10L,
+ IcebergMaintenanceJob.compactionMinDataFileMse(
+ Collections.singletonMap(IcebergDataCompactionContent.MIN_DATA_FILE_MSE_KEY, 10)));
+ }
+
+ @Test
+ public void testWithCompactionDataMseRatioEnrichesBeforeAndAfterShape() throws Exception {
+ Map<String, Object> inventory = new HashMap<>();
+ inventory.put(IcebergDataCompactionContent.DATA_FILE_MSE_METRIC, 20D);
+ inventory.put(IcebergDataCompactionContent.FILE_NUMBER_METRIC, 3L);
+ TableSnapshotMetrics sample = TableSnapshotMetrics.of(42L, inventory);
+
+ TableSnapshotMetrics enriched =
+ IcebergMaintenanceJob.withCompactionDataMseRatio(
+ sample,
+ Policy.BuiltInType.ICEBERG_COMPACTION,
+ Collections.singletonMap(IcebergDataCompactionContent.MIN_DATA_FILE_MSE_KEY, 10));
+
+ Map<String, Object> metrics =
+ JsonUtils.anyFieldMapper()
+ .readValue(enriched.metricsJson(), new TypeReference<Map<String, Object>>() {});
+ assertEquals(42L, enriched.snapshotId());
+ assertEquals(
+ 2D,
+ ((Number) metrics.get(IcebergDataCompactionContent.DATA_MSE_RATIO_METRIC)).doubleValue());
+ assertFalse(metrics.containsKey(IcebergDataCompactionContent.MIN_DATA_FILE_MSE_KEY));
+
+ TableSnapshotMetrics skipped =
+ IcebergMaintenanceJob.withCompactionDataMseRatio(
+ sample, Policy.BuiltInType.ICEBERG_SNAPSHOT_EXPIRATION, null);
+ assertEquals(sample.metricsJson(), skipped.metricsJson());
+ }
}
diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.java
index 2d540b492f..afadea3f24 100644
--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.java
+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteDataFilesJob.java
@@ -30,6 +30,9 @@ import org.apache.gravitino.job.JobTemplateProvider;
import org.apache.gravitino.job.SparkJobTemplate;
import org.apache.gravitino.policy.IcebergDataCompactionContent;
import org.apache.spark.sql.Row;
+import org.apache.spark.sql.catalyst.expressions.GenericRowWithSchema;
+import org.apache.spark.sql.types.DataTypes;
+import org.apache.spark.sql.types.StructType;
import org.junit.jupiter.api.Test;
public class TestIcebergRewriteDataFilesJob {
@@ -544,7 +547,7 @@ public class TestIcebergRewriteDataFilesJob {
public void testCompactionMetricsSchemaForTms() {
Map<String, Object> metrics =
IcebergRewriteDataFilesJob.aggregatePartitionCompactionMetrics(new Row[0]);
- assertEquals(5, metrics.size());
+ assertEquals(6, metrics.size());
assertEquals(
0D,
((Number) metrics.get(IcebergDataCompactionContent.DATA_FILE_MSE_METRIC)).doubleValue());
@@ -559,5 +562,48 @@ public class TestIcebergRewriteDataFilesJob {
((Number) metrics.get(IcebergDataCompactionContent.TOTAL_FILE_SIZE_METRIC)).longValue());
assertEquals(
0L, ((Number) metrics.get(IcebergDataCompactionContent.FILE_NUMBER_METRIC)).longValue());
+ assertEquals(
+ 0L,
+ ((Number) metrics.get(IcebergDataCompactionContent.SMALL_FILE_NUMBER_METRIC)).longValue());
+ assertFalse(metrics.containsKey(IcebergDataCompactionContent.DATA_MSE_RATIO_METRIC));
+ }
+
+ @Test
+ public void testAggregatePartitionCompactionMetricsSumsSmallFiles() {
+ StructType schema =
+ new StructType()
+ .add("data-file-mse", DataTypes.DoubleType)
+ .add("delete-file-number", DataTypes.LongType)
+ .add("avg-file-size", DataTypes.DoubleType)
+ .add("total-file-size", DataTypes.LongType)
+ .add("file-number", DataTypes.LongType)
+ .add("small-file-number", DataTypes.LongType);
+ Row[] partitions =
+ new Row[] {
+ new GenericRowWithSchema(new Object[] {10.0D, 1L, 100.0D, 200L, 2L, 2L}, schema),
+ new GenericRowWithSchema(new Object[] {30.0D, 3L, 50.0D, 150L, 3L, 1L}, schema)
+ };
+
+ Map<String, Object> metrics =
+ IcebergRewriteDataFilesJob.aggregatePartitionCompactionMetrics(partitions);
+
+ assertEquals(
+ 30.0D,
+ ((Number) metrics.get(IcebergDataCompactionContent.DATA_FILE_MSE_METRIC)).doubleValue());
+ assertEquals(
+ 4L,
+ ((Number) metrics.get(IcebergDataCompactionContent.DELETE_FILE_NUMBER_METRIC)).longValue());
+ assertEquals(
+ 70.0D,
+ ((Number) metrics.get(IcebergDataCompactionContent.AVG_FILE_SIZE_METRIC)).doubleValue());
+ assertEquals(
+ 350L,
+ ((Number) metrics.get(IcebergDataCompactionContent.TOTAL_FILE_SIZE_METRIC)).longValue());
+ assertEquals(
+ 5L, ((Number) metrics.get(IcebergDataCompactionContent.FILE_NUMBER_METRIC)).longValue());
+ assertEquals(
+ 3L,
+ ((Number) metrics.get(IcebergDataCompactionContent.SMALL_FILE_NUMBER_METRIC)).longValue());
+ assertFalse(metrics.containsKey(IcebergDataCompactionContent.DATA_MSE_RATIO_METRIC));
}
}
diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJobWithSpark.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJobWithSpark.java
index cc3cb02547..5a931342c0 100644
--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJobWithSpark.java
+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJobWithSpark.java
@@ -22,6 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import com.fasterxml.jackson.core.type.TypeReference;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
@@ -37,6 +38,7 @@ import org.apache.gravitino.dto.AuditDTO;
import org.apache.gravitino.dto.policy.PolicyDTO;
import org.apache.gravitino.dto.rel.TableDTO;
import org.apache.gravitino.dto.util.DTOConverters;
+import org.apache.gravitino.json.JsonUtils;
import org.apache.gravitino.maintenance.jobs.TemplateArguments;
import org.apache.gravitino.maintenance.optimizer.api.common.StatisticEntry;
import org.apache.gravitino.maintenance.optimizer.api.recommender.StrategyHandlerContext;
@@ -161,6 +163,48 @@ public class TestIcebergRewriteManifestsJobWithSpark {
.contains(IcebergRewriteManifestsContent.MANIFEST_PARTITION_SPEC_METRIC));
}
+ /**
+ * TMS S1 after rewrite re-collects inventory for the resolved spec and merges the procedure
+ * rewritten count so Validation Before/After/Change can use the same inventory keys.
+ */
+ @Test
+ public void testAfterMetricsIncludeInventoryAndRewritten() throws Exception {
+ assertEquals(3, manifests(1).size());
+ Map<String, String> args = new HashMap<>();
+ IcebergRewriteManifestsJob job = new IcebergRewriteManifestsJob();
+ TableSnapshotMetrics before =
+ job.collectBeforeMetrics(spark, "manifest_catalog", "db.events", args);
+ Map<String, Object> beforeMetrics =
+ JsonUtils.anyFieldMapper()
+ .readValue(before.metricsJson(), new TypeReference<Map<String, Object>>() {});
+ assertEquals(
+ 3L,
+ ((Number) beforeMetrics.get(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC))
+ .longValue());
+
+ TableSnapshotMetrics after =
+ job.executeAndCollectAfter(spark, "manifest_catalog", "db.events", args, before);
+ Map<String, Object> afterMetrics =
+ JsonUtils.anyFieldMapper()
+ .readValue(after.metricsJson(), new TypeReference<Map<String, Object>>() {});
+
+ assertEquals(1, manifests(1).size());
+ assertEquals(
+ 1L,
+ ((Number) afterMetrics.get(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC))
+ .longValue());
+ assertTrue(afterMetrics.containsKey(IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC));
+ assertEquals(
+ 3L,
+ ((Number) afterMetrics.get(IcebergRewriteManifestsContent.REWRITTEN_MANIFEST_NUMBER_METRIC))
+ .longValue());
+ assertEquals(1, afterMetrics.get(IcebergRewriteManifestsContent.MANIFEST_SPEC_ID_METRIC));
+ assertEquals(
+ "hour(event_time)",
+ afterMetrics.get(IcebergRewriteManifestsContent.MANIFEST_PARTITION_SPEC_METRIC));
+ assertEquals(currentSnapshot(), after.snapshotId());
+ }
+
/** An explicit old spec is rewritten without migrating it or changing the current spec. */
@Test
public void testExplicitOldSpecWithCaching() {