World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#14358] improvement(tms): Link before/after metrics by metrics_id and reclaim soft slots with a new action_id (#14357)
MaSai2e348a9d32c5
diff --git a/docs/open-api/maintenance/maintenance.yaml b/docs/open-api/maintenance/maintenance.yamlindex 7ac6375731..8ada6d5d59 100644--- a/docs/open-api/maintenance/maintenance.yaml+++ b/docs/open-api/maintenance/maintenance.yaml@@ -19,10 +19,10 @@paths:- /metalakes/{metalake}/maintenance/actions/{jobId}/metrics/before:+ /metalakes/{metalake}/maintenance/actions/{actionId}/metrics/before:parameters:- $ref: "../openapi.yaml#/components/parameters/metalake"- - $ref: "#/components/parameters/jobId"+ - $ref: "#/components/parameters/actionId"- $ref: "#/components/parameters/finish"post:tags:@@ -30,11 +30,11 @@ paths:summary: Report TMS before-maintenance (S0) snapshot metricsoperationId: reportMaintenanceActionBeforeMetricsdescription: |- Spark callback for an in-flight maintenance action at S0: persists snapshot metrics and- records `before_snapshot_id`. `tableId` and `policyId` select which bound action row when- one Spark job covers multiple tables and/or policies. Optional query `finish=true` closes- that table/policy soft slot (for example on snapshot drift / skip). Continue / stop stays- in the job.+ Spark callback for an in-flight maintenance action at S0: inserts a+ `table_snapshot_metrics` row and records `before_metrics_id` on the action keyed by+ `actionId` (injected at submit). `tableId` and `policyId` must match the soft-slot row.+ Optional query `finish=true` closes that soft slot (for example on snapshot drift / skip).+ Continue / stop stays in the job. Soft-slot release without metrics uses POST .../finish.requestBody:required: truecontent:@@ -58,20 +58,21 @@ paths:"5xx":$ref: "../openapi.yaml#/components/responses/ServerErrorResponse"- /metalakes/{metalake}/maintenance/actions/{jobId}/finish:+ /metalakes/{metalake}/maintenance/actions/{actionId}/finish:parameters:- $ref: "../openapi.yaml#/components/parameters/metalake"- - $ref: "#/components/parameters/jobId"+ - $ref: "#/components/parameters/actionId"post:tags:- maintenancesummary: Finish TMS maintenance action soft slot without metricsoperationId: finishMaintenanceActiondescription: |- Closes the soft slot for one bound table/policy without writing snapshot metrics.- Use when the maintenance type does not sample metrics, or when metrics were already- reported and only occupancy release remains. `tableId` and `policyId` select the action- row. Optional `afterSnapshotId` sets `after_snapshot_id` when known.+ Closes the soft slot for one bound action (`finished_at` set) without writing snapshot+ metrics. Use when the maintenance type does not sample metrics, or when metrics were+ already reported and only occupancy release remains. `tableId` and `policyId` must match+ the soft-slot row addressed by `actionId`. Iceberg snapshot ids live on the metrics rows,+ not on this request.requestBody:required: truecontent:@@ -95,10 +96,10 @@ paths:"5xx":$ref: "../openapi.yaml#/components/responses/ServerErrorResponse"- /metalakes/{metalake}/maintenance/actions/{jobId}/metrics/after:+ /metalakes/{metalake}/maintenance/actions/{actionId}/metrics/after:parameters:- $ref: "../openapi.yaml#/components/parameters/metalake"- - $ref: "#/components/parameters/jobId"+ - $ref: "#/components/parameters/actionId"- $ref: "#/components/parameters/finish"post:tags:@@ -106,10 +107,11 @@ paths:summary: Report TMS after-maintenance (S1) snapshot metricsoperationId: reportMaintenanceActionAfterMetricsdescription: |- Spark callback for an in-flight maintenance action at S1: persists snapshot metrics.- `tableId` and `policyId` select which bound action row when one Spark job covers multiple- tables and/or policies. Optional query `finish=true` closes that table/policy soft slot- and sets `after_snapshot_id` to `snapshotId`. Continue / stop stays in the job.+ Spark callback for an in-flight maintenance action at S1: inserts a+ `table_snapshot_metrics` row and records `after_metrics_id` on the action keyed by+ `actionId`. `tableId` and `policyId` must match the soft-slot row. Optional query+ `finish=true` closes that soft slot. Continue / stop stays in the job. Soft-slot release+ without metrics uses POST .../finish.requestBody:required: truecontent:@@ -136,10 +138,12 @@ paths:components:parameters:- jobId:- name: jobId+ actionId:+ name: actionIdin: path- description: Gravitino job run id (numeric)+ description: |+ Soft-slot id from `table_maintenance_action.action_id`, injected into the Spark job as+ `action_ids` at submit time.required: trueschema:type: integer@@ -148,10 +152,8 @@ components:name: finishin: querydescription: |- When true, close the soft slot for this job/table/policy after storing metrics.- Before: typically on drift/skip (after_snapshot_id left null). After: typically after- successful maintenance (after_snapshot_id = snapshotId). Prefer POST .../finish when no- metrics are written.+ When true, close the soft slot for this action after storing metrics (sets `finished_at`).+ Prefer POST .../finish when no metrics are written.required: falseschema:type: boolean@@ -169,18 +171,18 @@ components:tableId:type: integerformat: int64- description: Table entity id bound to this job+ description: Table entity id that must match the soft-slot row for actionIdpolicyId:type: integerformat: int64- description: Policy entity id bound to this job (required when one job covers multiple policies)+ description: Policy entity id that must match the soft-slot row for actionIdsnapshotId:type: integerformat: int64- description: Iceberg snapshot id the metrics were collected for+ description: Iceberg snapshot id stored on the new table_snapshot_metrics rowmetricsJson:type: string- description: Serialized metrics JSON for table_snapshot_metrics+ description: Serialized metrics JSON for table_snapshot_metrics.metrics_valueMaintenanceActionFinishRequest:type: objectrequired:@@ -190,16 +192,11 @@ components:tableId:type: integerformat: int64- description: Table entity id bound to this job+ description: Table entity id that must match the soft-slot row for actionIdpolicyId:type: integerformat: int64- description: Policy entity id bound to this job- afterSnapshotId:- type: integer- format: int64- nullable: true- description: Optional terminal snapshot id stored as after_snapshot_id+ description: Policy entity id that must match the soft-slot row for actionIdexamples:MaintenanceActionBeforeMetricsRequest:@@ -219,6 +216,5 @@ components:MaintenanceActionFinishRequest:value: {"tableId": 10,- "policyId": 20,- "afterSnapshotId": null+ "policyId": 20}diff --git a/docs/open-api/maintenance/openapi.yaml b/docs/open-api/maintenance/openapi.yamlindex fa137d497e..24edfdbc2a 100644--- a/docs/open-api/maintenance/openapi.yaml+++ b/docs/open-api/maintenance/openapi.yaml@@ -27,7 +27,8 @@ info:OpenAPI specification for table-maintenance metrics callbacks exposed by the TMS plugin.Enable them by registering `org.apache.gravitino.maintenance.web.rest.feature` in`gravitino.server.rest.extensionPackages`. Callers authenticate with the server- authenticators and must be the metalake owner or hold `RUN_JOB`.+ authenticators and must be the metalake owner or hold `RUN_JOB`. Paths are keyed by+ soft-slot `actionId` (not the Gravitino job run id).servers:- url: "{scheme}://{host}:{port}/{basePath}"@@ -52,12 +53,12 @@ security:- KerberosAuth: []paths:- /metalakes/{metalake}/maintenance/actions/{jobId}/metrics/before:- $ref: "./maintenance.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1maintenance~1actions~1%7BjobId%7D~1metrics~1before"- /metalakes/{metalake}/maintenance/actions/{jobId}/metrics/after:- $ref: "./maintenance.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1maintenance~1actions~1%7BjobId%7D~1metrics~1after"- /metalakes/{metalake}/maintenance/actions/{jobId}/finish:- $ref: "./maintenance.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1maintenance~1actions~1%7BjobId%7D~1finish"+ /metalakes/{metalake}/maintenance/actions/{actionId}/metrics/before:+ $ref: "./maintenance.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1maintenance~1actions~1%7BactionId%7D~1metrics~1before"+ /metalakes/{metalake}/maintenance/actions/{actionId}/metrics/after:+ $ref: "./maintenance.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1maintenance~1actions~1%7BactionId%7D~1metrics~1after"+ /metalakes/{metalake}/maintenance/actions/{actionId}/finish:+ $ref: "./maintenance.yaml#/paths/~1metalakes~1%7Bmetalake%7D~1maintenance~1actions~1%7BactionId%7D~1finish"components:securitySchemes:diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/MaintenanceActionHttpClient.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/MaintenanceActionHttpClient.javaindex b98cea2a2d..401f006fbf 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/MaintenanceActionHttpClient.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/MaintenanceActionHttpClient.java@@ -18,6 +18,7 @@*/package org.apache.gravitino.maintenance.jobs;+import com.fasterxml.jackson.databind.DeserializationFeature;import com.fasterxml.jackson.databind.ObjectMapper;import com.google.common.annotations.VisibleForTesting;import com.google.common.base.Preconditions;@@ -101,38 +102,43 @@ public final class MaintenanceActionHttpClient implements AutoCloseable {Preconditions.checkArgument(StringUtils.isNotBlank(metalake), "updater_options must contain metalake");GravitinoAuthSettings auth = GravitinoAuthSettings.from(new OptimizerConfig(properties));- return new MaintenanceActionHttpClient(- JsonUtils.objectMapper(), uri.trim(), metalake.trim(), auth);+ // Keycloak (and other IdPs) return extra token fields such as refresh_expires_in; match+ // client-java ObjectMapperProvider so OAuth callbacks do not fail on unknown properties.+ ObjectMapper mapper =+ JsonUtils.objectMapper()+ .copy()+ .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);+ return new MaintenanceActionHttpClient(mapper, uri.trim(), metalake.trim(), auth);}/*** Reports S0 (before-maintenance) snapshot metrics.*- * @param jobId Gravitino job run id+ * @param actionId maintenance action id* @param request metrics payload*/- public void reportBeforeMetrics(long jobId, MaintenanceActionMetricsRequest request) {- postJson(jobId, "metrics/before", request);+ public void reportBeforeMetrics(long actionId, MaintenanceActionMetricsRequest request) {+ postJson(actionId, "metrics/before", request);}/*** Reports S1 (after-maintenance) snapshot metrics.*- * @param jobId Gravitino job run id+ * @param actionId maintenance action id* @param request metrics payload*/- public void reportAfterMetrics(long jobId, MaintenanceActionMetricsRequest request) {- postJson(jobId, "metrics/after", request);+ public void reportAfterMetrics(long actionId, MaintenanceActionMetricsRequest request) {+ postJson(actionId, "metrics/after", request);}/*** Closes the soft slot for one table without writing metrics.*- * @param jobId Gravitino job run id+ * @param actionId maintenance action id* @param request finish payload*/- public void finish(long jobId, MaintenanceActionFinishRequest request) {- postJson(jobId, "finish", request);+ public void finish(long actionId, MaintenanceActionFinishRequest request) {+ postJson(actionId, "finish", request);}@Override@@ -141,13 +147,13 @@ public final class MaintenanceActionHttpClient implements AutoCloseable {bearerExpiresAtMillis = 0L;}- private void postJson(long jobId, String action, RESTRequest request) {+ private void postJson(long actionId, String action, RESTRequest request) {Preconditions.checkArgument(request != null, "request must not be null");request.validate();String path =String.format("/api/metalakes/%s/maintenance/actions/%d/%s",- RESTUtils.encodeString(metalakeName), jobId, action);+ RESTUtils.encodeString(metalakeName), actionId, action);try {HttpResult result =post(baseUri + path, JSON, mapper.writeValueAsString(request), authorizationHeader());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.javaindex 1a5419e70b..5844312e8c 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,8 +21,6 @@ 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.ImmutableList;-import java.nio.file.Path;-import java.nio.file.Paths;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;@@ -34,7 +32,6 @@ import java.util.Map;import java.util.Set;import java.util.stream.Collectors;import javax.annotation.Nullable;-import org.apache.gravitino.job.JobHandle;import org.apache.gravitino.job.JobTemplateProvider;import org.apache.gravitino.job.SparkJobTemplate;import org.apache.gravitino.json.JsonUtils;@@ -64,22 +61,16 @@ import org.slf4j.LoggerFactory;* (snapshot drift and trigger-expr recommend) is decided in-job after S0 sample. Soft slots are* closed via the finish callback in {@code finally}.*- * <p>TMS-specific {@code jobConf} keys: {@code maintenance_types}, {@code policy_ids} (parallel- * comma-separated policy entity ids), {@code tables} (JSON targets with system-filled {@code- * table_id}), {@code updater_options}, {@code rules}. Shared procedure / Spark keys match other- * Iceberg built-ins. The Gravitino job id is read from the local executor staging directory ({@code- * job-} plus the numeric id), or from {@code GRAVITINO_JOB_ID}.+ * <p>TMS-specific {@code jobConf} keys: {@code maintenance_types}, {@code policy_ids} and {@code+ * action_ids} (parallel comma-separated ids), {@code tables} (JSON targets with system-filled+ * {@code table_id}), {@code updater_options}, {@code rules}. Shared procedure / Spark keys match+ * other Iceberg built-ins. Soft-slot callbacks use injected {@code action_ids}, not the Gravitino+ * job run id.*/public class IcebergMaintenanceJob implements BuiltInJob {private static final Logger LOG = LoggerFactory.getLogger(IcebergMaintenanceJob.class);- /**- * Optional job-id override. Not injected by {@code JobManager}; the local executor staging- * directory is the default source.- */- private static final String GRAVITINO_JOB_ID_ENV = "GRAVITINO_JOB_ID";-/** Built-in template name submitted by TMS cron / commit. */public static final String NAME =JobTemplateProvider.BUILTIN_NAME_PREFIX + "iceberg-maintenance-task";@@ -104,6 +95,12 @@ public class IcebergMaintenanceJob implements BuiltInJob {*/public static final String POLICY_IDS_KEY = "policy_ids";+ /**+ * JobConf key for {@code table_maintenance_action.action_id} values parallel to {@link+ * #POLICY_IDS_KEY} (comma-separated). Injected by TMS submit after soft-slot acquire.+ */+ public static final String ACTION_IDS_KEY = "action_ids";+private static final String VERSION = "v1";/** Supported {@code maintenance_types} wire values. */@@ -186,13 +183,13 @@ public class IcebergMaintenanceJob implements BuiltInJob {List<MaintenanceType> types;List<Long> policyIds;- long jobId;+ List<Long> actionIds;List<TableTarget> tables;Map<String, String> updaterOptions;try {types = parseMaintenanceTypes(argMap.get("maintenance-types"));policyIds = parsePolicyIds(argMap.get("policy-ids"), types.size());- jobId = resolveGravitinoJobId();+ actionIds = parseActionIds(argMap.get("action-ids"), types.size());tables = parseTables(IcebergJobUtils.nullIfUnresolvedPlaceholder(argMap.get("tables")));updaterOptions =parseUpdaterOptions(@@ -217,26 +214,35 @@ public class IcebergMaintenanceJob implements BuiltInJob {IcebergJobUtils.requireIcebergSparkRuntimeOrExit(spark);try (MaintenanceActionHttpClient client =MaintenanceActionHttpClient.fromUpdaterOptions(updaterOptions)) {- // Soft slots are per (tableId, policyId) and already bound to jobId; close every slot even- // when a procedure fails or we never reach a later type/table.+ // Soft slots are per action_id; close every slot even when a procedure fails or we never+ // reach a later type/table.Set<String> finishedSlots = new HashSet<>();try {for (TableTarget table : tables) {for (int i = 0; i < types.size(); i++) {MaintenanceType type = types.get(i);long policyId = policyIds.get(i);- Long afterSnapshotId = null;+ long actionId = actionIds.get(i);try {SnapshotSample s0 =sampleSnapshot(spark, table.catalogName, table.tableIdentifier, type);- reportMetricsQuietly(client, jobId, table.tableId, policyId, s0, /*after=*/ false);+ if (!reportBeforeMetrics(client, actionId, table.tableId, policyId, s0)) {+ LOG.info(+ "TMS type {} stopped for action_id {} table {} policy {}:"+ + " before-metrics claim failed (abandoned or unbound)",+ type.wireName,+ actionId,+ table.tableId,+ policyId);+ continue;+ }if (s0.snapshotId != s0.headSnapshotId) {LOG.info(- "TMS type {} skipped for job {} table {} policy {} due to snapshot drift"+ "TMS type {} skipped for action_id {} table {} policy {} due to snapshot drift"+ " (s0={} head={})",type.wireName,- jobId,+ actionId,table.tableId,policyId,s0.snapshotId,@@ -246,10 +252,10 @@ public class IcebergMaintenanceJob implements BuiltInJob {if (!MaintenanceTriggerGate.shouldMaintain(type, argMap, s0.metricsJson)) {LOG.info(- "TMS type {} skipped for job {} table {} policy {} due to in-Spark recommend"- + " skip",+ "TMS type {} skipped for action_id {} table {} policy {} due to in-Spark"+ + " recommend skip",type.wireName,- jobId,+ actionId,table.tableId,policyId);continue;@@ -258,23 +264,25 @@ public class IcebergMaintenanceJob implements BuiltInJob {runProcedure(spark, type, table.catalogName, table.tableIdentifier, argMap);SnapshotSample s1 =sampleSnapshot(spark, table.catalogName, table.tableIdentifier, type);- afterSnapshotId = s1.snapshotId;- reportMetricsQuietly(client, jobId, table.tableId, policyId, s1, /*after=*/ true);+ reportMetricsQuietly(+ client, actionId, table.tableId, policyId, s1, /*after=*/ true);} finally {- finishQuietly(client, jobId, table.tableId, policyId, afterSnapshotId);+ finishQuietly(client, actionId, table.tableId, policyId);finishedSlots.add(slotKey(table.tableId, policyId));}}}return 0;} catch (Exception e) {- LOG.error("TMS Iceberg maintenance failed for job {}", jobId, e);+ LOG.error("TMS Iceberg maintenance failed for action_ids {}", actionIds, e);return 1;} finally {for (TableTarget table : tables) {- for (long policyId : policyIds) {+ for (int i = 0; i < policyIds.size(); i++) {+ long policyId = policyIds.get(i);+ long actionId = actionIds.get(i);if (!finishedSlots.contains(slotKey(table.tableId, policyId))) {- finishQuietly(client, jobId, table.tableId, policyId, /*afterSnapshotId=*/ null);+ finishQuietly(client, actionId, table.tableId, policyId);}}}@@ -555,27 +563,53 @@ public class IcebergMaintenanceJob implements BuiltInJob {}private static void finishQuietly(+ MaintenanceActionHttpClient client, long actionId, long tableId, long policyId) {+ try {+ client.finish(actionId, new MaintenanceActionFinishRequest(tableId, policyId));+ } catch (Exception e) {+ LOG.warn(+ "Best-effort TMS finish failed for action_id {} table {} policy {}",+ actionId,+ tableId,+ policyId,+ e);+ }+ }++ /**+ * S0 metrics are a hard gate: failure means the soft slot is abandoned/unbound, so maintenance+ * must not run.+ */+ private static boolean reportBeforeMetrics(MaintenanceActionHttpClient client,- long jobId,+ long actionId,long tableId,long policyId,- @Nullable Long afterSnapshotId) {+ SnapshotSample sample) {+ if (sample == null || sample.metricsJson == null || sample.metricsJson.trim().isEmpty()) {+ return false;+ }try {- client.finish(jobId, new MaintenanceActionFinishRequest(tableId, policyId, afterSnapshotId));+ client.reportBeforeMetrics(+ actionId,+ new MaintenanceActionMetricsRequest(+ tableId, policyId, sample.snapshotId, sample.metricsJson));+ return true;} catch (Exception e) {LOG.warn(- "Best-effort TMS finish failed for job {} table {} policy {} afterSnapshotId={}",- jobId,+ "TMS before metrics failed for action_id {} table {} policy {} snapshot {}: {}",+ actionId,tableId,policyId,- afterSnapshotId,- e);+ sample.snapshotId,+ e.toString());+ return false;}}private static void reportMetricsQuietly(MaintenanceActionHttpClient client,- long jobId,+ long actionId,long tableId,long policyId,SnapshotSample sample,@@ -588,15 +622,15 @@ public class IcebergMaintenanceJob implements BuiltInJob {new MaintenanceActionMetricsRequest(tableId, policyId, sample.snapshotId, sample.metricsJson);if (after) {- client.reportAfterMetrics(jobId, request);+ client.reportAfterMetrics(actionId, request);} else {- client.reportBeforeMetrics(jobId, request);+ client.reportBeforeMetrics(actionId, request);}} catch (Exception e) {LOG.warn(- "Best-effort TMS {} metrics report failed for job {} table {} policy {} snapshot {}",+ "Best-effort TMS {} metrics report failed for action_id {} table {} policy {} snapshot {}",after ? "after" : "before",- jobId,+ actionId,tableId,policyId,sample.snapshotId,@@ -617,50 +651,34 @@ public class IcebergMaintenanceJob implements BuiltInJob {}}- /**- * Prefers {@code GRAVITINO_JOB_ID}. Falls back to parsing a {@code job-} plus numeric id segment- * from {@code user.dir} (local executor staging directory).- */- private static long resolveGravitinoJobId() {- String envValue = System.getenv(GRAVITINO_JOB_ID_ENV);- if (envValue != null && !envValue.trim().isEmpty()) {+ private static List<Long> parseActionIds(@Nullable String raw, int expectedCount) {+ if (raw == null || raw.trim().isEmpty()) {+ throw new IllegalArgumentException("action_ids is required");+ }+ String[] parts = raw.split(",");+ List<Long> ids = new ArrayList<>(parts.length);+ for (String part : parts) {+ String trimmed = part.trim();+ if (trimmed.isEmpty()) {+ continue;+ }try {- long parsed = Long.parseLong(envValue.trim());+ long parsed = Long.parseLong(trimmed);if (parsed <= 0) {- throw new IllegalStateException(- GRAVITINO_JOB_ID_ENV + " must be a positive long: " + envValue);+ throw new IllegalArgumentException("action_ids must be positive longs: " + trimmed);}- return parsed;+ ids.add(parsed);} catch (NumberFormatException e) {- throw new IllegalStateException(GRAVITINO_JOB_ID_ENV + " must be a long: " + envValue, e);+ throw new IllegalArgumentException("action_ids must be longs: " + trimmed, e);}}- String userDir = System.getProperty("user.dir");- if (userDir != null && !userDir.trim().isEmpty()) {- Path dir = Paths.get(userDir).toAbsolutePath().normalize();- for (Path current = dir; current != null; current = current.getParent()) {- Path fileName = current.getFileName();- if (fileName == null) {- continue;- }- String name = fileName.toString();- if (!name.startsWith(JobHandle.JOB_ID_PREFIX)) {- continue;- }- try {- long parsed = Long.parseLong(name.substring(JobHandle.JOB_ID_PREFIX.length()));- if (parsed > 0) {- return parsed;- }- } catch (NumberFormatException ignored) {- // Keep walking parents; staging dirs use job-<numericId>.- }- }+ if (ids.size() != expectedCount) {+ throw new IllegalArgumentException(+ String.format(+ "action_ids count %s must match maintenance_types count %s",+ ids.size(), expectedCount));}- throw new IllegalStateException(- "Cannot resolve Gravitino job id: set "- + GRAVITINO_JOB_ID_ENV- + " or run under a job-<id> staging directory");+ return ids;}private static void putIfPresent(Map<String, String> target, String key, @Nullable String raw) {@@ -682,6 +700,8 @@ public class IcebergMaintenanceJob implements BuiltInJob {"{{maintenance_types}}","--policy-ids","{{policy_ids}}",+ "--action-ids",+ "{{action_ids}}","--tables","{{tables}}","--updater-options",diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/TestBuiltInJobTemplateProvider.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/TestBuiltInJobTemplateProvider.javaindex c89e3ef4a9..cf590b32d6 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/TestBuiltInJobTemplateProvider.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/TestBuiltInJobTemplateProvider.java@@ -91,7 +91,8 @@ public class TestBuiltInJobTemplateProvider {// A built-in template must let a caller run it with the catalog and the table alone, so every// other parameter needs a default value. Catalog and updater connections have no defaults that// fit every deployment, and an empty where clause rewrites a whole table, so those stay- // required.+ // required. The TMS maintenance task also requires action_ids: the scheduler injects the+ // soft-slot ids and the placeholder has no default.Map<String, Set<String>> expected = new HashMap<>();Set<String> icebergCatalog =ImmutableSet.of(@@ -115,7 +116,7 @@ public class TestBuiltInJobTemplateProvider {"builtin-iceberg-maintenance-task",ImmutableSet.<String>builder().add("catalog_name", "catalog_type", "catalog_uri", "warehouse_location")- .add("maintenance_types", "policy_ids", "tables")+ .add("maintenance_types", "policy_ids", "tables", "action_ids").build());for (JobTemplate template : new BuiltInJobTemplateProvider().jobTemplates()) {diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/TestMaintenanceActionHttpClient.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/TestMaintenanceActionHttpClient.javaindex c7fdf4d8ed..e66680dbc9 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/TestMaintenanceActionHttpClient.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/TestMaintenanceActionHttpClient.java@@ -88,7 +88,7 @@ public class TestMaintenanceActionHttpClient {assertEquals("/api/metalakes/demo/maintenance/actions/7/metrics/before", path.get());assertTrue(body.get().contains("\"tableId\":1"));assertTrue(body.get().contains("\"policyId\":20"));- client.finish(7L, new MaintenanceActionFinishRequest(1L, 20L, 11L));+ client.finish(7L, new MaintenanceActionFinishRequest(1L, 20L));assertEquals("/api/metalakes/demo/maintenance/actions/7/finish", path.get());}assertEquals(basic("alice", "dummy"), auth.get());diff --git a/maintenance/maintenance-common/src/main/java/org/apache/gravitino/maintenance/dto/requests/MaintenanceActionFinishRequest.java b/maintenance/maintenance-common/src/main/java/org/apache/gravitino/maintenance/dto/requests/MaintenanceActionFinishRequest.javaindex 414691fbc9..57e4ea292d 100644--- a/maintenance/maintenance-common/src/main/java/org/apache/gravitino/maintenance/dto/requests/MaintenanceActionFinishRequest.java+++ b/maintenance/maintenance-common/src/main/java/org/apache/gravitino/maintenance/dto/requests/MaintenanceActionFinishRequest.java@@ -20,7 +20,6 @@ package org.apache.gravitino.maintenance.dto.requests;import com.fasterxml.jackson.annotation.JsonProperty;import com.google.common.base.Preconditions;-import javax.annotation.Nullable;import lombok.EqualsAndHashCode;import lombok.Getter;import org.apache.gravitino.rest.RESTRequest;@@ -30,7 +29,8 @@ import org.apache.gravitino.rest.RESTRequest;* metrics.** <p>Use when a maintenance type does not sample metrics, or when metrics were already reported and- * only occupancy release remains.+ * only occupancy release remains. Iceberg snapshot ids stay on {@code table_snapshot_metrics}; this+ * request does not carry them.*/@Getter@EqualsAndHashCode@@ -42,27 +42,9 @@ public class MaintenanceActionFinishRequest implements RESTRequest {@JsonProperty("policyId")private final Long policyId;- /**- * Optional Iceberg snapshot id to store as {@code after_snapshot_id}. Omit or null when releasing- * without an S1 (for example skipped work with no rewrite).- */- @Nullable- @JsonProperty("afterSnapshotId")- private final Long afterSnapshotId;-/** Default constructor for Jackson. */public MaintenanceActionFinishRequest() {- this(null, null, null);- }-- /**- * Creates a finish request that leaves {@code after_snapshot_id} null.- *- * @param tableId table entity id bound to the job- * @param policyId policy entity id bound to the job- */- public MaintenanceActionFinishRequest(Long tableId, Long policyId) {- this(tableId, policyId, null);+ this(null, null);}/**@@ -70,13 +52,10 @@ public class MaintenanceActionFinishRequest implements RESTRequest {** @param tableId table entity id bound to the job* @param policyId policy entity id bound to the job- * @param afterSnapshotId terminal snapshot id, or null*/- public MaintenanceActionFinishRequest(- Long tableId, Long policyId, @Nullable Long afterSnapshotId) {+ public MaintenanceActionFinishRequest(Long tableId, Long policyId) {this.tableId = tableId;this.policyId = policyId;- this.afterSnapshotId = afterSnapshotId;}@Overridediff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/MaintenanceMetricsService.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/MaintenanceMetricsService.javaindex 8cd620b345..b194f3a2f7 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/MaintenanceMetricsService.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/MaintenanceMetricsService.java@@ -18,6 +18,7 @@*/package org.apache.gravitino.maintenance;+import java.util.Objects;import java.util.function.LongFunction;import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.maintenance.dto.requests.MaintenanceActionFinishRequest;@@ -36,8 +37,8 @@ import org.slf4j.LoggerFactory;* parameter on metrics reports, or via {@link #finishAction} when no metrics are needed. There is* no job-terminal reclaim path.*- * <p>Callbacks that arrive before submit-side {@code bindJobId} lazy-bind the unbound claim for the- * reported {@code (tableId, policyId)} onto the path {@code jobId}.+ * <p>Callbacks are keyed by {@code action_id} injected at submit time. Metrics writes require the+ * row to be bound ({@code job_id IS NOT NULL}).*/public class MaintenanceMetricsService {@@ -77,122 +78,127 @@ public class MaintenanceMetricsService {}/**- * S0 report: stores metrics, records {@code before_snapshot_id}, optionally closes the soft slot+ * S0 report: stores metrics, records {@code before_metrics_id}, optionally closes the soft slot* (for example snapshot drift / skip).** @param metalake metalake name from the request path- * @param jobId Gravitino job run id+ * @param actionId maintenance action id* @param finish when {@code true}, close the soft slot after storing metrics* @param request validated metrics payload*/public void reportBeforeMetrics(- String metalake, long jobId, boolean finish, MaintenanceActionMetricsRequest request) {- TableMaintenanceActionPO action =- loadInFlight(metalake, jobId, request.getTableId(), request.getPolicyId());- metricsMetaService.insertMetrics(- action.tableId(), action.policyId(), request.getSnapshotId(), request.getMetricsJson());- actionMetaService.recordBeforeSnapshot(- jobId, action.tableId(), action.policyId(), request.getSnapshotId());- maybeFinish(- jobId,- action,- /*afterSnapshotId=*/ null,- finish,- "before",- metalake,- request.getSnapshotId());+ String metalake, long actionId, boolean finish, MaintenanceActionMetricsRequest request) {+ TableMaintenanceActionPO action = loadInFlight(metalake, actionId, request);+ long metricsId =+ action.beforeMetricsId() != null+ ? action.beforeMetricsId()+ : metricsMetaService.insertMetrics(+ action.tableId(),+ action.policyId(),+ request.getSnapshotId(),+ request.getMetricsJson());+ actionMetaService.recordBeforeMetrics(actionId, metricsId);+ maybeFinish(actionId, action, finish, "before", metalake, metricsId);}/**- * S1 report: stores metrics and optionally closes the soft slot with {@code after_snapshot_id} =- * {@code snapshotId}.+ * S1 report: stores metrics, records {@code after_metrics_id}, optionally closes the soft slot.** @param metalake metalake name from the request path- * @param jobId Gravitino job run id+ * @param actionId maintenance action id* @param finish when {@code true}, close the soft slot after storing metrics* @param request validated metrics payload*/public void reportAfterMetrics(- String metalake, long jobId, boolean finish, MaintenanceActionMetricsRequest request) {- TableMaintenanceActionPO action =- loadInFlight(metalake, jobId, request.getTableId(), request.getPolicyId());- metricsMetaService.insertMetrics(- action.tableId(), action.policyId(), request.getSnapshotId(), request.getMetricsJson());- maybeFinish(- jobId, action, request.getSnapshotId(), finish, "after", metalake, request.getSnapshotId());+ String metalake, long actionId, boolean finish, MaintenanceActionMetricsRequest request) {+ TableMaintenanceActionPO action = loadInFlight(metalake, actionId, request);+ long metricsId =+ action.afterMetricsId() != null+ ? action.afterMetricsId()+ : metricsMetaService.insertMetrics(+ action.tableId(),+ action.policyId(),+ request.getSnapshotId(),+ request.getMetricsJson());+ actionMetaService.recordAfterMetrics(actionId, metricsId);+ maybeFinish(actionId, action, finish, "after", metalake, metricsId);}/**- * Closes the soft slot for one bound table/policy without writing metrics.+ * Closes the soft slot for one bound action without writing metrics.** @param metalake metalake name from the request path- * @param jobId Gravitino job run id- * @param request finish payload ({@code tableId}, {@code policyId}, optional {@code- * afterSnapshotId})+ * @param actionId maintenance action id+ * @param request finish payload ({@code tableId}, {@code policyId})*/- public void finishAction(String metalake, long jobId, MaintenanceActionFinishRequest request) {+ public void finishAction(String metalake, long actionId, MaintenanceActionFinishRequest request) {TableMaintenanceActionPO action =- loadInFlight(metalake, jobId, request.getTableId(), request.getPolicyId());- actionMetaService.markFinished(- jobId,- action.tableId(),- action.policyId(),- request.getAfterSnapshotId(),- System.currentTimeMillis());+ loadInFlight(+ metalake,+ actionId,+ request.getTableId(),+ request.getPolicyId(),+ /*requireBound=*/ true);+ actionMetaService.markFinished(actionId, System.currentTimeMillis());LOG.info(- "action finished for job {} metalake {} table {} policy {} afterSnapshotId={}",- jobId,+ "action finished for action_id {} metalake {} table {} policy {}",+ actionId,metalake,action.tableId(),- action.policyId(),- request.getAfterSnapshotId());+ action.policyId());}private void maybeFinish(- long jobId,+ long actionId,TableMaintenanceActionPO action,- Long afterSnapshotId,boolean finish,String phase,String metalake,- long snapshotId) {+ long metricsId) {if (!finish) {LOG.info(- "{} metrics reported for job {} metalake {} table {} policy {} snapshot {}",+ "{} metrics reported for action_id {} metalake {} table {} policy {} metricsId {}",phase,- jobId,+ actionId,metalake,action.tableId(),action.policyId(),- snapshotId);+ metricsId);return;}- actionMetaService.markFinished(- jobId, action.tableId(), action.policyId(), afterSnapshotId, System.currentTimeMillis());+ actionMetaService.markFinished(actionId, System.currentTimeMillis());LOG.info(- "{} metrics reported and action finished for job {} metalake {} table {} policy {} snapshot {}",+ "{} metrics reported and action finished for action_id {} metalake {} table {} policy {} metricsId {}",phase,- jobId,+ actionId,metalake,action.tableId(),action.policyId(),- snapshotId);+ metricsId);}private TableMaintenanceActionPO loadInFlight(- String metalake, long jobId, long tableId, long policyId) {- TableMaintenanceActionPO action =- actionMetaService.getByJobIdAndTableIdAndPolicyId(jobId, tableId, policyId);+ String metalake, long actionId, MaintenanceActionMetricsRequest request) {+ return loadInFlight(+ metalake, actionId, request.getTableId(), request.getPolicyId(), /*requireBound=*/ true);+ }++ private TableMaintenanceActionPO loadInFlight(+ String metalake, long actionId, long tableId, long policyId, boolean requireBound) {+ TableMaintenanceActionPO action = actionMetaService.getById(actionId);if (action == null) {- if (actionMetaService.bindJobIdIfUnbound(tableId, policyId, jobId)) {- action = actionMetaService.getByJobIdAndTableIdAndPolicyId(jobId, tableId, policyId);- }+ throw new NoSuchEntityException("no maintenance action for action_id=%s", actionId);}- if (action == null) {+ if (!Objects.equals(action.tableId(), tableId)+ || !Objects.equals(action.policyId(), policyId)) {throw new NoSuchEntityException(- "no maintenance action for job_id=%s table_id=%s policy_id=%s", jobId, tableId, policyId);+ "action_id=%s does not match table_id=%s policy_id=%s", actionId, tableId, policyId);}requireActionInFlight(action);+ if (requireBound && action.jobId() == null) {+ throw new NoSuchEntityException(+ "maintenance action action_id=%s is not bound to a job yet", actionId);+ }requireActionInMetalake(action, metalake);return action;}@@ -200,7 +206,7 @@ public class MaintenanceMetricsService {private static void requireActionInFlight(TableMaintenanceActionPO action) {if (action.finishedAt() == null || action.finishedAt() != 0L) {throw new NoSuchEntityException(- "no in-flight maintenance action for job_id=%s", action.jobId());+ "no in-flight maintenance action for action_id=%s", action.actionId());}}@@ -208,11 +214,11 @@ public class MaintenanceMetricsService {String actionMetalake = metalakeLookup.apply(action.tableId());if (actionMetalake == null) {throw new NoSuchEntityException(- "no metalake for table_id=%s (job_id=%s)", action.tableId(), action.jobId());+ "no metalake for table_id=%s (action_id=%s)", action.tableId(), action.actionId());}if (!actionMetalake.equals(metalake)) {throw new NoSuchEntityException(- "no maintenance action for job_id=%s under metalake %s", action.jobId(), metalake);+ "no maintenance action for action_id=%s under metalake %s", action.actionId(), metalake);}}}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/TableMaintenanceInJobPipeline.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/TableMaintenanceInJobPipeline.javaindex 9cef15ca4e..3a149b84f1 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/TableMaintenanceInJobPipeline.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/TableMaintenanceInJobPipeline.java@@ -42,7 +42,7 @@ public class TableMaintenanceInJobPipeline {/*** Runs sample → drift → recommend for a cron Spark Job.*- * @param jobId Gravitino {@code job_run_meta.job_run_id}+ * @param actionId {@code table_maintenance_action.action_id} for the in-flight row* @param tableId table entity id* @param policyId policy entity id* @param sampledSnapshotId {@code S0}@@ -51,7 +51,7 @@ public class TableMaintenanceInJobPipeline {* @return continue only when HEAD matches {@code S0} and recommender says maintain*/public InJobGateOutcome gateCronJob(- long jobId,+ long actionId,long tableId,long policyId,long sampledSnapshotId,@@ -59,7 +59,7 @@ public class TableMaintenanceInJobPipeline {SnapshotHead head) {InJobGateOutcome afterSample =sampler.sampleAndGateCronJob(- jobId, tableId, policyId, sampledSnapshotId, metricsJson, head);+ actionId, tableId, policyId, sampledSnapshotId, metricsJson, head);if (!afterSample.continueMaintenance()) {return afterSample;}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/TableMaintenanceInJobSampler.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/TableMaintenanceInJobSampler.javaindex 59f187392f..14f7d12fee 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/TableMaintenanceInJobSampler.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/TableMaintenanceInJobSampler.java@@ -19,12 +19,13 @@package org.apache.gravitino.maintenance.injob;import com.google.common.base.Preconditions;+import org.apache.gravitino.maintenance.storage.po.TableMaintenanceActionPO;import org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService;import org.apache.gravitino.maintenance.storage.service.TableSnapshotMetricsMetaService;/*** In-Spark sampling path for cron jobs (§5.2.2): sample once at {@code S0}, persist metrics, record- * {@code before_snapshot_id}, then gate on snapshot drift without re-sampling.+ * {@code before_metrics_id}, then gate on snapshot drift without re-sampling.*/public class TableMaintenanceInJobSampler {@@ -50,13 +51,13 @@ public class TableMaintenanceInJobSampler {}/**- * Persists metrics for {@code S0}, sets {@code before_snapshot_id} on the maintenance action row,+ * Persists metrics for {@code S0}, sets {@code before_metrics_id} on the maintenance action row,* and returns whether the cron Spark Job should continue.** <p>If HEAD has drifted after the sample, the caller must end the job early and must not* re-sample in a loop (§4.3).*- * @param jobId Gravitino {@code job_run_meta.job_run_id} for the in-flight maintenance row+ * @param actionId {@code table_maintenance_action.action_id} for the in-flight row* @param tableId table entity id* @param policyId policy entity id* @param sampledSnapshotId Iceberg snapshot id at sample time ({@code S0})@@ -65,7 +66,7 @@ public class TableMaintenanceInJobSampler {* @return continue vs drift stop outcome*/public InJobGateOutcome sampleAndGateCronJob(- long jobId,+ long actionId,long tableId,long policyId,long sampledSnapshotId,@@ -74,8 +75,25 @@ public class TableMaintenanceInJobSampler {Preconditions.checkNotNull(metricsJson, "metricsJson");Preconditions.checkNotNull(head, "head");- metricsMetaService.insertMetrics(tableId, policyId, sampledSnapshotId, metricsJson);- actionMetaService.recordBeforeSnapshot(jobId, tableId, policyId, sampledSnapshotId);+ TableMaintenanceActionPO action = actionMetaService.getById(actionId);+ Preconditions.checkState(action != null, "no maintenance action for action_id %s", actionId);+ Preconditions.checkState(+ action.tableId() != null+ && action.tableId() == tableId+ && action.policyId() != null+ && action.policyId() == policyId,+ "action_id %s does not match table %s policy %s",+ actionId,+ tableId,+ policyId);+ long metricsId;+ if (action.beforeMetricsId() != null) {+ metricsId = action.beforeMetricsId();+ } else {+ metricsId =+ metricsMetaService.insertMetrics(tableId, policyId, sampledSnapshotId, metricsJson);+ actionMetaService.recordBeforeMetrics(actionId, metricsId);+ }long headSnapshotId = head.currentSnapshotId();if (sampledSnapshotId != headSnapshotId) {diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/MaintenanceJobSpec.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/MaintenanceJobSpec.javaindex 516d70b3ea..5da9c2547e 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/MaintenanceJobSpec.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/MaintenanceJobSpec.java@@ -20,6 +20,7 @@ package org.apache.gravitino.maintenance.scheduler;import com.fasterxml.jackson.annotation.JsonIgnore;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;+import com.fasterxml.jackson.annotation.JsonProperty;import com.google.common.base.Preconditions;import java.util.ArrayList;import java.util.Collections;@@ -29,126 +30,128 @@ import java.util.Map;import java.util.Objects;import java.util.stream.Collectors;import javax.annotation.Nullable;+import org.apache.gravitino.maintenance.optimizer.common.util.IcebergSparkConfigUtils;+import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceJobTemplates;/*** Enqueue-time spec stored as JSON in db-scheduler {@code task_data} for {@code cron-job} and* {@code commit-job} rows.*- * <p>Thin envelope only: {@link #jobConf} is the same {@code Map<String,String>} passed to {@code- * runJob} (including {@code updater_options} as a JSON string). Tables carry {@code tableId} plus- * NameIdentifier levels (metalake first); operations carry {@code policyId} plus the wire- * maintenance type. Metalake for {@code runJob} is derived from {@link #tables}.+ * <p>Shape stays close to Iceberg update-stats {@code runJob} conf: each {@link Task} carries TMS+ * routing fields plus a flat {@code parameters} map (old template placeholders). Shared session+ * bags {@code updater_options} and {@code spark_conf} sit at the envelope top as JSON object+ * strings. Submit merges one task (cron) or all tasks (commit chain) into the flat {@code+ * Map<String,String>} passed to {@code runJob}.*/@JsonIgnoreProperties(ignoreUnknown = true)public final class MaintenanceJobSpec {- private List<TableTarget> tables = new ArrayList<>();- private List<Operation> operations = new ArrayList<>();- private Map<String, String> jobConf = new LinkedHashMap<>();+ private List<Task> tasks = new ArrayList<>();++ @JsonProperty("updater_options")+ private String updaterOptions;++ @JsonProperty("spark_conf")+ private String sparkConf;/** Jackson / empty constructor. */public MaintenanceJobSpec() {}/**- * @param tables table targets (order preserved)- * @param operations maintenance operations (order preserved; cron: one; commit: chain)- * @param jobConf runJob configuration map+ * @param tasks maintenance tasks (order preserved)+ * @param updaterOptions JSON object string for {@code updater_options}+ * @param sparkConf JSON object string for {@code spark_conf}; may be null when empty*/public MaintenanceJobSpec(- List<TableTarget> tables, List<Operation> operations, Map<String, String> jobConf) {- this.tables = new ArrayList<>(Preconditions.checkNotNull(tables, "tables"));- this.operations = new ArrayList<>(Preconditions.checkNotNull(operations, "operations"));- this.jobConf = new LinkedHashMap<>(Preconditions.checkNotNull(jobConf, "jobConf"));+ List<Task> tasks, @Nullable String updaterOptions, @Nullable String sparkConf) {+ this.tasks = new ArrayList<>(Preconditions.checkNotNull(tasks, "tasks"));+ this.updaterOptions = updaterOptions;+ this.sparkConf = sparkConf;}/**- * @return table targets+ * @return maintenance tasks*/- public List<TableTarget> getTables() {- return tables;+ public List<Task> getTasks() {+ return tasks;}/**- * @param tables table targets+ * @param tasks maintenance tasks*/- public void setTables(List<TableTarget> tables) {- this.tables = tables == null ? new ArrayList<>() : new ArrayList<>(tables);+ public void setTasks(List<Task> tasks) {+ this.tasks = tasks == null ? new ArrayList<>() : new ArrayList<>(tasks);}/**- * @return maintenance operations+ * @return shared updater options JSON string*/- public List<Operation> getOperations() {- return operations;+ public String getUpdaterOptions() {+ return updaterOptions;}/**- * @param operations maintenance operations+ * @param updaterOptions shared updater options JSON string*/- public void setOperations(List<Operation> operations) {- this.operations = operations == null ? new ArrayList<>() : new ArrayList<>(operations);+ public void setUpdaterOptions(String updaterOptions) {+ this.updaterOptions = updaterOptions;}/**- * @return runJob configuration+ * @return shared spark_conf JSON string*/- public Map<String, String> getJobConf() {- return jobConf;+ public String getSparkConf() {+ return sparkConf;}/**- * @param jobConf runJob configuration+ * @param sparkConf shared spark_conf JSON string*/- public void setJobConf(Map<String, String> jobConf) {- this.jobConf = jobConf == null ? new LinkedHashMap<>() : new LinkedHashMap<>(jobConf);+ public void setSparkConf(String sparkConf) {+ this.sparkConf = sparkConf;}/**- * @return unmodifiable table entity ids in spec order+ * @return unmodifiable table entity ids in task order (may contain duplicates across types)*/@JsonIgnorepublic List<Long> tableIds() {- if (tables == null || tables.isEmpty()) {+ if (tasks == null || tasks.isEmpty()) {return List.of();}return Collections.unmodifiableList(- tables.stream().map(TableTarget::getTableId).collect(Collectors.toList()));+ tasks.stream().map(Task::getTableId).collect(Collectors.toList()));}/**- * Metalake for {@code runJob} / cancel, taken from the first table's NameIdentifier.+ * Metalake for {@code runJob} / cancel, taken from {@code updater_options.metalake}.*- * @return metalake name, or {@code null} when tables are missing / incomplete+ * @return metalake name, or {@code null} when missing*/@JsonIgnore@Nullablepublic String metalake() {- if (tables == null || tables.isEmpty()) {- return null;- }- List<String> identifier = tables.get(0).getIdentifier();- if (identifier == null || identifier.isEmpty()) {+ if (updaterOptions == null || updaterOptions.isBlank()) {return null;}- String name = identifier.get(0);- return name == null || name.isBlank() ? null : name;+ Map<String, String> options =+ IcebergSparkConfigUtils.parseFlatJsonMap(+ updaterOptions, MaintenanceJobTemplates.UPDATER_OPTIONS_JOB_CONF_KEY);+ String metalake = options.get("metalake");+ return metalake == null || metalake.isBlank() ? null : metalake.trim();}/**- * @return true when tables, operations, and jobConf look usable for submit+ * @return true when tasks and shared updater_options look usable for submit*/@JsonIgnorepublic boolean isValid() {return metalake() != null- && tables != null- && !tables.isEmpty()- && operations != null- && !operations.isEmpty()- && jobConf != null- && !jobConf.isEmpty()- && operations.get(0).getPolicyId() > 0- && tables.stream().allMatch(TableTarget::isValid)- && operations.stream().allMatch(Operation::isValid);+ && updaterOptions != null+ && !updaterOptions.isBlank()+ && tasks != null+ && !tasks.isEmpty()+ && tasks.stream().allMatch(Task::isValid);}@Override@@ -160,45 +163,61 @@ public final class MaintenanceJobSpec {return false;}MaintenanceJobSpec that = (MaintenanceJobSpec) o;- return Objects.equals(tables, that.tables)- && Objects.equals(operations, that.operations)- && Objects.equals(jobConf, that.jobConf);+ return Objects.equals(tasks, that.tasks)+ && Objects.equals(updaterOptions, that.updaterOptions)+ && Objects.equals(sparkConf, that.sparkConf);}@Overridepublic int hashCode() {- return Objects.hash(tables, operations, jobConf);+ return Objects.hash(tasks, updaterOptions, sparkConf);}@Overridepublic String toString() {- return "MaintenanceJobSpec{tables="+ return "MaintenanceJobSpec{tasks="+ + (tasks == null ? 0 : tasks.size())+ + ", tableIds="+ tableIds()- + ", operations="- + (operations == null ? 0 : operations.size())- + ", jobConfKeys="- + (jobConf == null ? 0 : jobConf.size())+ '}';}- /** One table covered by this spec. */+ /**+ * One runnable maintenance unit (typically one {@code runJob} on the cron path; commit chains+ * pack several tasks into one Spark submit).+ */@JsonIgnoreProperties(ignoreUnknown = true)- public static final class TableTarget {+ public static final class Task {private long tableId;- private List<String> identifier = new ArrayList<>();+ @Nullable private Long actionId;+ private long policyId;+ private String maintenanceType;+ private Map<String, String> parameters = new LinkedHashMap<>();/** Jackson constructor. */- public TableTarget() {}+ public Task() {}/*** @param tableId table entity id- * @param identifier NameIdentifier levels (metalake, catalog, …, table)+ * @param policyId policy entity id+ * @param maintenanceType Spark wire maintenance type+ * @param actionId soft-slot action id when known; null at enqueue+ * @param parameters flat template placeholders (old builtin jobConf keys)*/- public TableTarget(long tableId, List<String> identifier) {+ public Task(+ long tableId,+ long policyId,+ String maintenanceType,+ @Nullable Long actionId,+ Map<String, String> parameters) {Preconditions.checkArgument(tableId > 0, "tableId must be positive");+ Preconditions.checkArgument(policyId > 0, "policyId must be positive");this.tableId = tableId;- this.identifier = new ArrayList<>(Preconditions.checkNotNull(identifier, "identifier"));+ this.policyId = policyId;+ this.maintenanceType = Preconditions.checkNotNull(maintenanceType, "maintenanceType");+ this.actionId = actionId;+ this.parameters = new LinkedHashMap<>(Preconditions.checkNotNull(parameters, "parameters"));}/**@@ -216,117 +235,90 @@ public final class MaintenanceJobSpec {}/**- * @return NameIdentifier levels+ * @return soft-slot action id, or null before acquire*/- public List<String> getIdentifier() {- return identifier;+ @Nullable+ public Long getActionId() {+ return actionId;}/**- * @param identifier NameIdentifier levels+ * @param actionId soft-slot action id*/- public void setIdentifier(List<String> identifier) {- this.identifier = identifier == null ? new ArrayList<>() : new ArrayList<>(identifier);+ public void setActionId(@Nullable Long actionId) {+ this.actionId = actionId;}/**- * @return Spark catalog name ({@code identifier[1]})+ * @return policy entity id*/- @JsonIgnore- @Nullable- public String catalogName() {- return identifier != null && identifier.size() >= 2 ? identifier.get(1) : null;+ public long getPolicyId() {+ return policyId;}/**- * @return {@code schema.table} (or nested) Spark table identifier+ * @param policyId policy entity id*/- @JsonIgnore- @Nullable- public String sparkTableIdentifier() {- if (identifier == null || identifier.size() < 3) {- return null;- }- return String.join(".", identifier.subList(2, identifier.size()));- }-- @JsonIgnore- boolean isValid() {- return tableId > 0- && identifier != null- && identifier.size() >= 3- && identifier.stream().noneMatch(part -> part == null || part.isBlank());- }-- @Override- public boolean equals(Object o) {- if (this == o) {- return true;- }- if (!(o instanceof TableTarget)) {- return false;- }- TableTarget that = (TableTarget) o;- return tableId == that.tableId && Objects.equals(identifier, that.identifier);+ public void setPolicyId(long policyId) {+ this.policyId = policyId;}- @Override- public int hashCode() {- return Objects.hash(tableId, identifier);+ /**+ * @return Spark wire maintenance type+ */+ public String getMaintenanceType() {+ return maintenanceType;}- }-- /** One maintenance operation (cron: single type; commit: chain member). */- @JsonIgnoreProperties(ignoreUnknown = true)- public static final class Operation {-- private long policyId;- private String maintenanceType;-- /** Jackson constructor. */- public Operation() {}/**- * @param policyId policy entity id- * @param maintenanceType Spark wire name+ * @param maintenanceType Spark wire maintenance type*/- public Operation(long policyId, String maintenanceType) {- Preconditions.checkArgument(policyId > 0, "policyId must be positive");- this.policyId = policyId;- this.maintenanceType = Preconditions.checkNotNull(maintenanceType, "maintenanceType");+ public void setMaintenanceType(String maintenanceType) {+ this.maintenanceType = maintenanceType;}/**- * @return policy entity id+ * @return flat template placeholders*/- public long getPolicyId() {- return policyId;+ public Map<String, String> getParameters() {+ return parameters;}/**- * @param policyId policy entity id+ * @param parameters flat template placeholders*/- public void setPolicyId(long policyId) {- this.policyId = policyId;+ public void setParameters(Map<String, String> parameters) {+ this.parameters =+ parameters == null ? new LinkedHashMap<>() : new LinkedHashMap<>(parameters);}/**- * @return Spark wire maintenance type+ * @return Spark catalog name from {@code parameters.catalog_name}*/- public String getMaintenanceType() {- return maintenanceType;+ @JsonIgnore+ @Nullable+ public String catalogName() {+ return blankToNull(parameters == null ? null : parameters.get("catalog_name"));}/**- * @param maintenanceType Spark wire maintenance type+ * @return {@code schema.table} from {@code parameters.table_identifier}*/- public void setMaintenanceType(String maintenanceType) {- this.maintenanceType = maintenanceType;+ @JsonIgnore+ @Nullable+ public String tableIdentifier() {+ return blankToNull(parameters == null ? null : parameters.get("table_identifier"));}@JsonIgnoreboolean isValid() {- return policyId > 0 && maintenanceType != null && !maintenanceType.isBlank();+ return tableId > 0+ && policyId > 0+ && maintenanceType != null+ && !maintenanceType.isBlank()+ && parameters != null+ && catalogName() != null+ && tableIdentifier() != null;}@Override@@ -334,16 +326,24 @@ public final class MaintenanceJobSpec {if (this == o) {return true;}- if (!(o instanceof Operation)) {+ if (!(o instanceof Task)) {return false;}- Operation that = (Operation) o;- return policyId == that.policyId && Objects.equals(maintenanceType, that.maintenanceType);+ Task that = (Task) o;+ return tableId == that.tableId+ && policyId == that.policyId+ && Objects.equals(actionId, that.actionId)+ && Objects.equals(maintenanceType, that.maintenanceType)+ && Objects.equals(parameters, that.parameters);}@Overridepublic int hashCode() {- return Objects.hash(policyId, maintenanceType);+ return Objects.hash(tableId, actionId, policyId, maintenanceType, parameters);+ }++ private static @Nullable String blankToNull(@Nullable String value) {+ return value == null || value.isBlank() ? null : value.trim();}}}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/MaintenanceJobSpecFactory.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/MaintenanceJobSpecFactory.javaindex 37c55059e0..d6adf556ee 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/MaintenanceJobSpecFactory.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/MaintenanceJobSpecFactory.java@@ -19,29 +19,31 @@package org.apache.gravitino.maintenance.scheduler;import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.core.type.TypeReference;import com.google.common.annotations.VisibleForTesting;import com.google.common.base.Preconditions;+import com.google.common.collect.ImmutableSet;import java.util.ArrayList;-import java.util.Arrays;import java.util.LinkedHashMap;import java.util.List;import java.util.Locale;import java.util.Map;import java.util.Optional;+import java.util.Set;import java.util.regex.Matcher;import java.util.regex.Pattern;+import javax.annotation.Nullable;import org.apache.gravitino.Config;import org.apache.gravitino.json.JsonUtils;-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.Operation;-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.TableTarget;+import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.Task;import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceJobConfBuilder;import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceJobTemplates;import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceTableRefs.ResolvedTableRef;import org.apache.gravitino.meta.PolicyEntity;/**- * Builds enqueue-time {@link MaintenanceJobSpec} values for the cron path and shared jobConf- * helpers used by cron pick / commit merge.+ * Builds enqueue-time {@link MaintenanceJobSpec} values for the cron path and helpers used by cron+ * / commit submit to assemble the flat {@code runJob} map.*/public final class MaintenanceJobSpecFactory {@@ -49,6 +51,29 @@ public final class MaintenanceJobSpecFactory {private static final Pattern MEMORY_VALUE =Pattern.compile("^(\\d+(?:\\.\\d+)?)\\s*([kmgt]?i?b?)$", Pattern.CASE_INSENSITIVE);+ /**+ * Keys that belong on the {@code task_data} envelope or are re-derived at submit — not stored in+ * per-task {@code parameters}.+ */+ private static final Set<String> NON_PARAMETER_KEYS =+ ImmutableSet.of(+ MaintenanceJobTemplates.UPDATER_OPTIONS_JOB_CONF_KEY,+ "spark_conf",+ MaintenanceJobTemplates.MAINTENANCE_TYPES_KEY,+ MaintenanceJobTemplates.POLICY_IDS_KEY,+ MaintenanceJobTemplates.ACTION_IDS_KEY,+ "tables",+ "table_id",+ "spark_master",+ "spark_executor_instances",+ "spark_executor_cores",+ "spark_executor_memory",+ "spark_driver_memory",+ "catalog_type",+ "catalog_uri",+ "warehouse_location",+ "gravitino_job_id");+private final MaintenanceJobConfBuilder jobConfBuilder;/**@@ -60,9 +85,9 @@ public final class MaintenanceJobSpecFactory {}/**- * Cron spec for one or more tables under a single policy. Shared {@code jobConf} omits per-table- * keys; pick overlays {@code catalog_name} / {@code table_identifier} for each {@link- * TableTarget}.+ * Cron spec for one or more tables under a single policy. Shared {@code updater_options} / {@code+ * spark_conf} sit on the envelope; each table becomes one {@link Task} with its own {@code+ * parameters}.** <p>All tables must share the same Spark catalog name so catalog-scoped {@code spark_conf} keys* stay correct for every member of a batch.@@ -87,77 +112,138 @@ public final class MaintenanceJobSpecFactory {ref.catalogName());}- String metalake = policy.namespace().level(0);- Map<String, String> jobConf = jobConfBuilder.build(policy, catalogName);- // Per-table keys are applied at pick so one batch spec can cover many tables.- jobConf.remove("catalog_name");- jobConf.remove("table_identifier");+ Map<String, String> built = jobConfBuilder.build(policy, catalogName);+ MaintenanceJobConfBuilder.foldPlaceholdersIntoSparkConf(built, catalogName);+ EnqueueBags bags = splitEnqueueBags(built);- List<TableTarget> targets = new ArrayList<>(tables.size());+ List<Task> tasks = new ArrayList<>(tables.size());for (ResolvedTableRef ref : tables) {- targets.add(toTarget(metalake, ref));+ Map<String, String> parameters = new LinkedHashMap<>(bags.parameters);+ parameters.put("catalog_name", ref.catalogName());+ parameters.put("table_identifier", ref.tableIdentifier());+ tasks.add(new Task(ref.tableId(), policy.id(), wire.get(), null, parameters));}- List<Operation> operations = List.of(new Operation(policy.id(), wire.get()));- return new MaintenanceJobSpec(targets, operations, jobConf);+ return new MaintenanceJobSpec(tasks, bags.updaterOptions, bags.sparkConf);}/**- * Copies {@code shared} and overlays catalog plus a one-element {@code tables} JSON for submit.+ * Assembles the flat {@code runJob} map for one cron task: task {@code parameters} + envelope+ * bags + TMS wire keys + one-element {@code tables} JSON.*- * <p>Entity {@code table_id} stays inside {@code tables} (system-filled). It is not a top-level- * template placeholder — users submitting the built-in template do not know entity ids.+ * @param spec enqueue spec+ * @param task task to submit+ * @return mutable jobConf (caller resolves secrets / injects {@code action_ids})+ */+ public static Map<String, String> jobConfForTask(MaintenanceJobSpec spec, Task task) {+ Preconditions.checkNotNull(spec, "spec");+ Preconditions.checkNotNull(task, "task");+ String catalogName = task.catalogName();+ String tableIdentifier = task.tableIdentifier();+ Preconditions.checkArgument(+ catalogName != null && tableIdentifier != null,+ "task tableId=%s is missing catalog_name/table_identifier in parameters",+ task.getTableId());++ Map<String, String> jobConf = new LinkedHashMap<>(task.getParameters());+ putSharedBags(jobConf, spec);+ jobConf.put(MaintenanceJobTemplates.MAINTENANCE_TYPES_KEY, task.getMaintenanceType());+ jobConf.put(MaintenanceJobTemplates.POLICY_IDS_KEY, Long.toString(task.getPolicyId()));+ jobConf.put("tables", toTablesJson(task.getTableId(), catalogName, tableIdentifier));+ jobConf.remove("table_identifier");+ jobConf.remove("table_id");+ MaintenanceJobConfBuilder.applySparkConfPlaceholders(jobConf, catalogName);+ return jobConf;+ }++ /**+ * Assembles one chained commit {@code runJob} map from all tasks (merged parameters + shared+ * bags).*- * @param shared jobConf- * @param target table to submit- * @return mutable per-table jobConf+ * @param spec commit-chain spec+ * @return mutable jobConf*/- public static Map<String, String> jobConfForTable(- Map<String, String> shared, TableTarget target) {- Preconditions.checkNotNull(shared, "shared");- Preconditions.checkNotNull(target, "target");- String catalogName = target.catalogName();- String tableIdentifier = target.sparkTableIdentifier();+ public static Map<String, String> jobConfForCommitChain(MaintenanceJobSpec spec) {+ Preconditions.checkNotNull(spec, "spec");+ Preconditions.checkArgument(+ spec.getTasks() != null && !spec.getTasks().isEmpty(), "tasks must not be empty");+ Task first = spec.getTasks().get(0);+ String catalogName = first.catalogName();+ String tableIdentifier = first.tableIdentifier();Preconditions.checkArgument(catalogName != null && tableIdentifier != null,- "table target %s is missing catalog/table identifier levels",- target.getTableId());- Map<String, String> jobConf = new LinkedHashMap<>(shared);- jobConf.put("catalog_name", catalogName);- jobConf.put("tables", toTablesJson(List.of(target)));+ "commit task tableId=%s is missing catalog_name/table_identifier",+ first.getTableId());++ Map<String, String> jobConf = new LinkedHashMap<>(first.getParameters());+ for (int i = 1; i < spec.getTasks().size(); i++) {+ Map<String, String> later = spec.getTasks().get(i).getParameters();+ mergeTaskParameters(jobConf, later);+ mergePolicyRulesByType(jobConf, later);+ }+ putSharedBags(jobConf, spec);++ List<String> types = new ArrayList<>(spec.getTasks().size());+ List<String> policyIds = new ArrayList<>(spec.getTasks().size());+ for (Task task : spec.getTasks()) {+ types.add(task.getMaintenanceType());+ policyIds.add(Long.toString(task.getPolicyId()));+ }+ jobConf.put(MaintenanceJobTemplates.MAINTENANCE_TYPES_KEY, String.join(",", types));+ jobConf.put(MaintenanceJobTemplates.POLICY_IDS_KEY, String.join(",", policyIds));+ jobConf.put("tables", toTablesJson(first.getTableId(), catalogName, tableIdentifier));jobConf.remove("table_identifier");jobConf.remove("table_id");+ MaintenanceJobConfBuilder.applySparkConfPlaceholders(jobConf, catalogName);return jobConf;}- private static String toTablesJson(List<TableTarget> tables) {- List<Map<String, Object>> payload = new ArrayList<>(tables.size());- for (TableTarget target : tables) {- String catalogName = target.catalogName();- String tableIdentifier = target.sparkTableIdentifier();- Preconditions.checkArgument(- catalogName != null && tableIdentifier != null,- "table target %s is missing catalog/table identifier levels",- target.getTableId());- Map<String, Object> entry = new LinkedHashMap<>();- entry.put("table_id", target.getTableId());- entry.put("catalog_name", catalogName);- entry.put("table_identifier", tableIdentifier);- payload.add(entry);+ private static void putSharedBags(Map<String, String> jobConf, MaintenanceJobSpec spec) {+ if (spec.getUpdaterOptions() != null && !spec.getUpdaterOptions().isBlank()) {+ jobConf.put(MaintenanceJobTemplates.UPDATER_OPTIONS_JOB_CONF_KEY, spec.getUpdaterOptions());}- try {- return JsonUtils.anyFieldMapper().writeValueAsString(payload);- } catch (JsonProcessingException e) {- throw new IllegalStateException("Failed to serialize tables for runJob", e);+ if (spec.getSparkConf() != null && !spec.getSparkConf().isBlank()) {+ jobConf.put("spark_conf", spec.getSparkConf());+ }+ }++ /**+ * Splits a {@link MaintenanceJobConfBuilder#build} map into envelope bags vs per-task parameters.+ */+ public static EnqueueBags splitEnqueueBags(Map<String, String> built) {+ Preconditions.checkNotNull(built, "built");+ Map<String, String> parameters = new LinkedHashMap<>();+ String updaterOptions = null;+ String sparkConf = null;+ for (Map.Entry<String, String> entry : built.entrySet()) {+ String key = entry.getKey();+ String value = entry.getValue();+ if (key == null || value == null) {+ continue;+ }+ if (MaintenanceJobTemplates.UPDATER_OPTIONS_JOB_CONF_KEY.equals(key)) {+ updaterOptions = value;+ continue;+ }+ if ("spark_conf".equals(key)) {+ sparkConf = value;+ continue;+ }+ if (NON_PARAMETER_KEYS.contains(key)) {+ continue;+ }+ parameters.put(key, value);}+ Preconditions.checkArgument(+ updaterOptions != null && !updaterOptions.isBlank(),+ "updater_options is required on enqueue jobConf");+ return new EnqueueBags(parameters, updaterOptions, sparkConf);}/**- * For resource-shaped keys ({@code *memory*}, {@code *cores*}, {@code *instances*}), keep the- * larger value. Memory keys compare normalized byte sizes ({@code 1g} > {@code 512m}); cores /- * instances compare the leading integer. Other keys from the first policy are left unchanged.+ * Max-merge resource-shaped keys for commit-chain spark_conf / leftover flat keys.*- * @param into baseline jobConf (mutated)- * @param from candidate jobConf+ * @param into baseline map (mutated)+ * @param from candidate map*/public static void mergeResourceKeys(Map<String, String> into, Map<String, String> from) {for (Map.Entry<String, String> entry : from.entrySet()) {@@ -182,16 +268,74 @@ public final class MaintenanceJobSpecFactory {}/**- * @param metalake metalake name- * @param ref resolved Spark table ref- * @return table target with NameIdentifier levels+ * Merges later-task procedure parameters into the first task's map (first-wins except resource+ * keys; {@code rules} merged separately).+ */+ static void mergeTaskParameters(Map<String, String> into, Map<String, String> from) {+ mergeResourceKeys(into, from);+ for (Map.Entry<String, String> entry : from.entrySet()) {+ String key = entry.getKey();+ String value = entry.getValue();+ if (key == null+ || value == null+ || MaintenanceJobTemplates.RULES_KEY.equals(key)+ || "catalog_name".equals(key)+ || "table_identifier".equals(key)) {+ continue;+ }+ into.putIfAbsent(key, value);+ }+ }++ /**+ * Union {@link MaintenanceJobTemplates#RULES_KEY} maps so each chain type keeps its enqueue-time+ * rules.*/- public static TableTarget toTarget(String metalake, ResolvedTableRef ref) {- List<String> levels = new ArrayList<>();- levels.add(metalake);- levels.add(ref.catalogName());- levels.addAll(Arrays.asList(ref.tableIdentifier().split("\\.")));- return new TableTarget(ref.tableId(), levels);+ static void mergePolicyRulesByType(Map<String, String> into, Map<String, String> from) {+ String fromJson = from.get(MaintenanceJobTemplates.RULES_KEY);+ if (fromJson == null || fromJson.trim().isEmpty()) {+ return;+ }+ Map<String, Map<String, Object>> merged =+ new LinkedHashMap<>(parseRulesByType(into.get(MaintenanceJobTemplates.RULES_KEY)));+ for (Map.Entry<String, Map<String, Object>> entry : parseRulesByType(fromJson).entrySet()) {+ merged.putIfAbsent(entry.getKey(), entry.getValue());+ }+ try {+ into.put(+ MaintenanceJobTemplates.RULES_KEY, JsonUtils.anyFieldMapper().writeValueAsString(merged));+ } catch (JsonProcessingException e) {+ throw new IllegalStateException(+ "Failed to serialize " + MaintenanceJobTemplates.RULES_KEY, e);+ }+ }++ private static Map<String, Map<String, Object>> parseRulesByType(@Nullable String json) {+ if (json == null || json.trim().isEmpty()) {+ return Map.of();+ }+ try {+ Map<String, Map<String, Object>> parsed =+ JsonUtils.anyFieldMapper()+ .readValue(json, new TypeReference<Map<String, Map<String, Object>>>() {});+ return parsed == null ? Map.of() : parsed;+ } catch (JsonProcessingException e) {+ throw new IllegalStateException("Failed to parse " + MaintenanceJobTemplates.RULES_KEY, e);+ }+ }++ private static String toTablesJson(long tableId, String catalogName, String tableIdentifier) {+ List<Map<String, Object>> payload = new ArrayList<>(1);+ Map<String, Object> entry = new LinkedHashMap<>();+ entry.put("table_id", tableId);+ entry.put("catalog_name", catalogName);+ entry.put("table_identifier", tableIdentifier);+ payload.add(entry);+ try {+ return JsonUtils.anyFieldMapper().writeValueAsString(payload);+ } catch (JsonProcessingException e) {+ throw new IllegalStateException("Failed to serialize tables for runJob", e);+ }}private static boolean isResourceKey(String key) {@@ -282,4 +426,20 @@ public final class MaintenanceJobSpecFactory {}return map;}++ /** Envelope bags peeled from {@link MaintenanceJobConfBuilder#build}. */+ public static final class EnqueueBags {+ /** Per-task template placeholders (no updater/spark session bags). */+ public final Map<String, String> parameters;+ /** Shared updater_options JSON string. */+ public final String updaterOptions;+ /** Shared spark_conf JSON string; may be null. */+ @Nullable public final String sparkConf;++ EnqueueBags(Map<String, String> parameters, String updaterOptions, @Nullable String sparkConf) {+ this.parameters = parameters;+ this.updaterOptions = updaterOptions;+ this.sparkConf = sparkConf;+ }+ }}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobSpecFactory.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobSpecFactory.javaindex ad83df0f4f..4046f2aea5 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobSpecFactory.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobSpecFactory.java@@ -19,44 +19,32 @@package org.apache.gravitino.maintenance.scheduler.job.commit;import com.fasterxml.jackson.core.JsonProcessingException;-import com.fasterxml.jackson.core.type.TypeReference;import com.google.common.base.Preconditions;+import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;-import java.util.Set;-import java.util.stream.Collectors;+import javax.annotation.Nullable;import org.apache.gravitino.Config;import org.apache.gravitino.json.JsonUtils;import org.apache.gravitino.maintenance.optimizer.common.util.IcebergSparkConfigUtils;import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.Operation;-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.TableTarget;+import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.Task;import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpecFactory;+import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpecFactory.EnqueueBags;import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceJobConfBuilder;-import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceJobTemplates;import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceTableRefs.ResolvedTableRef;/*** Builds enqueue-time {@link MaintenanceJobSpec} values for the commit-job path (keeps commit →* scheduler dependency one-way; no scheduler → commit package cycle).*- * <p>Chain {@code jobConf} starts from the first policy, takes the max of resource-shaped keys from- * later members, and {@code putIfAbsent}s remaining keys so later types keep their procedure params- * (e.g. expire {@code older_than}) when auth bags already agree. {@code rules} is unioned across- * members so each type keeps its enqueue-time rules for in-Spark recommend.+ * <p>Each onCommit chain member becomes one {@link Task} with its own {@code parameters}. Shared+ * {@code updater_options} come from the first policy; {@code spark_conf} is merged across members+ * (first-wins keys, max resource-shaped values).*/final class CommitJobSpecFactory {- private static final Set<String> CHAIN_OWNED_KEYS =- Set.of(- MaintenanceJobTemplates.MAINTENANCE_TYPES_KEY,- MaintenanceJobTemplates.POLICY_IDS_KEY,- "catalog_name",- "table_identifier",- "tables",- MaintenanceJobTemplates.RULES_KEY);-private final MaintenanceJobConfBuilder jobConfBuilder;/**@@ -73,128 +61,68 @@ final class CommitJobSpecFactory {** @param chain non-empty onCommit members in order* @param ref resolved Spark table ref- * @return spec with merged {@code jobConf} including {@code maintenance_types} and {@code- * policy_ids}+ * @return spec with one task per chain member*/MaintenanceJobSpec forCommit(List<CommitChainMember> chain, ResolvedTableRef ref) {Preconditions.checkArgument(chain != null && !chain.isEmpty(), "chain must not be empty");Preconditions.checkNotNull(ref, "ref");- CommitChainMember first = chain.get(0);- String metalake = first.policy().namespace().level(0);- Map<String, String> jobConf = buildChainJobConf(chain, ref);- List<TableTarget> targets = List.of(MaintenanceJobSpecFactory.toTarget(metalake, ref));- List<Operation> operations =- chain.stream()- .map(m -> new Operation(m.policy().id(), m.maintenanceType()))- .collect(Collectors.toList());- return new MaintenanceJobSpec(targets, operations, jobConf);- }-- private Map<String, String> buildChainJobConf(- List<CommitChainMember> chain, ResolvedTableRef ref) {- CommitChainMember first = chain.get(0);- Map<String, String> jobConf = jobConfBuilder.build(first.policy(), ref.catalogName());- for (int i = 1; i < chain.size(); i++) {- Map<String, String> other = jobConfBuilder.build(chain.get(i).policy(), ref.catalogName());- mergeLaterMemberJobConf(jobConf, other);- }- List<String> types =- chain.stream().map(CommitChainMember::maintenanceType).collect(Collectors.toList());- List<String> policyIds =- chain.stream().map(m -> Long.toString(m.policy().id())).collect(Collectors.toList());- jobConf.put(MaintenanceJobTemplates.MAINTENANCE_TYPES_KEY, String.join(",", types));- jobConf.put(MaintenanceJobTemplates.POLICY_IDS_KEY, String.join(",", policyIds));- // Per-table keys (catalog_name / tables JSON) are applied at pick via jobConfForTable.- jobConf.remove("catalog_name");- jobConf.remove("table_identifier");- jobConf.remove("tables");- return jobConf;- }+ Map<String, String> firstBuilt = jobConfBuilder.build(chain.get(0).policy(), ref.catalogName());+ MaintenanceJobConfBuilder.foldPlaceholdersIntoSparkConf(firstBuilt, ref.catalogName());+ EnqueueBags first = MaintenanceJobSpecFactory.splitEnqueueBags(firstBuilt);+ String updaterOptions = first.updaterOptions;+ Map<String, String> sparkConf =+ new LinkedHashMap<>(+ IcebergSparkConfigUtils.parseFlatJsonMap(nullToEmpty(first.sparkConf), "spark_conf"));- /**- * Max-merge resource keys; fill missing non-owned keys from a later chain member (procedure- * params). First-policy auth / {@code updater_options} win. Nested {@code spark_conf} is merged- * by key with first-wins {@code putIfAbsent}. {@code rules} are unioned by maintenance type.- */- static void mergeLaterMemberJobConf(Map<String, String> into, Map<String, String> from) {- MaintenanceJobSpecFactory.mergeResourceKeys(into, from);- mergePolicyRulesByType(into, from);- mergeSparkConfByKey(into, from);- for (Map.Entry<String, String> entry : from.entrySet()) {- String key = entry.getKey();- String value = entry.getValue();- if (key == null- || value == null- || CHAIN_OWNED_KEYS.contains(key)- || "spark_conf".equals(key)) {- continue;+ List<Task> tasks = new ArrayList<>(chain.size());+ for (int i = 0; i < chain.size(); i++) {+ CommitChainMember member = chain.get(i);+ EnqueueBags bags;+ if (i == 0) {+ bags = first;+ } else {+ Map<String, String> built = jobConfBuilder.build(member.policy(), ref.catalogName());+ MaintenanceJobConfBuilder.foldPlaceholdersIntoSparkConf(built, ref.catalogName());+ bags = MaintenanceJobSpecFactory.splitEnqueueBags(built);+ mergeSparkConfMaps(sparkConf, bags.sparkConf);}- into.putIfAbsent(key, value);+ Map<String, String> parameters = new LinkedHashMap<>(bags.parameters);+ parameters.put("catalog_name", ref.catalogName());+ parameters.put("table_identifier", ref.tableIdentifier());+ tasks.add(+ new Task(+ ref.tableId(), member.policy().id(), member.maintenanceType(), null, parameters));}++ String sparkConfJson = sparkConf.isEmpty() ? null : writeJson(sparkConf, "spark_conf");+ return new MaintenanceJobSpec(tasks, updaterOptions, sparkConfJson);}/**- * Merges nested {@code spark_conf} JSON maps. Existing keys in {@code into} win; keys only in- * {@code from} are added.+ * Merges nested {@code spark_conf} maps into {@code into}: max resource-shaped values, otherwise+ * first-wins {@code putIfAbsent}.*/- static void mergeSparkConfByKey(Map<String, String> into, Map<String, String> from) {- String fromJson = from.get("spark_conf");+ static void mergeSparkConfMaps(Map<String, String> into, @Nullable String fromJson) {if (fromJson == null || fromJson.trim().isEmpty()) {return;}- Map<String, String> merged =- new LinkedHashMap<>(- IcebergSparkConfigUtils.parseFlatJsonMap(into.get("spark_conf"), "spark_conf"));Map<String, String> later = IcebergSparkConfigUtils.parseFlatJsonMap(fromJson, "spark_conf");+ MaintenanceJobSpecFactory.mergeResourceKeys(into, later);for (Map.Entry<String, String> entry : later.entrySet()) {- merged.putIfAbsent(entry.getKey(), entry.getValue());- }- if (merged.isEmpty()) {- return;- }- try {- into.put("spark_conf", JsonUtils.anyFieldMapper().writeValueAsString(merged));- } catch (JsonProcessingException e) {- throw new IllegalStateException("Failed to merge spark_conf for commit chain", e);+ into.putIfAbsent(entry.getKey(), entry.getValue());}}- /**- * Union {@link MaintenanceJobTemplates#RULES_KEY} maps so each chain type keeps its own- * enqueue-time rules for in-Spark recommend.- */- static void mergePolicyRulesByType(Map<String, String> into, Map<String, String> from) {- String fromJson = from.get(MaintenanceJobTemplates.RULES_KEY);- if (fromJson == null || fromJson.trim().isEmpty()) {- return;- }- Map<String, Map<String, Object>> merged =- new LinkedHashMap<>(parseRulesByType(into.get(MaintenanceJobTemplates.RULES_KEY)));- Map<String, Map<String, Object>> later = parseRulesByType(fromJson);- for (Map.Entry<String, Map<String, Object>> entry : later.entrySet()) {- merged.putIfAbsent(entry.getKey(), entry.getValue());- }+ private static String writeJson(Object value, String field) {try {- into.put(- MaintenanceJobTemplates.RULES_KEY, JsonUtils.anyFieldMapper().writeValueAsString(merged));+ return JsonUtils.anyFieldMapper().writeValueAsString(value);} catch (JsonProcessingException e) {- throw new IllegalStateException(- "Failed to serialize " + MaintenanceJobTemplates.RULES_KEY, e);+ throw new IllegalStateException("Failed to serialize " + field, e);}}- private static Map<String, Map<String, Object>> parseRulesByType(String json) {- if (json == null || json.trim().isEmpty()) {- return Map.of();- }- try {- Map<String, Map<String, Object>> parsed =- JsonUtils.anyFieldMapper()- .readValue(json, new TypeReference<Map<String, Map<String, Object>>>() {});- return parsed == null ? Map.of() : parsed;- } catch (JsonProcessingException e) {- throw new IllegalStateException("Failed to parse " + MaintenanceJobTemplates.RULES_KEY, e);- }+ private static String nullToEmpty(@Nullable String value) {+ return value == null ? "" : value;}}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/MaintenanceCommitSubmitPipeline.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/MaintenanceCommitSubmitPipeline.javaindex 1675579dad..20e2a3c9e3 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/MaintenanceCommitSubmitPipeline.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/MaintenanceCommitSubmitPipeline.java@@ -25,8 +25,7 @@ import java.util.Optional;import java.util.stream.Collectors;import javax.annotation.Nullable;import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.Operation;-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.TableTarget;+import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.Task;import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpecFactory;import org.apache.gravitino.maintenance.scheduler.MaintenanceTaskIds;import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceJobConfBuilder;@@ -42,9 +41,9 @@ import org.slf4j.LoggerFactory;* abort if any step is in-flight → soft-slot claim for every chain policy → one chained {@code* runJob} → bind the same job id on every claim.*- * <p>Chain collection, cooldown filtering, auth consistency, and jobConf merge happen at enqueue- * (see {@link CommitJobClient}). The caller always deletes the one-shot {@code commit-job} row- * after this method returns.+ * <p>Chain collection, cooldown filtering, auth consistency, and task_data assembly happen at+ * enqueue (see {@link CommitJobClient}). The caller always deletes the one-shot {@code commit-job}+ * row after this method returns.*/public final class MaintenanceCommitSubmitPipeline {@@ -99,29 +98,28 @@ public final class MaintenanceCommitSubmitPipeline {"Skipping commit-job submit for table {} with missing/invalid task_data spec", tableId);return;}- TableTarget target = spec.getTables().get(0);- if (target.getTableId() != tableId) {+ if (spec.getTasks().stream().anyMatch(task -> task.getTableId() != tableId)) {LOG.warn(- "Skipping commit-job submit for instance {} whose spec tableId is {}",+ "Skipping commit-job submit for instance {} whose spec tableIds are {}",instanceId,- target.getTableId());+ spec.tableIds());return;}// Design §5.2.3: any remaining type in-flight → delete commit-job and stop.- for (Operation step : spec.getOperations()) {- if (occupancyGate.isInFlight(tableId, step.getPolicyId())) {+ for (Task task : spec.getTasks()) {+ if (occupancyGate.isInFlight(tableId, task.getPolicyId())) {LOG.info("Skipping commit-job submit for table {} (type {} policy {} still in-flight)",tableId,- step.getMaintenanceType(),- step.getPolicyId());+ task.getMaintenanceType(),+ task.getPolicyId());return;}}List<Long> policyIds =- spec.getOperations().stream().map(Operation::getPolicyId).collect(Collectors.toList());+ spec.getTasks().stream().map(Task::getPolicyId).collect(Collectors.toList());Optional<List<OccupancyClaim>> claims =actionMetaService.tryAcquireInFlightBatch(tableId, policyIds, claimTimeoutMs);if (claims.isEmpty()) {@@ -140,17 +138,16 @@ public final class MaintenanceCommitSubmitPipeline {Map<String, String> jobConf;try {jobConf =- jobConfBuilder.resolveForSubmit(- MaintenanceJobSpecFactory.jobConfForTable(- spec.getJobConf(), spec.getTables().get(0)));+ jobConfBuilder.resolveForSubmit(MaintenanceJobSpecFactory.jobConfForCommitChain(spec));} catch (RuntimeException e) {actionMetaService.deleteClaims(claims);LOG.warn(- "Skipping commit-job submit for table {}: invalid spec table target: {}",- tableId,- e.toString());+ "Skipping commit-job submit for table {}: invalid task_data: {}", tableId, e.toString());return;}+ jobConf.put(+ MaintenanceJobTemplates.ACTION_IDS_KEY,+ claims.stream().map(c -> Long.toString(c.actionId())).collect(Collectors.joining(",")));Long jobId = null;try {jobId =@@ -161,10 +158,8 @@ public final class MaintenanceCommitSubmitPipeline {"Submitted commit-job for table {} as job {} (chain={}, policies={})",tableId,jobId,- spec.getOperations().stream()- .map(Operation::getMaintenanceType)- .collect(Collectors.toList()),- spec.getOperations().stream().map(Operation::getPolicyId).collect(Collectors.toList()));+ spec.getTasks().stream().map(Task::getMaintenanceType).collect(Collectors.toList()),+ spec.getTasks().stream().map(Task::getPolicyId).collect(Collectors.toList()));} catch (RuntimeException e) {if (jobId != null) {cancelJobQuietly(metalake, jobId);@@ -173,7 +168,7 @@ public final class MaintenanceCommitSubmitPipeline {LOG.warn("Failed commit-job submit for table {} policies={}: {}",tableId,- spec.getOperations().stream().map(Operation::getPolicyId).collect(Collectors.toList()),+ spec.getTasks().stream().map(Task::getPolicyId).collect(Collectors.toList()),e.toString());}}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/CronJobClient.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/CronJobClient.javaindex db78566ed9..6d9efdbe51 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/CronJobClient.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/CronJobClient.java@@ -40,7 +40,7 @@ import org.apache.gravitino.Config;import org.apache.gravitino.json.JsonUtils;import org.apache.gravitino.maintenance.scheduler.AutocommitDataSources;import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.TableTarget;+import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.Task;import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpecFactory;import org.apache.gravitino.maintenance.scheduler.MaintenanceTaskIds;import org.apache.gravitino.maintenance.scheduler.TableMaintenanceSchedulerPools;@@ -418,11 +418,11 @@ public class CronJobClient {if (extraTableIds.isEmpty()) {return true;}- Map<Long, TableTarget> byId = new LinkedHashMap<>();- for (TableTarget target : open.spec.getTables()) {- byId.put(target.getTableId(), target);+ Map<Long, Task> byTableId = new LinkedHashMap<>();+ for (Task task : open.spec.getTasks()) {+ byTableId.putIfAbsent(task.getTableId(), task);}- if (byId.size() + extraTableIds.stream().filter(id -> !byId.containsKey(id)).count()+ if (byTableId.size() + extraTableIds.stream().filter(id -> !byTableId.containsKey(id)).count()> batchCapacity) {return false;}@@ -443,13 +443,13 @@ public class CronJobClient {extraTableIds);return false;}- String metalake = open.spec.metalake();- if (metalake == null) {+ if (open.spec.metalake() == null) {LOG.warn("Could not merge tables into cron-job {}: missing metalake on open spec",open.instanceId.getId());return false;}+ Task template = open.spec.getTasks().get(0);boolean added = false;for (ResolvedTableRef ref : resolved) {if (!openCatalog.equals(ref.catalogName())) {@@ -461,20 +461,32 @@ public class CronJobClient {openCatalog);return false;}- if (!byId.containsKey(ref.tableId())) {- byId.put(ref.tableId(), MaintenanceJobSpecFactory.toTarget(metalake, ref));+ if (!byTableId.containsKey(ref.tableId())) {+ Map<String, String> parameters = new LinkedHashMap<>(template.getParameters());+ parameters.put("catalog_name", ref.catalogName());+ parameters.put("table_identifier", ref.tableIdentifier());+ byTableId.put(+ ref.tableId(),+ new Task(+ ref.tableId(),+ template.getPolicyId(),+ template.getMaintenanceType(),+ null,+ parameters));added = true;}}if (!added) {return true;}- if (byId.size() > batchCapacity) {+ if (byTableId.size() > batchCapacity) {return false;}MaintenanceJobSpec merged =new MaintenanceJobSpec(- new ArrayList<>(byId.values()), open.spec.getOperations(), open.spec.getJobConf());+ new ArrayList<>(byTableId.values()),+ open.spec.getUpdaterOptions(),+ open.spec.getSparkConf());try {return client.reschedule(open.instanceId, open.executionTime, merged);} catch (RuntimeException e) {@@ -570,7 +582,7 @@ public class CronJobClient {continue;}String instanceId = execution.getTaskInstance().getId();- String catalog = data.getTables().isEmpty() ? null : data.getTables().get(0).catalogName();+ String catalog = data.getTasks().isEmpty() ? null : data.getTasks().get(0).catalogName();Optional<long[]> batch = MaintenanceTaskIds.parseCronBatch(instanceId);if (batch.isPresent()) {// [batchId, policyId]@@ -608,7 +620,7 @@ public class CronJobClient {String expireType =MaintenanceJobTemplates.maintenanceType(Policy.BuiltInType.ICEBERG_SNAPSHOT_EXPIRATION).orElseThrow();- return spec.getOperations().stream().anyMatch(op -> expireType.equals(op.getMaintenanceType()));+ return spec.getTasks().stream().anyMatch(t -> expireType.equals(t.getMaintenanceType()));}private static long nextBatchId(SchedulerClient client, long policyId) {diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceJobConfBuilder.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceJobConfBuilder.javaindex b5dcb43532..1cfdfcd78f 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceJobConfBuilder.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceJobConfBuilder.java@@ -19,6 +19,7 @@package org.apache.gravitino.maintenance.scheduler.job.cron;import com.fasterxml.jackson.core.JsonProcessingException;+import com.google.common.base.Preconditions;import com.google.common.collect.ImmutableMap;import com.google.common.collect.ImmutableSet;import java.time.Clock;@@ -130,7 +131,7 @@ public final class MaintenanceJobConfBuilder {** @param policy effective maintenance policy* @param catalogName Spark catalog alias for IRC property scoping- * @return mutable jobConf (per-table keys applied later by {@code jobConfForTable})+ * @return mutable jobConf (split into envelope bags / task {@code parameters} by the factory)*/public Map<String, String> build(PolicyEntity policy, String catalogName) {PolicyContent content = policy.content();@@ -193,6 +194,69 @@ public final class MaintenanceJobConfBuilder {return jobConf;}+ /**+ * Re-derives flat template placeholders ({@code spark_executor_memory}, {@code catalog_type}, …)+ * from nested {@code spark_conf}. Used when enqueue {@code task_data} stores only the JSON bag.+ *+ * @param jobConf mutable runJob map that already contains {@code spark_conf}+ * @param catalogName Spark catalog alias for IRC property scoping+ */+ public static void applySparkConfPlaceholders(Map<String, String> jobConf, String catalogName) {+ Preconditions.checkNotNull(jobConf, "jobConf");+ Preconditions.checkNotNull(catalogName, "catalogName");+ String sparkConfJson = jobConf.get("spark_conf");+ if (sparkConfJson == null || sparkConfJson.trim().isEmpty()) {+ return;+ }+ Map<String, String> sparkConf =+ IcebergSparkConfigUtils.parseFlatJsonMap(sparkConfJson, "spark_conf");+ fillPlaceholdersFromSparkConf(jobConf, sparkConf, catalogName);+ }++ /**+ * Folds flat session placeholders ({@code spark_executor_memory}, {@code catalog_type}, …) into+ * nested {@code spark_conf} so enqueue {@code task_data} can keep only the JSON bag at the top+ * level.+ *+ * @param jobConf mutable map from {@link #build}+ * @param catalogName Spark catalog alias for IRC property scoping+ */+ public static void foldPlaceholdersIntoSparkConf(+ Map<String, String> jobConf, String catalogName) {+ Preconditions.checkNotNull(jobConf, "jobConf");+ Preconditions.checkNotNull(catalogName, "catalogName");+ Map<String, String> sparkConf =+ new TreeMap<>(+ IcebergSparkConfigUtils.parseFlatJsonMap(jobConf.get("spark_conf"), "spark_conf"));+ for (Map.Entry<String, String> entry : SPARK_KEY_TO_PLACEHOLDER.entrySet()) {+ String sparkKey = entry.getKey();+ String placeholder = entry.getValue();+ String value = jobConf.get(placeholder);+ if (value != null && !value.isBlank()) {+ sparkConf.putIfAbsent(sparkKey, value);+ }+ }+ String catalogPrefix = SPARK_SQL_CATALOG_PREFIX + catalogName;+ putIfAbsentSparkFromPlaceholder(jobConf, sparkConf, "catalog_type", catalogPrefix + ".type");+ putIfAbsentSparkFromPlaceholder(jobConf, sparkConf, "catalog_uri", catalogPrefix + ".uri");+ putIfAbsentSparkFromPlaceholder(+ jobConf, sparkConf, "warehouse_location", catalogPrefix + ".warehouse");+ if (!sparkConf.isEmpty()) {+ jobConf.put("spark_conf", writeJson(sparkConf, "spark_conf"));+ }+ }++ private static void putIfAbsentSparkFromPlaceholder(+ Map<String, String> jobConf,+ Map<String, String> sparkConf,+ String placeholder,+ String sparkKey) {+ String value = jobConf.get(placeholder);+ if (value != null && !value.isBlank()) {+ sparkConf.putIfAbsent(sparkKey, value);+ }+ }+/*** Expands {@code gravitino.maintenance.*} conf-key references in an enqueue snapshot into live* values from {@code gravitino.conf}. Call immediately before {@code runJob}.diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceJobTemplates.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceJobTemplates.javaindex 79d0d3bfe7..94d51780eb 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceJobTemplates.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceJobTemplates.java@@ -49,6 +49,12 @@ public final class MaintenanceJobTemplates {*/public static final String POLICY_IDS_KEY = "policy_ids";+ /**+ * JobConf key for {@code table_maintenance_action.action_id} values parallel to {@link+ * #POLICY_IDS_KEY} (comma-separated). Injected at submit after soft-slot acquire.+ */+ public static final String ACTION_IDS_KEY = "action_ids";+/** JobConf key for overlaid updater options (JSON object string). */public static final String UPDATER_OPTIONS_JOB_CONF_KEY = "updater_options";diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceSparkSubmitPipeline.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceSparkSubmitPipeline.javaindex b4f960f8f4..8eda6f5b31 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceSparkSubmitPipeline.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceSparkSubmitPipeline.java@@ -23,8 +23,7 @@ import java.util.Map;import java.util.Optional;import javax.annotation.Nullable;import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.Operation;-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.TableTarget;+import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.Task;import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpecFactory;import org.apache.gravitino.maintenance.scheduler.MaintenanceTaskIds;import org.apache.gravitino.maintenance.storage.service.OccupancyClaim;@@ -37,12 +36,11 @@ import org.slf4j.LoggerFactory;* in-flight gate → soft-slot claim → {@code runJob} → bind job id.** <p>Single-table {@code table:...} and snapshot-expiry {@code batch:...} rows share the same spec- * shape; batch pick overlays per-table keys and submits one Spark job per table. If any spec table- * is in-flight, the whole pick stops without partial submits (one-shot row is still removed by the- * caller).+ * shape; each {@link Task} becomes one Spark job. If any task table is in-flight, the whole pick+ * stops without partial submits (one-shot row is still removed by the caller).** <p>Does not sample metrics or evaluate trigger-expr (both run inside Spark from enqueue-time- * {@code rules} in jobConf). Policy / jobConf are not recomputed here.+ * {@code rules} in task parameters).*/public final class MaintenanceSparkSubmitPipeline {@@ -94,8 +92,7 @@ public final class MaintenanceSparkSubmitPipeline {return;}- Operation step = spec.getOperations().get(0);- long policyId = step.getPolicyId();+ long policyId = spec.getTasks().get(0).getPolicyId();// parseCron* returns [leftId, policyId]long expectedPolicyId = tableIds.isPresent() ? tableIds.get()[1] : batchIds.get()[1];if (policyId != expectedPolicyId) {@@ -106,9 +103,19 @@ public final class MaintenanceSparkSubmitPipeline {expectedPolicyId);return;}+ for (Task task : spec.getTasks()) {+ if (task.getPolicyId() != policyId) {+ LOG.warn(+ "Skipping cron-job submit for {}: mixed policyIds in tasks ({} vs {})",+ instanceId,+ policyId,+ task.getPolicyId());+ return;+ }+ }if (tableIds.isPresent()) {long expectedTableId = tableIds.get()[0];- if (spec.getTables().size() != 1 || spec.getTables().get(0).getTableId() != expectedTableId) {+ if (spec.getTasks().size() != 1 || spec.getTasks().get(0).getTableId() != expectedTableId) {LOG.warn("Skipping cron-job submit for {}: spec tables {} do not match instance tableId {}",instanceId,@@ -120,28 +127,29 @@ public final class MaintenanceSparkSubmitPipeline {// minInterval was gated at expand enqueue; pick only blocks on in-flight. Any in-flight// member aborts the whole pick so a batch row is not partially submitted then deleted.- for (TableTarget target : spec.getTables()) {- if (occupancyGate.isInFlight(target.getTableId(), policyId)) {+ for (Task task : spec.getTasks()) {+ if (occupancyGate.isInFlight(task.getTableId(), policyId)) {LOG.info("Skipping cron-job {} entirely (table {} in-flight for policy {})",instanceId,- target.getTableId(),+ task.getTableId(),policyId);return;}}- for (TableTarget target : spec.getTables()) {- submitOne(spec, target, policyId);+ for (Task task : spec.getTasks()) {+ submitOne(spec, task);}}- private void submitOne(MaintenanceJobSpec spec, TableTarget target, long policyId) {+ private void submitOne(MaintenanceJobSpec spec, Task task) {+ long policyId = task.getPolicyId();Optional<OccupancyClaim> claim =- actionMetaService.tryAcquireInFlight(target.getTableId(), policyId, claimTimeoutMs);+ actionMetaService.tryAcquireInFlight(task.getTableId(), policyId, claimTimeoutMs);if (claim.isEmpty()) {LOG.info("Skipping cron-job submit for table {} policy {} (lost soft-slot race)",- target.getTableId(),+ task.getTableId(),policyId);return;}@@ -149,18 +157,17 @@ public final class MaintenanceSparkSubmitPipeline {Map<String, String> jobConf;try {jobConf =- jobConfBuilder.resolveForSubmit(- MaintenanceJobSpecFactory.jobConfForTable(spec.getJobConf(), target));+ jobConfBuilder.resolveForSubmit(MaintenanceJobSpecFactory.jobConfForTask(spec, task));} catch (RuntimeException e) {releaseClaimQuietly(claim.get());LOG.warn(- "Skipping cron-job submit for table {} policy {}: invalid spec table target: {}",- target.getTableId(),+ "Skipping cron-job submit for table {} policy {}: invalid task: {}",+ task.getTableId(),policyId,e.toString());return;}- runAndBind(spec.metalake(), jobConf, claim.get(), target.getTableId(), policyId);+ runAndBind(spec.metalake(), jobConf, claim.get(), task.getTableId(), policyId);}private void runAndBind(@@ -169,6 +176,7 @@ public final class MaintenanceSparkSubmitPipeline {OccupancyClaim claim,long tableId,long policyId) {+ jobConf.put(MaintenanceJobTemplates.ACTION_IDS_KEY, Long.toString(claim.actionId()));Long jobId = null;try {jobId =@@ -204,12 +212,14 @@ public final class MaintenanceSparkSubmitPipeline {if (!actionMetaService.deleteUnboundClaim(claim)) {LOG.debug("Occupancy claim {} created_at={} was not released (reclaimed or already bound)",- claim.id(),+ claim.actionId(),claim.createdAt());}} catch (RuntimeException releaseError) {LOG.warn(- "Failed to release occupancy claim {} after submit failure", claim.id(), releaseError);+ "Failed to release occupancy claim {} after submit failure",+ claim.actionId(),+ releaseError);}}}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/TableMaintenanceActionMapper.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/TableMaintenanceActionMapper.javaindex 522c4dbcc2..3012b18d57 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/TableMaintenanceActionMapper.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/TableMaintenanceActionMapper.java@@ -34,7 +34,7 @@ public interface TableMaintenanceActionMapper {String TABLE_NAME = "table_maintenance_action";@InsertProvider(type = TableMaintenanceActionSQLProviderFactory.class, method = "insertAction")- @Options(useGeneratedKeys = true, keyProperty = "actionMeta.id", keyColumn = "id")+ @Options(useGeneratedKeys = true, keyProperty = "actionMeta.actionId", keyColumn = "action_id")void insertAction(@Param("actionMeta") TableMaintenanceActionPO actionMeta);@InsertProvider(type = TableMaintenanceActionSQLProviderFactory.class, method = "insertActions")@@ -71,13 +71,13 @@ public interface TableMaintenanceActionMapper {@UpdateProvider(type = TableMaintenanceActionSQLProviderFactory.class, method = "bindJobId")int bindJobId(- @Param("id") long id,+ @Param("actionId") long actionId,@Param("jobId") long jobId,@Param("expectedCreatedAt") long expectedCreatedAt);@Nullable@SelectProvider(type = TableMaintenanceActionSQLProviderFactory.class, method = "selectById")- TableMaintenanceActionPO selectById(@Param("id") long id);+ TableMaintenanceActionPO selectById(@Param("actionId") long actionId);@SelectProvider(type = TableMaintenanceActionSQLProviderFactory.class, method = "selectByJobId")List<TableMaintenanceActionPO> selectByJobId(@Param("jobId") long jobId);@@ -98,37 +98,27 @@ public interface TableMaintenanceActionMapper {@UpdateProvider(type = TableMaintenanceActionSQLProviderFactory.class,- method = "updateBeforeSnapshot")- int updateBeforeSnapshot(- @Param("jobId") long jobId,- @Param("tableId") long tableId,- @Param("policyId") long policyId,- @Param("beforeSnapshotId") long beforeSnapshotId);-- @UpdateProvider(type = TableMaintenanceActionSQLProviderFactory.class, method = "markFinished")- int markFinished(- @Param("jobId") long jobId,- @Param("tableId") long tableId,- @Param("policyId") long policyId,- @Param("afterSnapshotId") Long afterSnapshotId,- @Param("finishedAt") long finishedAt);+ method = "updateBeforeMetrics")+ int updateBeforeMetrics(+ @Param("actionId") long actionId, @Param("beforeMetricsId") long beforeMetricsId);@UpdateProvider(type = TableMaintenanceActionSQLProviderFactory.class,- method = "backfillAfterSnapshot")- int backfillAfterSnapshot(- @Param("jobId") long jobId,- @Param("tableId") long tableId,- @Param("policyId") long policyId,- @Param("afterSnapshotId") long afterSnapshotId);+ method = "updateAfterMetrics")+ int updateAfterMetrics(+ @Param("actionId") long actionId, @Param("afterMetricsId") long afterMetricsId);++ @UpdateProvider(type = TableMaintenanceActionSQLProviderFactory.class, method = "markFinished")+ int markFinished(@Param("actionId") long actionId, @Param("finishedAt") long finishedAt);@DeleteProvider(type = TableMaintenanceActionSQLProviderFactory.class, method = "deleteById")- int deleteById(@Param("id") long id);+ int deleteById(@Param("actionId") long actionId);@DeleteProvider(type = TableMaintenanceActionSQLProviderFactory.class,method = "deleteUnboundClaim")- int deleteUnboundClaim(@Param("id") long id, @Param("expectedCreatedAt") long expectedCreatedAt);+ int deleteUnboundClaim(+ @Param("actionId") long actionId, @Param("expectedCreatedAt") long expectedCreatedAt);@DeleteProvider(type = TableMaintenanceActionSQLProviderFactory.class, method = "deleteByJobId")int deleteByJobId(@Param("jobId") long jobId);diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/TableMaintenanceActionSQLProviderFactory.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/TableMaintenanceActionSQLProviderFactory.javaindex 8a9818b84e..89bd6aa79f 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/TableMaintenanceActionSQLProviderFactory.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/TableMaintenanceActionSQLProviderFactory.java@@ -112,24 +112,24 @@ public class TableMaintenanceActionSQLProviderFactory {}/**- * @param id action id+ * @param actionId action id* @param jobId job run id* @param expectedCreatedAt claim lease start observed at acquire time* @return UPDATE statement*/public static String bindJobId(- @Param("id") long id,+ @Param("actionId") long actionId,@Param("jobId") long jobId,@Param("expectedCreatedAt") long expectedCreatedAt) {- return getProvider().bindJobId(id, jobId, expectedCreatedAt);+ return getProvider().bindJobId(actionId, jobId, expectedCreatedAt);}/**- * @param id action id+ * @param actionId action id* @return SELECT statement*/- public static String selectById(@Param("id") long id) {- return getProvider().selectById(id);+ public static String selectById(@Param("actionId") long actionId) {+ return getProvider().selectById(actionId);}/**@@ -164,68 +164,51 @@ public class TableMaintenanceActionSQLProviderFactory {}/**- * @param jobId job run id- * @param tableId table entity id- * @param policyId policy entity id- * @param beforeSnapshotId snapshot id+ * @param actionId action id+ * @param beforeMetricsId S0 metrics row id* @return UPDATE statement*/- public static String updateBeforeSnapshot(- @Param("jobId") long jobId,- @Param("tableId") long tableId,- @Param("policyId") long policyId,- @Param("beforeSnapshotId") long beforeSnapshotId) {- return getProvider().updateBeforeSnapshot(jobId, tableId, policyId, beforeSnapshotId);+ public static String updateBeforeMetrics(+ @Param("actionId") long actionId, @Param("beforeMetricsId") long beforeMetricsId) {+ return getProvider().updateBeforeMetrics(actionId, beforeMetricsId);}/**- * @param jobId job run id- * @param tableId table entity id- * @param policyId policy entity id- * @param afterSnapshotId after snapshot- * @param finishedAt finish millis+ * @param actionId action id+ * @param afterMetricsId S1 metrics row id* @return UPDATE statement*/- public static String markFinished(- @Param("jobId") long jobId,- @Param("tableId") long tableId,- @Param("policyId") long policyId,- @Param("afterSnapshotId") Long afterSnapshotId,- @Param("finishedAt") long finishedAt) {- return getProvider().markFinished(jobId, tableId, policyId, afterSnapshotId, finishedAt);+ public static String updateAfterMetrics(+ @Param("actionId") long actionId, @Param("afterMetricsId") long afterMetricsId) {+ return getProvider().updateAfterMetrics(actionId, afterMetricsId);}/**- * @param jobId job run id- * @param tableId table entity id- * @param policyId policy entity id- * @param afterSnapshotId after snapshot+ * @param actionId action id+ * @param finishedAt finish millis* @return UPDATE statement*/- public static String backfillAfterSnapshot(- @Param("jobId") long jobId,- @Param("tableId") long tableId,- @Param("policyId") long policyId,- @Param("afterSnapshotId") long afterSnapshotId) {- return getProvider().backfillAfterSnapshot(jobId, tableId, policyId, afterSnapshotId);+ public static String markFinished(+ @Param("actionId") long actionId, @Param("finishedAt") long finishedAt) {+ return getProvider().markFinished(actionId, finishedAt);}/**- * @param id action id+ * @param actionId action id* @return DELETE statement*/- public static String deleteById(@Param("id") long id) {- return getProvider().deleteById(id);+ public static String deleteById(@Param("actionId") long actionId) {+ return getProvider().deleteById(actionId);}/**- * @param id action id+ * @param actionId action id* @param expectedCreatedAt claim lease start* @return DELETE statement*/public static String deleteUnboundClaim(- @Param("id") long id, @Param("expectedCreatedAt") long expectedCreatedAt) {- return getProvider().deleteUnboundClaim(id, expectedCreatedAt);+ @Param("actionId") long actionId, @Param("expectedCreatedAt") long expectedCreatedAt) {+ return getProvider().deleteUnboundClaim(actionId, expectedCreatedAt);}/**diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/TableSnapshotMetricsMapper.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/TableSnapshotMetricsMapper.javaindex d80303fc1f..09da1cfabf 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/TableSnapshotMetricsMapper.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/TableSnapshotMetricsMapper.java@@ -21,6 +21,7 @@ package org.apache.gravitino.maintenance.storage.mapper;import javax.annotation.Nullable;import org.apache.gravitino.maintenance.storage.po.TableSnapshotMetricsPO;import org.apache.ibatis.annotations.InsertProvider;+import org.apache.ibatis.annotations.Options;import org.apache.ibatis.annotations.Param;import org.apache.ibatis.annotations.SelectProvider;@@ -30,12 +31,10 @@ public interface TableSnapshotMetricsMapper {String TABLE_NAME = "table_snapshot_metrics";@InsertProvider(type = TableSnapshotMetricsSQLProviderFactory.class, method = "insertMetrics")+ @Options(useGeneratedKeys = true, keyProperty = "metricsMeta.metricsId", keyColumn = "metrics_id")void insertMetrics(@Param("metricsMeta") TableSnapshotMetricsPO metricsMeta);@Nullable- @SelectProvider(type = TableSnapshotMetricsSQLProviderFactory.class, method = "selectMetrics")- TableSnapshotMetricsPO selectMetrics(- @Param("tableId") long tableId,- @Param("policyId") long policyId,- @Param("snapshotId") long snapshotId);+ @SelectProvider(type = TableSnapshotMetricsSQLProviderFactory.class, method = "selectById")+ TableSnapshotMetricsPO selectById(@Param("metricsId") long metricsId);}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/TableSnapshotMetricsSQLProviderFactory.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/TableSnapshotMetricsSQLProviderFactory.javaindex 1ab21cd27f..0dbbf080d3 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/TableSnapshotMetricsSQLProviderFactory.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/TableSnapshotMetricsSQLProviderFactory.java@@ -57,16 +57,11 @@ public class TableSnapshotMetricsSQLProviderFactory {}/**- * @param tableId table id- * @param policyId policy id- * @param snapshotId snapshot id+ * @param metricsId metrics row id* @return SELECT statement*/- public static String selectMetrics(- @Param("tableId") long tableId,- @Param("policyId") long policyId,- @Param("snapshotId") long snapshotId) {- return getProvider().selectMetrics(tableId, policyId, snapshotId);+ public static String selectById(@Param("metricsId") long metricsId) {+ return getProvider().selectById(metricsId);}static TableSnapshotMetricsBaseSQLProvider getProvider() {diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/provider/base/TableMaintenanceActionBaseSQLProvider.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/provider/base/TableMaintenanceActionBaseSQLProvider.javaindex 5da601c0e7..aed75b246f 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/provider/base/TableMaintenanceActionBaseSQLProvider.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/provider/base/TableMaintenanceActionBaseSQLProvider.java@@ -76,8 +76,9 @@ public class TableMaintenanceActionBaseSQLProvider {}/**- * Extends an expired unbound claim lease by CAS on {@code created_at} (ShedLock-style). Lease age- * is evaluated against the database clock so every node shares one TTL timeline.+ * Abandons an expired unbound soft slot by setting {@code finished_at} to the database clock.+ * Callers then {@code INSERT} a new in-flight row (new {@code action_id}). Lease age uses the+ * database clock so multi-node TTL does not depend on JVM skew.** @param tableId table entity id* @param policyId policy entity id@@ -91,7 +92,7 @@ public class TableMaintenanceActionBaseSQLProvider {String now = currentTimeMillisExpr();return "UPDATE "+ TABLE_NAME- + " SET created_at = "+ + " SET finished_at = "+ now+ " WHERE table_id = #{tableId} AND policy_id = #{policyId}"+ " AND job_id IS NULL AND finished_at = 0"@@ -113,8 +114,7 @@ public class TableMaintenanceActionBaseSQLProvider {}/**- * Unbound in-flight claims for a table (any policy). Used by callback lazy-bind when the Spark- * job reports before submit-side {@code bindJobId}.+ * Unbound in-flight claims for a table (any policy).** @param tableId table entity id* @return SELECT statement@@ -145,31 +145,31 @@ public class TableMaintenanceActionBaseSQLProvider {/*** Binds the Gravitino job run id after {@code runJob}. Keeps {@code finished_at = 0} so the soft- * slot covers the whole run. {@code expectedCreatedAt} fences against a concurrent reclaim that- * CAS-updated {@code created_at}.+ * slot covers the whole run. {@code expectedCreatedAt} fences against a concurrent abandon that+ * closed this row and inserted a new {@code action_id}.*- * @param id action row id+ * @param actionId action row id* @param jobId {@code job_run_meta.job_run_id}* @param expectedCreatedAt claim lease start observed at acquire time* @return UPDATE statement*/public String bindJobId(- @Param("id") long id,+ @Param("actionId") long actionId,@Param("jobId") long jobId,@Param("expectedCreatedAt") long expectedCreatedAt) {return "UPDATE "+ TABLE_NAME+ " SET job_id = #{jobId}"- + " WHERE id = #{id} AND job_id IS NULL AND finished_at = 0"+ + " WHERE action_id = #{actionId} AND job_id IS NULL AND finished_at = 0"+ " AND created_at = #{expectedCreatedAt}";}/**- * @param id action row id+ * @param actionId action row id* @return SELECT statement*/- public String selectById(@Param("id") long id) {- return selectColumns() + " WHERE id = #{id}";+ public String selectById(@Param("actionId") long actionId) {+ return selectColumns() + " WHERE action_id = #{actionId}";}/**@@ -205,96 +205,80 @@ public class TableMaintenanceActionBaseSQLProvider {}/**- * Sets {@code before_snapshot_id} when {@code S0} is sampled ({@code IS NULL} first write).- * Callers treat an already-matching value as an idempotent no-op in Java.+ * Sets {@code before_metrics_id} when {@code S0} is sampled ({@code IS NULL} first write).+ * Requires the soft slot to be bound ({@code job_id IS NOT NULL}) so unbound TTL cannot abandon+ * the row after a successful metrics write.*- * @param jobId Gravitino job run id- * @param tableId table entity id- * @param policyId policy entity id- * @param beforeSnapshotId sampled snapshot id+ * @param actionId action row id+ * @param beforeMetricsId {@code table_snapshot_metrics.metrics_id} for the S0 sample* @return UPDATE statement*/- public String updateBeforeSnapshot(- @Param("jobId") long jobId,- @Param("tableId") long tableId,- @Param("policyId") long policyId,- @Param("beforeSnapshotId") long beforeSnapshotId) {+ public String updateBeforeMetrics(+ @Param("actionId") long actionId, @Param("beforeMetricsId") long beforeMetricsId) {return "UPDATE "+ TABLE_NAME- + " SET before_snapshot_id = #{beforeSnapshotId}"- + " WHERE job_id = #{jobId} AND table_id = #{tableId} AND policy_id = #{policyId}"- + " AND before_snapshot_id IS NULL AND finished_at = 0";+ + " SET before_metrics_id = #{beforeMetricsId}"+ + " WHERE action_id = #{actionId}"+ + " AND job_id IS NOT NULL AND before_metrics_id IS NULL AND finished_at = 0";}/**- * Sets terminal snapshot pointers for one bound table/policy row and releases its soft slot.- *- * <p>Only one in-flight row exists per {@code (table_id, policy_id)} ({@code finished_at = 0}),- * so finish timestamps do not contend across concurrent submitters.+ * Sets {@code after_metrics_id} when {@code S1} is sampled ({@code IS NULL} first write) while+ * the soft slot is still open and bound.*- * @param jobId Gravitino job run id- * @param tableId table entity id- * @param policyId policy entity id- * @param afterSnapshotId terminal snapshot id- * @param finishedAt finish time millis; must be {@code > 0}+ * @param actionId action row id+ * @param afterMetricsId {@code table_snapshot_metrics.metrics_id} for the S1 sample* @return UPDATE statement*/- public String markFinished(- @Param("jobId") long jobId,- @Param("tableId") long tableId,- @Param("policyId") long policyId,- @Param("afterSnapshotId") Long afterSnapshotId,- @Param("finishedAt") long finishedAt) {+ public String updateAfterMetrics(+ @Param("actionId") long actionId, @Param("afterMetricsId") long afterMetricsId) {return "UPDATE "+ TABLE_NAME- + " SET after_snapshot_id = #{afterSnapshotId}, finished_at = #{finishedAt}"- + " WHERE job_id = #{jobId} AND table_id = #{tableId} AND policy_id = #{policyId}"- + " AND finished_at = 0";+ + " SET after_metrics_id = #{afterMetricsId}"+ + " WHERE action_id = #{actionId}"+ + " AND job_id IS NOT NULL AND after_metrics_id IS NULL AND finished_at = 0";}/**- * Backfills a real S1 after failsafe reclaim closed the soft slot with {@code after_snapshot_id}- * still null (finish listener raced after reclaim).+ * Releases the soft slot for one bound action row. Does not write metrics pointers; S0/S1 use+ * {@link #updateBeforeMetrics} / {@link #updateAfterMetrics}.*- * @param jobId Gravitino job run id- * @param tableId table entity id- * @param policyId policy entity id- * @param afterSnapshotId terminal snapshot id; must be non-null+ * <p>Only one in-flight row exists per {@code (table_id, policy_id)} ({@code finished_at = 0}),+ * so finish timestamps do not contend across concurrent submitters.+ *+ * @param actionId action row id+ * @param finishedAt finish time millis; must be {@code > 0}* @return UPDATE statement*/- public String backfillAfterSnapshot(- @Param("jobId") long jobId,- @Param("tableId") long tableId,- @Param("policyId") long policyId,- @Param("afterSnapshotId") long afterSnapshotId) {+ public String markFinished(+ @Param("actionId") long actionId, @Param("finishedAt") long finishedAt) {return "UPDATE "+ TABLE_NAME- + " SET after_snapshot_id = #{afterSnapshotId}"- + " WHERE job_id = #{jobId} AND table_id = #{tableId} AND policy_id = #{policyId}"- + " AND finished_at > 0 AND after_snapshot_id IS NULL";+ + " SET finished_at = #{finishedAt}"+ + " WHERE action_id = #{actionId} AND job_id IS NOT NULL AND finished_at = 0";}/**- * @param id action row id+ * @param actionId action row id* @return DELETE statement*/- public String deleteById(@Param("id") long id) {- return "DELETE FROM " + TABLE_NAME + " WHERE id = #{id}";+ public String deleteById(@Param("actionId") long actionId) {+ return "DELETE FROM " + TABLE_NAME + " WHERE action_id = #{actionId}";}/*** Deletes an unbound claim only when the lease {@code created_at} still matches. A concurrent- * reclaim that CAS-updated {@code created_at} leaves the new owner's row intact.+ * abandon that closed this row leaves the new owner's {@code action_id} intact.*- * @param id action row id+ * @param actionId action row id* @param expectedCreatedAt claim lease start observed at acquire time* @return DELETE statement*/public String deleteUnboundClaim(- @Param("id") long id, @Param("expectedCreatedAt") long expectedCreatedAt) {+ @Param("actionId") long actionId, @Param("expectedCreatedAt") long expectedCreatedAt) {return "DELETE FROM "+ TABLE_NAME- + " WHERE id = #{id} AND job_id IS NULL AND finished_at = 0"+ + " WHERE action_id = #{actionId} AND job_id IS NULL AND finished_at = 0"+ " AND created_at = #{expectedCreatedAt}";}@@ -334,9 +318,9 @@ public class TableMaintenanceActionBaseSQLProvider {}private static String selectColumns() {- return "SELECT id, job_id AS jobId, table_id AS tableId, policy_id AS policyId,"- + " before_snapshot_id AS beforeSnapshotId, after_snapshot_id AS afterSnapshotId,"- + " finished_at AS finishedAt, created_at AS createdAt FROM "+ return "SELECT action_id AS actionId, job_id AS jobId, table_id AS tableId, policy_id AS policyId,"+ + " before_metrics_id AS beforeMetricsId, after_metrics_id AS afterMetricsId,"+ + " created_at AS createdAt, finished_at AS finishedAt FROM "+ TABLE_NAME;}}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/provider/base/TableSnapshotMetricsBaseSQLProvider.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/provider/base/TableSnapshotMetricsBaseSQLProvider.javaindex b3b58ac2fa..ee44cac8e6 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/provider/base/TableSnapshotMetricsBaseSQLProvider.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/mapper/provider/base/TableSnapshotMetricsBaseSQLProvider.java@@ -38,19 +38,13 @@ public class TableSnapshotMetricsBaseSQLProvider {}/**- * @param tableId table id- * @param policyId policy id- * @param snapshotId Iceberg snapshot id+ * @param metricsId metrics row id* @return SELECT statement*/- public String selectMetrics(- @Param("tableId") long tableId,- @Param("policyId") long policyId,- @Param("snapshotId") long snapshotId) {- return "SELECT id, table_id AS tableId, policy_id AS policyId, snapshot_id AS snapshotId,"- + " metrics_value AS metricsValue, created_at AS createdAt FROM "+ public String selectById(@Param("metricsId") long metricsId) {+ return "SELECT metrics_id AS metricsId, table_id AS tableId, policy_id AS policyId,"+ + " snapshot_id AS snapshotId, metrics_value AS metricsValue, created_at AS createdAt FROM "+ TableSnapshotMetricsMapper.TABLE_NAME- + " WHERE table_id = #{tableId} AND policy_id = #{policyId} AND snapshot_id ="- + " #{snapshotId}";+ + " WHERE metrics_id = #{metricsId}";}}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/po/TableMaintenanceActionPO.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/po/TableMaintenanceActionPO.javaindex 1f1928bbae..4a96b8a0ec 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/po/TableMaintenanceActionPO.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/po/TableMaintenanceActionPO.java@@ -37,12 +37,12 @@ import lombok.experimental.Accessors;@AllArgsConstructor(access = AccessLevel.PRIVATE)public class TableMaintenanceActionPO {- private Long id;+ private Long actionId;private Long jobId;private Long tableId;private Long policyId;- private Long beforeSnapshotId;- private Long afterSnapshotId;- private Long finishedAt;+ private Long beforeMetricsId;+ private Long afterMetricsId;private Long createdAt;+ private Long finishedAt;}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/po/TableSnapshotMetricsPO.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/po/TableSnapshotMetricsPO.javaindex 8cb2fd1313..2f745099ac 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/po/TableSnapshotMetricsPO.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/po/TableSnapshotMetricsPO.java@@ -37,7 +37,7 @@ import lombok.experimental.Accessors;@AllArgsConstructor(access = AccessLevel.PRIVATE)public class TableSnapshotMetricsPO {- private Long id;+ private Long metricsId;private Long tableId;private Long policyId;private Long snapshotId;diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/service/OccupancyClaim.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/service/OccupancyClaim.javaindex 5f927329f2..0684f60639 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/service/OccupancyClaim.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/service/OccupancyClaim.java@@ -27,29 +27,30 @@ import java.util.Objects;* and {@link TableMaintenanceActionMetaService#deleteUnboundClaim} without re-reading {@code* created_at} from the row.*- * <p>{@link #id()} is the durable claim token for OccupancyGate follow-ups: make {@code runJob}- * idempotent on this id (or outbox / reconcile-before-reclaim). Binding {@code job_id} alone cannot- * undo a submit that already succeeded after a crash between {@code runJob} and bind.+ * <p>{@link #actionId()} is injected into Spark jobConf. Expired unbound slots are abandoned+ * ({@code finished_at = now}) and replaced with a new row / {@code action_id}, so a stale claim+ * cannot update the successor soft slot. Binding {@code job_id} alone cannot undo a submit that+ * already succeeded after a crash between {@code runJob} and bind.*/public final class OccupancyClaim {- private final long id;+ private final long actionId;private final long createdAt;/**- * @param id {@code table_maintenance_action.id}- * @param createdAt claim lease start written at acquire / reclaim time+ * @param actionId {@code table_maintenance_action.action_id}+ * @param createdAt claim lease start written at acquire time*/- public OccupancyClaim(long id, long createdAt) {- this.id = id;+ public OccupancyClaim(long actionId, long createdAt) {+ this.actionId = actionId;this.createdAt = createdAt;}/*** @return action row id*/- public long id() {- return id;+ public long actionId() {+ return actionId;}/**@@ -68,16 +69,16 @@ public final class OccupancyClaim {return false;}OccupancyClaim that = (OccupancyClaim) o;- return id == that.id && createdAt == that.createdAt;+ return actionId == that.actionId && createdAt == that.createdAt;}@Overridepublic int hashCode() {- return Objects.hash(id, createdAt);+ return Objects.hash(actionId, createdAt);}@Overridepublic String toString() {- return "OccupancyClaim{id=" + id + ", createdAt=" + createdAt + '}';+ return "OccupancyClaim{actionId=" + actionId + ", createdAt=" + createdAt + '}';}}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/service/TableMaintenanceActionMetaService.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/service/TableMaintenanceActionMetaService.javaindex 4451b57cf9..3c08b1bdeb 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/service/TableMaintenanceActionMetaService.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/service/TableMaintenanceActionMetaService.java@@ -55,26 +55,26 @@ public class TableMaintenanceActionMetaService {* Tries to acquire an unbound occupancy claim before {@code runJob}.** <ol>- * <li>CAS-{@code UPDATE created_at} on an expired unbound row ({@code finished_at = 0}), using- * the database clock for lease age- * <li>Otherwise {@code INSERT} with {@code finished_at = 0} and DB {@code created_at}; unique+ * <li>Abandon an expired unbound row by setting {@code finished_at} to the database clock (row+ * is retained; soft slot freed)+ * <li>{@code INSERT} a new row with {@code finished_at = 0} and DB {@code created_at}; unique* conflict means lost race* </ol>** <p>{@code finished_at = 0} is the soft exclusive slot (like {@code deleted_at}); it stays until* {@link #markFinished}. {@code created_at} is the unbound claim lease start from the database- * clock so multi-node TTL does not depend on JVM skew.+ * clock so multi-node TTL does not depend on JVM skew. TTL abandon never reuses {@code+ * action_id}; Spark must be injected with the new id.** <p><b>Submit contract:</b> {@link #bindJobId} only fences the DB bind. It cannot undo a {@code- * runJob} that already succeeded. OccupancyGate / submit follow-ups must make {@code runJob}- * idempotent on {@link OccupancyClaim#id()} (or use an outbox / reconcile-before-reclaim) so a- * reclaim after a crash between submit and bind cannot double-submit Spark work.+ * runJob} that already succeeded. OccupancyGate / submit follow-ups must cancel orphaned Spark+ * work when bind fails so a crash between submit and bind cannot leave dual runners.** @param tableId table entity id* @param policyId policy entity id* @param claimTimeoutMs unbound claim TTL- * @return claim ({@code id} + DB {@code created_at}) when acquired, empty when another live claim- * or open run holds the slot+ * @return claim ({@code action_id} + DB {@code created_at}) when acquired, empty when another+ * live claim or open run holds the slot*/@Monitored(metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,@@ -82,13 +82,9 @@ public class TableMaintenanceActionMetaService {public Optional<OccupancyClaim> tryAcquireInFlight(long tableId, long policyId, long claimTimeoutMs) {Preconditions.checkArgument(claimTimeoutMs > 0, "claimTimeoutMs must be positive");- int reclaimed =- SessionUtils.doWithCommitAndFetchResult(- TableMaintenanceActionMapper.class,- mapper -> mapper.reclaimExpiredUnbound(tableId, policyId, claimTimeoutMs));- if (reclaimed == 1) {- return Optional.of(readUnboundClaim(tableId, policyId));- }+ SessionUtils.doWithCommit(+ TableMaintenanceActionMapper.class,+ mapper -> mapper.reclaimExpiredUnbound(tableId, policyId, claimTimeoutMs));TableMaintenanceActionPO live =SessionUtils.getWithoutCommit(@@ -113,22 +109,19 @@ public class TableMaintenanceActionMetaService {}throw e;}- Preconditions.checkState(actionMeta.id() != null, "insert did not return generated id");TableMaintenanceActionPO inserted =SessionUtils.getWithoutCommit(- TableMaintenanceActionMapper.class, mapper -> mapper.selectById(actionMeta.id()));- Preconditions.checkState(- inserted != null && inserted.createdAt() != null, "insert lost created_at");- return Optional.of(new OccupancyClaim(inserted.id(), inserted.createdAt()));+ TableMaintenanceActionMapper.class, mapper -> mapper.selectById(actionMeta.actionId()));+ return Optional.of(new OccupancyClaim(inserted.actionId(), inserted.createdAt()));}/*** Tries to acquire unbound soft slots for every entry in {@code policyIds} in one transaction* (commit-chain submit).*- * <p>Expired unbound rows are reclaimed first; remaining policies are inserted with a single- * multi-row {@code INSERT}. Any live slot or unique conflict aborts the transaction so the caller- * never holds a partial chain.+ * <p>Expired unbound rows are abandoned ({@code finished_at = now}) first; every policy is then+ * inserted with a single multi-row {@code INSERT} (new {@code action_id}s). Any live slot or+ * unique conflict aborts the transaction so the caller never holds a partial chain.** @param tableId table entity id* @param policyIds chain member policy ids (duplicates collapsed, order preserved)@@ -165,31 +158,19 @@ public class TableMaintenanceActionMetaService {long tableId,List<Long> policyIds,long claimTimeoutMs) {- List<Long> toInsert = new ArrayList<>();for (long policyId : policyIds) {- int reclaimed = mapper.reclaimExpiredUnbound(tableId, policyId, claimTimeoutMs);- if (reclaimed == 1) {- continue;- }+ mapper.reclaimExpiredUnbound(tableId, policyId, claimTimeoutMs);TableMaintenanceActionPO live =mapper.selectLiveUnboundByTableAndPolicy(tableId, policyId, claimTimeoutMs);if (live != null) {throw new SoftSlotBusyException();}- toInsert.add(policyId);- }- if (!toInsert.isEmpty()) {- mapper.insertActions(tableId, toInsert);}+ mapper.insertActions(tableId, policyIds);List<OccupancyClaim> claims = new ArrayList<>(policyIds.size());for (long policyId : policyIds) {TableMaintenanceActionPO unbound = mapper.selectUnboundByTableAndPolicy(tableId, policyId);- Preconditions.checkState(- unbound != null && unbound.id() != null && unbound.createdAt() != null,- "batch acquire lost unbound row for table %s policy %s",- tableId,- policyId);- claims.add(new OccupancyClaim(unbound.id(), unbound.createdAt()));+ claims.add(new OccupancyClaim(unbound.actionId(), unbound.createdAt()));}return claims;}@@ -250,11 +231,11 @@ public class TableMaintenanceActionMetaService {int updated =SessionUtils.doWithCommitAndFetchResult(TableMaintenanceActionMapper.class,- mapper -> mapper.bindJobId(claim.id(), jobId, claim.createdAt()));+ mapper -> mapper.bindJobId(claim.actionId(), jobId, claim.createdAt()));if (updated == 1) {return;}- TableMaintenanceActionPO current = getById(claim.id());+ TableMaintenanceActionPO current = getById(claim.actionId());if (current != null&& Objects.equals(current.jobId(), jobId)&& current.finishedAt() != null@@ -269,12 +250,14 @@ public class TableMaintenanceActionMetaService {/*** Lazy-binds {@code jobId} onto the unbound in-flight claim for {@code (tableId, policyId)}.*- * <p>Used when a Spark metrics/finish callback arrives before submit-side {@link #bindJobId}.- * Does nothing (returns {@code false}) when there is no unbound row for that pair.+ * <p><b>Not for Spark callbacks.</b> Callbacks must address the soft slot by the injected {@code+ * action_id} ({@link #getById} / metrics APIs). Ownership must not be inferred from {@code+ * (table_id, policy_id)} after TTL reclaim (old row finished, new {@code action_id}). Kept for+ * tests and rare control-plane repair; submit-side {@link #bindJobId} remains the normal path.*- * @param tableId table entity id from the callback- * @param policyId policy entity id from the callback- * @param jobId Gravitino job run id from the callback path+ * @param tableId table entity id+ * @param policyId policy entity id+ * @param jobId Gravitino job run id* @return {@code true} when a row is now bound to {@code jobId}*/@Monitored(@@ -289,11 +272,11 @@ public class TableMaintenanceActionMetaService {SessionUtils.getWithoutCommit(TableMaintenanceActionMapper.class,mapper -> mapper.selectUnboundByTableAndPolicy(tableId, policyId));- if (unbound == null || unbound.id() == null || unbound.createdAt() == null) {+ if (unbound == null || unbound.actionId() == null || unbound.createdAt() == null) {return false;}try {- bindJobId(new OccupancyClaim(unbound.id(), unbound.createdAt()), jobId);+ bindJobId(new OccupancyClaim(unbound.actionId(), unbound.createdAt()), jobId);return true;} catch (IllegalStateException e) {TableMaintenanceActionPO bound = getByJobIdAndTableIdAndPolicyId(jobId, tableId, policyId);@@ -321,26 +304,26 @@ public class TableMaintenanceActionMetaService {mapper -> {for (OccupancyClaim claim : claims) {Preconditions.checkNotNull(claim, "claim must not be null");- int updated = mapper.bindJobId(claim.id(), jobId, claim.createdAt());+ int updated = mapper.bindJobId(claim.actionId(), jobId, claim.createdAt());if (updated == 1) {continue;}- TableMaintenanceActionPO current = mapper.selectById(claim.id());+ TableMaintenanceActionPO current = mapper.selectById(claim.actionId());Preconditions.checkState(current != null&& Objects.equals(current.jobId(), jobId)&& current.finishedAt() != null&& current.finishedAt() == 0L,"expected to bind job_id on claim id=%s, updated=%s",- claim.id(),+ claim.actionId(),updated);}});}/**- * Releases unbound claims after a failed submit. Each delete is fenced on {@code (id,- * created_at)} so a concurrent reclaim's live claim is not removed.+ * Releases unbound claims after a failed submit. Each delete is fenced on {@code (action_id,+ * created_at)} so a concurrent abandon's new soft slot is not removed.** @param claims claims to release*/@@ -356,28 +339,17 @@ public class TableMaintenanceActionMetaService {}}- private static OccupancyClaim readUnboundClaim(long tableId, long policyId) {- TableMaintenanceActionPO unbound =- SessionUtils.getWithoutCommit(- TableMaintenanceActionMapper.class,- mapper -> mapper.selectUnboundByTableAndPolicy(tableId, policyId));- Preconditions.checkState(- unbound != null && unbound.id() != null && unbound.createdAt() != null,- "reclaim lost unbound row");- return new OccupancyClaim(unbound.id(), unbound.createdAt());- }-/**- * @param id action row id+ * @param actionId action row id* @return action row or null*/@Nullable@Monitored(metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,baseMetricName = "getTableMaintenanceActionById")- public TableMaintenanceActionPO getById(long id) {+ public TableMaintenanceActionPO getById(long actionId) {return SessionUtils.getWithoutCommit(- TableMaintenanceActionMapper.class, mapper -> mapper.selectById(id));+ TableMaintenanceActionMapper.class, mapper -> mapper.selectById(actionId));}/**@@ -455,93 +427,105 @@ public class TableMaintenanceActionMetaService {}/**- * Records the sampled Iceberg snapshot id ({@code S0}) for a running action on one table/policy.+ * Records the S0 metrics row id for a bound in-flight action.*- * <p>Safe to retry with the same {@code beforeSnapshotId} (cron / in-job re-entry after a partial- * sample). A different snapshot id on an already-set row fails.+ * <p>Requires {@code job_id IS NOT NULL} and {@code finished_at = 0}. Safe to retry with the same+ * {@code beforeMetricsId}. A different metrics id on an already-set row fails.*- * @param jobId Gravitino job run id- * @param tableId table entity id- * @param policyId policy entity id- * @param beforeSnapshotId sampled snapshot id+ * @param actionId action row id+ * @param beforeMetricsId {@code table_snapshot_metrics.metrics_id} for S0+ */+ @Monitored(+ metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,+ baseMetricName = "recordTableMaintenanceActionBeforeMetrics")+ public void recordBeforeMetrics(long actionId, long beforeMetricsId) {+ int updated =+ SessionUtils.doWithCommitAndFetchResult(+ TableMaintenanceActionMapper.class,+ mapper -> mapper.updateBeforeMetrics(actionId, beforeMetricsId));+ if (updated == 1) {+ return;+ }+ TableMaintenanceActionPO current = getById(actionId);+ Preconditions.checkState(+ current != null+ && current.jobId() != null+ && current.finishedAt() != null+ && current.finishedAt() == 0L,+ "expected a bound unfinished action for action_id=%s",+ actionId);+ Preconditions.checkState(+ current.beforeMetricsId() != null && current.beforeMetricsId() == beforeMetricsId,+ "before_metrics_id already set to %s, refusing %s",+ current.beforeMetricsId(),+ beforeMetricsId);+ }++ /**+ * Records the S1 metrics row id for a bound in-flight action.+ *+ * <p>Safe to retry with the same {@code afterMetricsId}. A different metrics id on an already-set+ * row fails.+ *+ * @param actionId action row id+ * @param afterMetricsId {@code table_snapshot_metrics.metrics_id} for S1*/@Monitored(metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,- baseMetricName = "recordTableMaintenanceActionBeforeSnapshot")- public void recordBeforeSnapshot(long jobId, long tableId, long policyId, long beforeSnapshotId) {+ baseMetricName = "recordTableMaintenanceActionAfterMetrics")+ public void recordAfterMetrics(long actionId, long afterMetricsId) {int updated =SessionUtils.doWithCommitAndFetchResult(TableMaintenanceActionMapper.class,- mapper -> mapper.updateBeforeSnapshot(jobId, tableId, policyId, beforeSnapshotId));+ mapper -> mapper.updateAfterMetrics(actionId, afterMetricsId));if (updated == 1) {return;}- TableMaintenanceActionPO current = getByJobIdAndTableIdAndPolicyId(jobId, tableId, policyId);+ TableMaintenanceActionPO current = getById(actionId);Preconditions.checkState(- current != null && current.finishedAt() != null && current.finishedAt() == 0L,- "expected an unfinished action for job_id=%s table_id=%s policy_id=%s",- jobId,- tableId,- policyId);+ current != null+ && current.jobId() != null+ && current.finishedAt() != null+ && current.finishedAt() == 0L,+ "expected a bound unfinished action for action_id=%s",+ actionId);Preconditions.checkState(- current.beforeSnapshotId() != null && current.beforeSnapshotId() == beforeSnapshotId,- "before_snapshot_id already set to %s, refusing %s",- current.beforeSnapshotId(),- beforeSnapshotId);+ current.afterMetricsId() != null && current.afterMetricsId() == afterMetricsId,+ "after_metrics_id already set to %s, refusing %s",+ current.afterMetricsId(),+ afterMetricsId);}/**- * Marks one in-flight action finished for {@code (jobId, tableId, policyId)}.+ * Marks one bound in-flight action finished by {@code action_id}.** <p>{@code UNIQUE(table_id, policy_id, finished_at)} exists so {@code finished_at = 0} is a* single soft slot per pair (like {@code deleted_at}). Only one in-flight row can finish that* pair at a time, so two completed rows cannot race to the same millisecond {@code finished_at}.*- * <p>If the row was already closed with a null after snapshot, a later call may still backfill a- * real S1 when {@code afterSnapshotId} is non-null. Safe to retry when the row is already- * finished with a null after and {@code afterSnapshotId} is also null.+ * <p>Does not write metrics pointers; call {@link #recordBeforeMetrics} / {@link+ * #recordAfterMetrics} separately when sampling. Safe to retry when the row is already finished.*- * @param jobId Gravitino job run id- * @param tableId table entity id- * @param policyId policy entity id- * @param afterSnapshotId terminal snapshot id, or null when releasing without an S1+ * @param actionId action row id* @param finishedAt finish timestamp millis*/@Monitored(metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,baseMetricName = "markTableMaintenanceActionFinished")- public void markFinished(- long jobId, long tableId, long policyId, Long afterSnapshotId, long finishedAt) {+ public void markFinished(long actionId, long finishedAt) {Preconditions.checkArgument(finishedAt > 0, "finishedAt must be positive");int updated =SessionUtils.doWithCommitAndFetchResult(TableMaintenanceActionMapper.class,- mapper -> mapper.markFinished(jobId, tableId, policyId, afterSnapshotId, finishedAt));+ mapper -> mapper.markFinished(actionId, finishedAt));if (updated == 1) {return;}- if (afterSnapshotId != null) {- int backfilled =- SessionUtils.doWithCommitAndFetchResult(- TableMaintenanceActionMapper.class,- mapper -> mapper.backfillAfterSnapshot(jobId, tableId, policyId, afterSnapshotId));- Preconditions.checkState(- backfilled == 1,- "expected to finish or backfill action for job_id=%s table_id=%s policy_id=%s, finished=%s, backfilled=%s",- jobId,- tableId,- policyId,- updated,- backfilled);- return;- }- TableMaintenanceActionPO current = getByJobIdAndTableIdAndPolicyId(jobId, tableId, policyId);+ TableMaintenanceActionPO current = getById(actionId);Preconditions.checkState(current != null && current.finishedAt() != null && current.finishedAt() > 0L,- "expected finished action for job_id=%s table_id=%s policy_id=%s, updated=%s",- jobId,- tableId,- policyId,+ "expected finished action for action_id=%s, updated=%s",+ actionId,updated);}@@ -549,21 +533,22 @@ public class TableMaintenanceActionMetaService {* Deletes the {@code table_maintenance_action} row. Does not delete {@code* table_snapshot_metrics}; metrics are retained for TTL/N cleanup.*- * @param id action row id+ * @param actionId action row id*/@Monitored(metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,baseMetricName = "deleteTableMaintenanceActionById")- public void deleteById(long id) {- SessionUtils.doWithCommit(TableMaintenanceActionMapper.class, mapper -> mapper.deleteById(id));+ public void deleteById(long actionId) {+ SessionUtils.doWithCommit(+ TableMaintenanceActionMapper.class, mapper -> mapper.deleteById(actionId));}/*** Releases an unbound occupancy claim when submit / bind fails.*- * <p>Deletes only when {@code (id, created_at)} still match and the row is unbound. A concurrent- * reclaim that CAS-updated {@code created_at} leaves the new owner's live claim intact (returns- * {@code false}).+ * <p>Deletes only when {@code (action_id, created_at)} still match and the row is unbound. A+ * concurrent abandon that closed this row leaves the successor soft slot intact (returns {@code+ * false}).** @param claim claim returned by {@link #tryAcquireInFlight} / {@link #insertInFlight}* @return {@code true} when this claim lease was deleted@@ -576,7 +561,7 @@ public class TableMaintenanceActionMetaService {int deleted =SessionUtils.doWithCommitAndFetchResult(TableMaintenanceActionMapper.class,- mapper -> mapper.deleteUnboundClaim(claim.id(), claim.createdAt()));+ mapper -> mapper.deleteUnboundClaim(claim.actionId(), claim.createdAt()));return deleted == 1;}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/service/TableSnapshotMetricsMetaService.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/service/TableSnapshotMetricsMetaService.javaindex fe7b0719d2..37643f25ec 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/service/TableSnapshotMetricsMetaService.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/service/TableSnapshotMetricsMetaService.java@@ -20,8 +20,6 @@ package org.apache.gravitino.maintenance.storage.service;import static org.apache.gravitino.metrics.source.MetricsSource.GRAVITINO_RELATIONAL_STORE_METRIC_NAME;-import java.sql.SQLIntegrityConstraintViolationException;-import java.util.Locale;import javax.annotation.Nullable;import org.apache.gravitino.maintenance.storage.mapper.TableSnapshotMetricsMapper;import org.apache.gravitino.maintenance.storage.po.TableSnapshotMetricsPO;@@ -44,24 +42,19 @@ public class TableSnapshotMetricsMetaService {}/**- * Idempotently stores metrics JSON for a table/policy/snapshot triple. If a row already exists,- * this is a no-op (does not overwrite) so sample / listener retries are safe.- *- * <p>A concurrent insert that loses the unique-key race is treated as success (first writer- * wins).+ * Inserts a metrics row and returns its generated id. The same Iceberg {@code snapshotId} may be+ * stored more than once (S0 and S1 can share a snapshot).** @param tableId table id* @param policyId policy id- * @param snapshotId Iceberg snapshot id+ * @param snapshotId Iceberg snapshot id sampled with these metrics* @param metricsJson serialized metrics payload+ * @return generated {@code table_snapshot_metrics.metrics_id}*/@Monitored(metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,baseMetricName = "insertTableSnapshotMetrics")- public void insertMetrics(long tableId, long policyId, long snapshotId, String metricsJson) {- if (getMetrics(tableId, policyId, snapshotId) != null) {- return;- }+ public long insertMetrics(long tableId, long policyId, long snapshotId, String metricsJson) {TableSnapshotMetricsPO metricsMeta =TableSnapshotMetricsPO.builder().withTableId(tableId)@@ -70,46 +63,21 @@ public class TableSnapshotMetricsMetaService {.withMetricsValue(metricsJson).withCreatedAt(System.currentTimeMillis()).build();- try {- SessionUtils.doWithCommit(- TableSnapshotMetricsMapper.class, mapper -> mapper.insertMetrics(metricsMeta));- } catch (RuntimeException e) {- if (isUniqueViolation(e)) {- return;- }- throw e;- }+ SessionUtils.doWithCommit(+ TableSnapshotMetricsMapper.class, mapper -> mapper.insertMetrics(metricsMeta));+ return metricsMeta.metricsId();}/**- * @param tableId table id- * @param policyId policy id- * @param snapshotId snapshot id+ * @param metricsId metrics row id* @return stored metrics or null*/@Nullable@Monitored(metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,- baseMetricName = "getTableSnapshotMetrics")- public TableSnapshotMetricsPO getMetrics(long tableId, long policyId, long snapshotId) {+ baseMetricName = "getTableSnapshotMetricsById")+ public TableSnapshotMetricsPO getMetrics(long metricsId) {return SessionUtils.getWithoutCommit(- TableSnapshotMetricsMapper.class,- mapper -> mapper.selectMetrics(tableId, policyId, snapshotId));- }-- private static boolean isUniqueViolation(Throwable throwable) {- for (Throwable t = throwable; t != null; t = t.getCause()) {- if (t instanceof SQLIntegrityConstraintViolationException) {- return true;- }- String message = t.getMessage();- if (message != null) {- String lower = message.toLowerCase(Locale.ROOT);- if (lower.contains("unique") || lower.contains("duplicate")) {- return true;- }- }- }- return false;+ TableSnapshotMetricsMapper.class, mapper -> mapper.selectById(metricsId));}}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/web/rest/TableMaintenanceActionOperations.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/web/rest/TableMaintenanceActionOperations.javaindex c069d22dad..937ec77d3d 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/web/rest/TableMaintenanceActionOperations.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/web/rest/TableMaintenanceActionOperations.java@@ -76,16 +76,16 @@ public class TableMaintenanceActionOperations {}/**- * Persists S0 metrics and {@code before_snapshot_id} for the action bound to {@code jobId}.+ * Persists S0 metrics and {@code before_metrics_id} for {@code actionId}.** @param metalake metalake name from the request path- * @param jobId Gravitino job run id bound to the action+ * @param actionId maintenance action id injected at submit* @param finish when {@code true}, close the soft slot after storing metrics* @param request metrics payload* @return empty success response*/@POST- @Path("{jobId}/metrics/before")+ @Path("{actionId}/metrics/before")@Timed(name = "maintenance-action-metrics-before." + MetricNames.HTTP_PROCESS_DURATION,absolute = true)@@ -94,32 +94,32 @@ public class TableMaintenanceActionOperations {public Response reportBeforeMetrics(@PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)String metalake,- @PathParam("jobId") long jobId,+ @PathParam("actionId") long actionId,@QueryParam("finish") @DefaultValue("false") boolean finish,MaintenanceActionMetricsRequest request) {return TableMaintenanceRESTUtils.doAs(httpRequest,() -> {requireBody(request);- metricsService.reportBeforeMetrics(metalake, jobId, finish, request);+ metricsService.reportBeforeMetrics(metalake, actionId, finish, request);return TableMaintenanceRESTUtils.ok(new BaseResponse());},"report-before-metrics",- jobId,+ actionId,metalake);}/**- * Persists S1 metrics for the action bound to {@code jobId}.+ * Persists S1 metrics for {@code actionId}.** @param metalake metalake name from the request path- * @param jobId Gravitino job run id bound to the action+ * @param actionId maintenance action id injected at submit* @param finish when {@code true}, close the soft slot after storing metrics* @param request metrics payload* @return empty success response*/@POST- @Path("{jobId}/metrics/after")+ @Path("{actionId}/metrics/after")@Timed(name = "maintenance-action-metrics-after." + MetricNames.HTTP_PROCESS_DURATION,absolute = true)@@ -128,48 +128,48 @@ public class TableMaintenanceActionOperations {public Response reportAfterMetrics(@PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)String metalake,- @PathParam("jobId") long jobId,+ @PathParam("actionId") long actionId,@QueryParam("finish") @DefaultValue("false") boolean finish,MaintenanceActionMetricsRequest request) {return TableMaintenanceRESTUtils.doAs(httpRequest,() -> {requireBody(request);- metricsService.reportAfterMetrics(metalake, jobId, finish, request);+ metricsService.reportAfterMetrics(metalake, actionId, finish, request);return TableMaintenanceRESTUtils.ok(new BaseResponse());},"report-after-metrics",- jobId,+ actionId,metalake);}/**- * Closes the soft slot for one bound table without writing metrics.+ * Closes the soft slot for one bound action without writing metrics.** @param metalake metalake name from the request path- * @param jobId Gravitino job run id bound to the action+ * @param actionId maintenance action id injected at submit* @param request finish payload* @return empty success response*/@POST- @Path("{jobId}/finish")+ @Path("{actionId}/finish")@Timed(name = "maintenance-action-finish." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)@ResponseMetered(name = "maintenance-action-finish", absolute = true)@AuthorizationExpression(expression = "METALAKE::OWNER || METALAKE::RUN_JOB")public Response finishAction(@PathParam("metalake") @AuthorizationMetadata(type = Entity.EntityType.METALAKE)String metalake,- @PathParam("jobId") long jobId,+ @PathParam("actionId") long actionId,MaintenanceActionFinishRequest request) {return TableMaintenanceRESTUtils.doAs(httpRequest,() -> {requireBody(request);- metricsService.finishAction(metalake, jobId, request);+ metricsService.finishAction(metalake, actionId, request);return TableMaintenanceRESTUtils.ok(new BaseResponse());},"finish",- jobId,+ actionId,metalake);}diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestTableMaintenanceInJobPipeline.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestTableMaintenanceInJobPipeline.javaindex c4cfbe9e56..8247cf6768 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestTableMaintenanceInJobPipeline.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestTableMaintenanceInJobPipeline.java@@ -20,6 +20,7 @@package org.apache.gravitino.maintenance.injob;import org.apache.gravitino.maintenance.TableMaintenanceConfig;+import org.apache.gravitino.maintenance.storage.service.OccupancyClaim;import org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService;import org.apache.gravitino.maintenance.storage.service.TableSnapshotMetricsMetaService;import org.apache.gravitino.storage.relational.TestJDBCBackend;@@ -51,30 +52,27 @@ class TestTableMaintenanceInJobPipeline extends TestJDBCBackend {@TestTemplatevoid testContinuesWhenNoDriftAndRecommenderMaintains() {- long jobId = 2001L;- insertBoundAction(jobId, 10L, 20L);+ long actionId = insertBoundAction(2001L, 10L, 20L);InJobGateOutcome outcome =- maintainPipeline.gateCronJob(jobId, 10L, 20L, 100L, METRICS_JSON, () -> 100L);+ maintainPipeline.gateCronJob(actionId, 10L, 20L, 100L, METRICS_JSON, () -> 100L);Assertions.assertTrue(outcome.continueMaintenance());Assertions.assertNull(outcome.stopReason());}@TestTemplatevoid testStopsOnDriftBeforeRecommend() {- long jobId = 2002L;- insertBoundAction(jobId, 11L, 21L);+ long actionId = insertBoundAction(2002L, 11L, 21L);InJobGateOutcome outcome =- maintainPipeline.gateCronJob(jobId, 11L, 21L, 200L, METRICS_JSON, () -> 201L);+ maintainPipeline.gateCronJob(actionId, 11L, 21L, 200L, METRICS_JSON, () -> 201L);Assertions.assertFalse(outcome.continueMaintenance());Assertions.assertEquals(InJobGateOutcome.StopReason.SNAPSHOT_DRIFT, outcome.stopReason());}@TestTemplatevoid testStopsWhenRecommenderSkips() {- long jobId = 2003L;- insertBoundAction(jobId, 12L, 22L);+ long actionId = insertBoundAction(2003L, 12L, 22L);InJobGateOutcome outcome =- skipPipeline.gateCronJob(jobId, 12L, 22L, 300L, METRICS_JSON, () -> 300L);+ skipPipeline.gateCronJob(actionId, 12L, 22L, 300L, METRICS_JSON, () -> 300L);Assertions.assertFalse(outcome.continueMaintenance());Assertions.assertEquals(InJobGateOutcome.StopReason.RECOMMENDER_SKIP, outcome.stopReason());}@@ -90,10 +88,11 @@ class TestTableMaintenanceInJobPipeline extends TestJDBCBackend {Assertions.assertEquals(InJobGateOutcome.StopReason.RECOMMENDER_SKIP, skip.stopReason());}- private void insertBoundAction(long jobId, long tableId, long policyId) {- actionMetaService.bindJobId(+ private long insertBoundAction(long jobId, long tableId, long policyId) {+ OccupancyClaim claim =actionMetaService.insertInFlight(- tableId, policyId, TableMaintenanceConfig.DEFAULT_CLAIM_TIMEOUT_MS),- jobId);+ tableId, policyId, TableMaintenanceConfig.DEFAULT_CLAIM_TIMEOUT_MS);+ actionMetaService.bindJobId(claim, jobId);+ return claim.actionId();}}diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestTableMaintenanceInJobSampler.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestTableMaintenanceInJobSampler.javaindex 8be445761a..d7451327b7 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestTableMaintenanceInJobSampler.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestTableMaintenanceInJobSampler.java@@ -21,6 +21,7 @@ package org.apache.gravitino.maintenance.injob;import org.apache.gravitino.maintenance.TableMaintenanceConfig;import org.apache.gravitino.maintenance.storage.po.TableSnapshotMetricsPO;+import org.apache.gravitino.maintenance.storage.service.OccupancyClaim;import org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService;import org.apache.gravitino.maintenance.storage.service.TableSnapshotMetricsMetaService;import org.apache.gravitino.storage.relational.TestJDBCBackend;@@ -45,47 +46,46 @@ class TestTableMaintenanceInJobSampler extends TestJDBCBackend {@TestTemplatevoid testCronJobSamplePersistsAndContinuesWhenNoDrift() {- long jobId = 1001L;- insertBoundAction(jobId, 1L, 2L);+ long actionId = insertBoundAction(1001L, 1L, 2L);InJobGateOutcome outcome =- sampler.sampleAndGateCronJob(jobId, 1L, 2L, 100L, METRICS_JSON, () -> 100L);+ sampler.sampleAndGateCronJob(actionId, 1L, 2L, 100L, METRICS_JSON, () -> 100L);Assertions.assertTrue(outcome.continueMaintenance());Assertions.assertNull(outcome.stopReason());- TableSnapshotMetricsPO stored = metricsMetaService.getMetrics(1L, 2L, 100L);+ long metricsId = actionMetaService.getById(actionId).beforeMetricsId();+ TableSnapshotMetricsPO stored = metricsMetaService.getMetrics(metricsId);Assertions.assertNotNull(stored);Assertions.assertEquals(METRICS_JSON, stored.metricsValue());- Assertions.assertEquals(100L, actionMetaService.getByJobId(jobId).beforeSnapshotId());+ Assertions.assertEquals(100L, stored.snapshotId());}@TestTemplatevoid testCronJobEndsEarlyWhenSnapshotDriftsAfterSample() {- long jobId = 1002L;- insertBoundAction(jobId, 3L, 4L);+ long actionId = insertBoundAction(1002L, 3L, 4L);InJobGateOutcome outcome =- sampler.sampleAndGateCronJob(jobId, 3L, 4L, 200L, METRICS_JSON, () -> 201L);+ sampler.sampleAndGateCronJob(actionId, 3L, 4L, 200L, METRICS_JSON, () -> 201L);Assertions.assertFalse(outcome.continueMaintenance());Assertions.assertEquals(InJobGateOutcome.StopReason.SNAPSHOT_DRIFT, outcome.stopReason());Assertions.assertEquals(200L, outcome.sampledSnapshotId());Assertions.assertEquals(201L, outcome.headSnapshotId());- Assertions.assertNotNull(metricsMetaService.getMetrics(3L, 4L, 200L));+ long metricsId = actionMetaService.getById(actionId).beforeMetricsId();+ Assertions.assertNotNull(metricsMetaService.getMetrics(metricsId));}@TestTemplatevoid testCronJobSampleRetryWithSameS0IsIdempotent() {- long jobId = 1003L;- insertBoundAction(jobId, 5L, 6L);+ long actionId = insertBoundAction(1003L, 5L, 6L);InJobGateOutcome first =- sampler.sampleAndGateCronJob(jobId, 5L, 6L, 300L, METRICS_JSON, () -> 300L);+ sampler.sampleAndGateCronJob(actionId, 5L, 6L, 300L, METRICS_JSON, () -> 300L);+ long metricsId = actionMetaService.getById(actionId).beforeMetricsId();InJobGateOutcome retry =- sampler.sampleAndGateCronJob(jobId, 5L, 6L, 300L, "{\"mse\":9}", () -> 300L);+ sampler.sampleAndGateCronJob(actionId, 5L, 6L, 300L, "{\"mse\":9}", () -> 300L);Assertions.assertTrue(first.continueMaintenance());Assertions.assertTrue(retry.continueMaintenance());- Assertions.assertEquals(- METRICS_JSON, metricsMetaService.getMetrics(5L, 6L, 300L).metricsValue());- Assertions.assertEquals(300L, actionMetaService.getByJobId(jobId).beforeSnapshotId());+ Assertions.assertEquals(metricsId, actionMetaService.getById(actionId).beforeMetricsId());+ Assertions.assertEquals(METRICS_JSON, metricsMetaService.getMetrics(metricsId).metricsValue());}@TestTemplate@@ -98,10 +98,11 @@ class TestTableMaintenanceInJobSampler extends TestJDBCBackend {Assertions.assertEquals(InJobGateOutcome.StopReason.SNAPSHOT_DRIFT, drift.stopReason());}- private void insertBoundAction(long jobId, long tableId, long policyId) {- actionMetaService.bindJobId(+ private long insertBoundAction(long jobId, long tableId, long policyId) {+ OccupancyClaim claim =actionMetaService.insertInFlight(- tableId, policyId, TableMaintenanceConfig.DEFAULT_CLAIM_TIMEOUT_MS),- jobId);+ tableId, policyId, TableMaintenanceConfig.DEFAULT_CLAIM_TIMEOUT_MS);+ actionMetaService.bindJobId(claim, jobId);+ return claim.actionId();}}diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/integration/test/IrcToCommitEnqueueIT.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/integration/test/IrcToCommitEnqueueIT.javaindex cacc011b41..d2628331a6 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/integration/test/IrcToCommitEnqueueIT.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/integration/test/IrcToCommitEnqueueIT.java@@ -138,8 +138,8 @@ public class IrcToCommitEnqueueIT extends BaseIT {assertNotNull(spec);assertTrue(spec.isValid());assertEquals(List.of(seeded.tableId), spec.tableIds());- assertEquals(seeded.policyId, spec.getOperations().get(0).getPolicyId());- assertTrue(spec.getJobConf().containsKey("updater_options"));+ assertEquals(seeded.policyId, spec.getTasks().get(0).getPolicyId());+ assertTrue(spec.getUpdaterOptions() != null && !spec.getUpdaterOptions().isBlank());}private static IcebergUpdateTableEvent icebergUpdateTableEvent(NameIdentifier tableId) {diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/integration/test/PolicyExpandToCronIT.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/integration/test/PolicyExpandToCronIT.javaindex 5aef4eaa81..8a7b41c3d3 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/integration/test/PolicyExpandToCronIT.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/integration/test/PolicyExpandToCronIT.java@@ -131,11 +131,11 @@ public class PolicyExpandToCronIT extends BaseIT {assertNotNull(spec);assertTrue(spec.isValid());assertEquals(List.of(seeded.tableId), spec.tableIds());- assertEquals(seeded.policyId, spec.getOperations().get(0).getPolicyId());- assertTrue(spec.getJobConf().containsKey("updater_options"));- assertEquals(seeded.catalogName, spec.getTables().get(0).catalogName());+ assertEquals(seeded.policyId, spec.getTasks().get(0).getPolicyId());+ assertTrue(spec.getUpdaterOptions() != null && !spec.getUpdaterOptions().isBlank());+ assertEquals(seeded.catalogName, spec.getTasks().get(0).catalogName());assertEquals(- seeded.schemaName + "." + seeded.tableName, spec.getTables().get(0).sparkTableIdentifier());+ seeded.schemaName + "." + seeded.tableName, spec.getTasks().get(0).tableIdentifier());}private static void awaitCronCapture(String expectedInstanceId, long timeoutSeconds)diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/integration/test/TableMaintenanceActionRESTIT.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/integration/test/TableMaintenanceActionRESTIT.javaindex a28a20a240..75f8d99757 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/integration/test/TableMaintenanceActionRESTIT.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/integration/test/TableMaintenanceActionRESTIT.java@@ -135,6 +135,8 @@ public class TableMaintenanceActionRESTIT extends BaseIT {actions.insertInFlight(tableId, policyId, TableMaintenanceConfig.forTest(1, 1, 1, 500L, 1_000L, 4, 10));assertNotNull(claim);+ actions.bindJobId(claim, jobId);+ long actionId = claim.actionId();String beforeBody ="{\"tableId\":"@@ -142,20 +144,24 @@ public class TableMaintenanceActionRESTIT extends BaseIT {+ ",\"policyId\":"+ policyId+ ",\"snapshotId\":100,\"metricsJson\":\"{\\\"mse\\\":1}\"}";- HttpResponse<String> before = postJson(actionPath(jobId, "metrics/before"), beforeBody);+ HttpResponse<String> before = postJson(actionPath(actionId, "metrics/before"), beforeBody);assertEquals(200, before.statusCode(), before.body());- TableMaintenanceActionPO afterBefore =- actions.getByJobIdAndTableIdAndPolicyId(jobId, tableId, policyId);+ TableMaintenanceActionPO afterBefore = actions.getById(actionId);assertNotNull(afterBefore);assertEquals(jobId, afterBefore.jobId());- assertEquals(100L, afterBefore.beforeSnapshotId());+ assertNotNull(afterBefore.beforeMetricsId());assertEquals(0L, afterBefore.finishedAt());assertEquals("{\"mse\":1}",TableSnapshotMetricsMetaService.getInstance()- .getMetrics(tableId, policyId, 100L)+ .getMetrics(afterBefore.beforeMetricsId()).metricsValue());+ assertEquals(+ 100L,+ TableSnapshotMetricsMetaService.getInstance()+ .getMetrics(afterBefore.beforeMetricsId())+ .snapshotId());String afterBody ="{\"tableId\":"@@ -164,23 +170,27 @@ public class TableMaintenanceActionRESTIT extends BaseIT {+ policyId+ ",\"snapshotId\":200,\"metricsJson\":\"{\\\"mse\\\":2}\"}";HttpResponse<String> after =- postJson(actionPath(jobId, "metrics/after") + "?finish=true", afterBody);+ postJson(actionPath(actionId, "metrics/after") + "?finish=true", afterBody);assertEquals(200, after.statusCode(), after.body());- TableMaintenanceActionPO finished =- actions.getByJobIdAndTableIdAndPolicyId(jobId, tableId, policyId);+ TableMaintenanceActionPO finished = actions.getById(actionId);assertNotNull(finished);- assertEquals(200L, finished.afterSnapshotId());+ assertNotNull(finished.afterMetricsId());assertTrue(finished.finishedAt() > 0L);assertEquals("{\"mse\":2}",TableSnapshotMetricsMetaService.getInstance()- .getMetrics(tableId, policyId, 200L)+ .getMetrics(finished.afterMetricsId()).metricsValue());+ assertEquals(+ 200L,+ TableSnapshotMetricsMetaService.getInstance()+ .getMetrics(finished.afterMetricsId())+ .snapshotId());}- private static String actionPath(long jobId, String suffix) {- return apiBase + "/metalakes/" + metalake + "/maintenance/actions/" + jobId + "/" + suffix;+ private static String actionPath(long actionId, String suffix) {+ return apiBase + "/metalakes/" + metalake + "/maintenance/actions/" + actionId + "/" + suffix;}private static HttpResponse<String> postJson(String url, String body) throws Exception {diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/occupancy/TestOccupancyGate.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/occupancy/TestOccupancyGate.javaindex def7654432..a8376c15da 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/occupancy/TestOccupancyGate.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/occupancy/TestOccupancyGate.java@@ -62,7 +62,7 @@ class TestOccupancyGate extends TestJDBCBackend {gate.shouldSkip(table.id(), policyId, 3_600_000L, System.currentTimeMillis()));long finishedAt = System.currentTimeMillis();- actions.markFinished(7001L, table.id(), policyId, 200L, finishedAt);+ actions.markFinished(claim.actionId(), finishedAt);Assertions.assertFalse(gate.isInFlight(table.id(), policyId));Assertions.assertEquals(finishedAt, actions.getByJobIdAndTableId(7001L, table.id()).finishedAt());@@ -86,7 +86,7 @@ class TestOccupancyGate extends TestJDBCBackend {long jobId = 8001L;actions.bindJobId(claim, jobId);long finishedAt = 1_700_000_000_000L;- actions.markFinished(jobId, table.id(), policyId, null, finishedAt);+ actions.markFinished(claim.actionId(), finishedAt);Assertions.assertTrue(gate.withinMinInterval(table.id(), policyId, 60_000L, finishedAt + 1_000L));@@ -119,7 +119,7 @@ class TestOccupancyGate extends TestJDBCBackend {Assertions.assertFalse(gate.isInFlight(table.id(), policyId));Assertions.assertTrue(actions.tryAcquireInFlight(table.id(), policyId, claimTimeoutMs).isPresent());- Assertions.assertEquals(claim.id(), actions.getById(claim.id()).id());+ Assertions.assertEquals(claim.actionId(), actions.getById(claim.actionId()).actionId());}private PolicyEntity insertPolicy(String metalakeName, String policyName) throws IOException {diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/TestMaintenanceJobSpecFactory.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/TestMaintenanceJobSpecFactory.javaindex 74027d4b9e..1bb42b00cf 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/TestMaintenanceJobSpecFactory.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/TestMaintenanceJobSpecFactory.java@@ -27,7 +27,7 @@ import java.util.Map;import org.apache.gravitino.Config;import org.apache.gravitino.json.JsonUtils;import org.apache.gravitino.maintenance.policy.MaintenanceAuthConfigs;-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.TableTarget;+import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceJobTemplates;import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceTableRefs.ResolvedTableRef;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.PolicyEntity;@@ -43,7 +43,7 @@ class TestMaintenanceJobSpecFactory {private static final String GRAVITINO_URI = "http://localhost:8090";@Test- void testForCronBuildsSharedJobConfAndIdentifierLevels() {+ void testForCronBuildsTasksAndSharedBags() {MaintenanceJobSpecFactory factory = new MaintenanceJobSpecFactory(configWithUri());PolicyEntity policy = compaction(202L);MaintenanceJobSpec spec =@@ -56,29 +56,33 @@ class TestMaintenanceJobSpecFactory {Assertions.assertTrue(spec.isValid());Assertions.assertEquals("ml", spec.metalake());Assertions.assertEquals(List.of(10L, 11L), spec.tableIds());- Assertions.assertEquals(1, spec.getOperations().size());- Assertions.assertEquals(202L, spec.getOperations().get(0).getPolicyId());- Assertions.assertEquals("rewrite_data_files", spec.getOperations().get(0).getMaintenanceType());- Assertions.assertNull(spec.getJobConf().get("catalog_name"));- Assertions.assertNull(spec.getJobConf().get("table_identifier"));- Assertions.assertFalse(spec.getJobConf().containsKey("tms_table_id"));- Assertions.assertFalse(spec.getJobConf().containsKey("tms_policy_id"));+ Assertions.assertEquals(2, spec.getTasks().size());+ Assertions.assertEquals(202L, spec.getTasks().get(0).getPolicyId());+ Assertions.assertEquals("rewrite_data_files", spec.getTasks().get(0).getMaintenanceType());+ Assertions.assertEquals("iceberg", spec.getTasks().get(0).catalogName());+ Assertions.assertEquals("db.t1", spec.getTasks().get(0).tableIdentifier());+ Assertions.assertEquals("db.t2", spec.getTasks().get(1).tableIdentifier());+ Assertions.assertFalse(spec.getTasks().get(0).getParameters().containsKey("updater_options"));+ Assertions.assertFalse(spec.getTasks().get(0).getParameters().containsKey("spark_conf"));+ Assertions.assertFalse(+ spec.getTasks().get(0).getParameters().containsKey("spark_executor_memory"));Assertions.assertTrue(- spec.getJobConf()- .get("updater_options")- .contains("gravitino.maintenance.gravitinoAuth.uri"));- Assertions.assertFalse(spec.getJobConf().get("updater_options").contains(GRAVITINO_URI));+ spec.getUpdaterOptions().contains("gravitino.maintenance.gravitinoAuth.uri"));+ Assertions.assertFalse(spec.getUpdaterOptions().contains(GRAVITINO_URI));+ Assertions.assertTrue(spec.getSparkConf().contains("spark.executor.memory"));- TableTarget first = spec.getTables().get(0);- Assertions.assertEquals(List.of("ml", "iceberg", "db", "t1"), first.getIdentifier());Map<String, String> perTable =- MaintenanceJobSpecFactory.jobConfForTable(spec.getJobConf(), first);+ MaintenanceJobSpecFactory.jobConfForTask(spec, spec.getTasks().get(0));Assertions.assertEquals("iceberg", perTable.get("catalog_name"));Assertions.assertNull(perTable.get("table_identifier"));Assertions.assertNull(perTable.get("table_id"));+ Assertions.assertEquals(+ "rewrite_data_files", perTable.get(MaintenanceJobTemplates.MAINTENANCE_TYPES_KEY));+ Assertions.assertEquals("202", perTable.get(MaintenanceJobTemplates.POLICY_IDS_KEY));Assertions.assertTrue(perTable.get("tables").contains("\"table_id\":10"));Assertions.assertTrue(perTable.get("tables").contains("\"table_identifier\":\"db.t1\""));- Assertions.assertFalse(perTable.containsKey("tms_table_id"));+ Assertions.assertTrue(perTable.containsKey("updater_options"));+ Assertions.assertEquals("4g", perTable.get("spark_executor_memory"));}@Test@@ -106,9 +110,10 @@ class TestMaintenanceJobSpecFactory {Assertions.assertEquals(original, restored);String json = new String(bytes, StandardCharsets.UTF_8);Assertions.assertFalse(json.contains("\"version\""));- Assertions.assertFalse(json.contains("\"metalake\""));- Assertions.assertTrue(json.contains("\"operations\""));+ Assertions.assertTrue(json.contains("\"tasks\""));+ Assertions.assertTrue(json.contains("\"parameters\""));Assertions.assertTrue(json.contains("updater_options"));+ Assertions.assertTrue(json.contains("spark_conf"));}@Testdiff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestCommitJobClient.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestCommitJobClient.javaindex 75be3da9b5..c464c49701 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestCommitJobClient.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestCommitJobClient.java@@ -93,11 +93,10 @@ class TestCommitJobClient extends TestJDBCBackend {.getData();Assertions.assertTrue(spec.isValid());Assertions.assertEquals(List.of(TABLE_ID), spec.tableIds());- Assertions.assertEquals(POLICY_ID, spec.getOperations().get(0).getPolicyId());- Assertions.assertTrue(spec.getJobConf().containsKey("updater_options"));- Assertions.assertNull(spec.getJobConf().get("catalog_name"));- Assertions.assertNull(spec.getJobConf().get("table_identifier"));- Assertions.assertEquals("iceberg", spec.getTables().get(0).catalogName());+ Assertions.assertEquals(POLICY_ID, spec.getTasks().get(0).getPolicyId());+ Assertions.assertTrue(spec.getUpdaterOptions() != null && !spec.getUpdaterOptions().isBlank());+ Assertions.assertEquals("iceberg", spec.getTasks().get(0).catalogName());+ Assertions.assertFalse(spec.getTasks().get(0).getParameters().containsKey("updater_options"));}private static Function<Long, Optional<CollectedCommitChain>> fixedCollector(diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestCommitJobSpecFactory.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestCommitJobSpecFactory.javaindex c6bb36e038..ecf8dfd3f9 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestCommitJobSpecFactory.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestCommitJobSpecFactory.java@@ -27,6 +27,7 @@ import org.apache.gravitino.json.JsonUtils;import org.apache.gravitino.maintenance.optimizer.common.util.IcebergSparkConfigUtils;import org.apache.gravitino.maintenance.policy.MaintenanceAuthConfigs;import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;+import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpecFactory;import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceJobTemplates;import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceTableRefs.ResolvedTableRef;import org.apache.gravitino.meta.AuditInfo;@@ -43,7 +44,7 @@ class TestCommitJobSpecFactory {private static final String GRAVITINO_URI = "http://localhost:8090";@Test- void testForCommitMergesChainAndSetsMaintenanceTypes() {+ void testForCommitBuildsPerTypeTasksAndSharedBags() {CommitJobSpecFactory factory = new CommitJobSpecFactory(configWithUri());CommitChainMember compaction =new CommitChainMember(@@ -56,24 +57,28 @@ class TestCommitJobSpecFactory {List.of(compaction, expire), new ResolvedTableRef(101L, "iceberg", "db.t"));Assertions.assertTrue(spec.isValid());- Assertions.assertEquals(2, spec.getOperations().size());+ Assertions.assertEquals(2, spec.getTasks().size());+ Assertions.assertEquals(101L, spec.getTasks().get(0).getTableId());+ Assertions.assertEquals(202L, spec.getTasks().get(0).getPolicyId());+ Assertions.assertEquals("rewrite_data_files", spec.getTasks().get(0).getMaintenanceType());+ Assertions.assertEquals("expire_snapshots", spec.getTasks().get(1).getMaintenanceType());+ Assertions.assertEquals("7d", spec.getTasks().get(1).getParameters().get("older_than"));+ Assertions.assertEquals("10", spec.getTasks().get(1).getParameters().get("retain_last"));+ Assertions.assertTrue(spec.getUpdaterOptions().contains("metalake"));+ Assertions.assertTrue(spec.getSparkConf().contains("spark.executor.memory"));+ Map<String, String> spark =+ IcebergSparkConfigUtils.parseFlatJsonMap(spec.getSparkConf(), "spark_conf");+ Assertions.assertEquals("4g", spark.get("spark.executor.memory"));++ Map<String, String> runJob = MaintenanceJobSpecFactory.jobConfForCommitChain(spec);Assertions.assertEquals("rewrite_data_files,expire_snapshots",- spec.getJobConf().get(MaintenanceJobTemplates.MAINTENANCE_TYPES_KEY));- Assertions.assertEquals(- "202,303", spec.getJobConf().get(MaintenanceJobTemplates.POLICY_IDS_KEY));- Assertions.assertFalse(spec.getJobConf().containsKey("tms_table_id"));- Assertions.assertFalse(spec.getJobConf().containsKey("tms_policy_id"));- Assertions.assertNull(spec.getJobConf().get("catalog_name"));- Assertions.assertNull(spec.getJobConf().get("table_identifier"));- Assertions.assertNull(spec.getJobConf().get("tables"));- Assertions.assertEquals(101L, spec.getTables().get(0).getTableId());- Assertions.assertEquals(202L, spec.getOperations().get(0).getPolicyId());- // Later chain members contribute procedure params the first policy does not set.- Assertions.assertEquals("7d", spec.getJobConf().get("older_than"));- Assertions.assertEquals("10", spec.getJobConf().get("retain_last"));- Assertions.assertEquals("4g", spec.getJobConf().get("spark_executor_memory"));- String rulesByType = spec.getJobConf().get(MaintenanceJobTemplates.RULES_KEY);+ runJob.get(MaintenanceJobTemplates.MAINTENANCE_TYPES_KEY));+ Assertions.assertEquals("202,303", runJob.get(MaintenanceJobTemplates.POLICY_IDS_KEY));+ Assertions.assertEquals("7d", runJob.get("older_than"));+ Assertions.assertEquals("10", runJob.get("retain_last"));+ Assertions.assertEquals("4g", runJob.get("spark_executor_memory"));+ String rulesByType = runJob.get(MaintenanceJobTemplates.RULES_KEY);Assertions.assertNotNull(rulesByType);Assertions.assertTrue(rulesByType.contains("\"rewrite_data_files\""));Assertions.assertTrue(rulesByType.contains("\"expire_snapshots\""));@@ -81,37 +86,26 @@ class TestCommitJobSpecFactory {}@Test- void testMergeLaterMemberJobConfMergesSparkConfByKey() {+ void testMergeSparkConfMapsMergesByKey() {Map<String, String> into = new HashMap<>();- into.put("spark_conf", "{\"spark.executor.memory\":\"4g\",\"shared\":\"first\"}");- Map<String, String> from =- Map.of(- "spark_conf",- "{\"spark.executor.cores\":\"2\",\"shared\":\"later\",\"spark.driver.memory\":\"2g\"}");-- CommitJobSpecFactory.mergeLaterMemberJobConf(into, from);+ into.put("spark.executor.memory", "4g");+ into.put("shared", "first");+ CommitJobSpecFactory.mergeSparkConfMaps(+ into,+ "{\"spark.executor.cores\":\"2\",\"shared\":\"later\",\"spark.driver.memory\":\"2g\"}");- Map<String, String> merged =- IcebergSparkConfigUtils.parseFlatJsonMap(into.get("spark_conf"), "spark_conf");- Assertions.assertEquals("4g", merged.get("spark.executor.memory"));- Assertions.assertEquals("first", merged.get("shared"));- Assertions.assertEquals("2", merged.get("spark.executor.cores"));- Assertions.assertEquals("2g", merged.get("spark.driver.memory"));+ Assertions.assertEquals("4g", into.get("spark.executor.memory"));+ Assertions.assertEquals("first", into.get("shared"));+ Assertions.assertEquals("2", into.get("spark.executor.cores"));+ Assertions.assertEquals("2g", into.get("spark.driver.memory"));}@Test- void testMergeLaterMemberJobConfAddsSparkConfWhenMissing() throws Exception {+ void testMergeSparkConfMapsAddsWhenMissing() throws Exception {Map<String, String> into = new HashMap<>();- into.put("older_than", "7d");- Map<String, String> from =- Map.of("spark_conf", JsonUtils.anyFieldMapper().writeValueAsString(Map.of("k", "v")));-- CommitJobSpecFactory.mergeLaterMemberJobConf(into, from);-- Assertions.assertEquals("7d", into.get("older_than"));- Assertions.assertEquals(- "v",- IcebergSparkConfigUtils.parseFlatJsonMap(into.get("spark_conf"), "spark_conf").get("k"));+ CommitJobSpecFactory.mergeSparkConfMaps(+ into, JsonUtils.anyFieldMapper().writeValueAsString(Map.of("k", "v")));+ Assertions.assertEquals("v", into.get("k"));}private static Config configWithUri() {diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestMaintenanceCommitSubmitPipeline.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestMaintenanceCommitSubmitPipeline.javaindex b6b84c123c..c86e823454 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestMaintenanceCommitSubmitPipeline.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestMaintenanceCommitSubmitPipeline.java@@ -36,8 +36,7 @@ import java.util.Optional;import java.util.Set;import org.apache.gravitino.Config;import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.Operation;-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.TableTarget;+import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.Task;import org.apache.gravitino.maintenance.scheduler.MaintenanceTaskIds;import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceJobConfBuilder;import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceJobSubmitter;@@ -93,18 +92,17 @@ class TestMaintenanceCommitSubmitPipeline {eq(TABLE_ID), eq(List.of(POLICY_ID, EXPIRE_POLICY_ID)), eq(CLAIM_TIMEOUT_MS))).thenReturn(Optional.of(claims));- Map<String, String> jobConf = new LinkedHashMap<>();- jobConf.put(- MaintenanceJobTemplates.MAINTENANCE_TYPES_KEY, "rewrite_data_files,expire_snapshots");- jobConf.put("updater_options", "{\"gravitino_uri\":\"http://localhost:8090\"}");-+ Map<String, String> p1 = new LinkedHashMap<>();+ p1.put("catalog_name", "iceberg");+ p1.put("table_identifier", "db.t");+ Map<String, String> p2 = new LinkedHashMap<>(p1);MaintenanceJobSpec spec =new MaintenanceJobSpec(- List.of(new TableTarget(TABLE_ID, List.of("ml", "iceberg", "db", "t"))),List.of(- new Operation(POLICY_ID, "rewrite_data_files"),- new Operation(EXPIRE_POLICY_ID, "expire_snapshots")),- jobConf);+ new Task(TABLE_ID, POLICY_ID, "rewrite_data_files", null, p1),+ new Task(TABLE_ID, EXPIRE_POLICY_ID, "expire_snapshots", null, p2)),+ "{\"gravitino_uri\":\"http://localhost:8090\",\"metalake\":\"ml\"}",+ null);pipeline(allowAllGate(), actions, submitter).submit(MaintenanceTaskIds.forCommitTable(TABLE_ID), spec);@@ -178,12 +176,12 @@ class TestMaintenanceCommitSubmitPipeline {}private static MaintenanceJobSpec spec() {- Map<String, String> jobConf = new LinkedHashMap<>();- jobConf.put(MaintenanceJobTemplates.MAINTENANCE_TYPES_KEY, "rewrite_data_files");- jobConf.put("updater_options", "{\"gravitino_uri\":\"http://localhost:8090\"}");+ Map<String, String> parameters = new LinkedHashMap<>();+ parameters.put("catalog_name", "iceberg");+ parameters.put("table_identifier", "db.t");return new MaintenanceJobSpec(- List.of(new TableTarget(TABLE_ID, List.of("ml", "iceberg", "db", "t"))),- List.of(new Operation(POLICY_ID, "rewrite_data_files")),- jobConf);+ List.of(new Task(TABLE_ID, POLICY_ID, "rewrite_data_files", null, parameters)),+ "{\"gravitino_uri\":\"http://localhost:8090\",\"metalake\":\"ml\"}",+ null);}}diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestCronJobClient.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestCronJobClient.javaindex 6229fd776f..4731dd87a8 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestCronJobClient.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestCronJobClient.java@@ -108,7 +108,7 @@ class TestCronJobClient extends TestJDBCBackend {.get().getData();Assertions.assertTrue(spec.isValid());- Assertions.assertTrue(spec.getJobConf().containsKey("updater_options"));+ Assertions.assertTrue(spec.getUpdaterOptions() != null && !spec.getUpdaterOptions().isBlank());Assertions.assertEquals(List.of(1L), spec.tableIds());}@@ -150,8 +150,8 @@ class TestCronJobClient extends TestJDBCBackend {MaintenanceJobSpec data =(MaintenanceJobSpec) client.getScheduledExecution(batch0).get().getData();Assertions.assertEquals(List.of(10L, 11L, 12L, 13L), data.tableIds());- Assertions.assertEquals(1, data.getOperations().size());- Assertions.assertTrue(data.getJobConf().containsKey("updater_options"));+ Assertions.assertEquals(4, data.getTasks().size());+ Assertions.assertTrue(data.getUpdaterOptions() != null && !data.getUpdaterOptions().isBlank());}@TestTemplatediff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestMaintenanceSparkSubmitPipeline.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestMaintenanceSparkSubmitPipeline.javaindex d46a603f1f..4fe32a0cc9 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestMaintenanceSparkSubmitPipeline.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestMaintenanceSparkSubmitPipeline.java@@ -36,8 +36,7 @@ import java.util.Map;import java.util.Optional;import org.apache.gravitino.Config;import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.Operation;-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.TableTarget;+import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.Task;import org.apache.gravitino.maintenance.scheduler.MaintenanceTaskIds;import org.apache.gravitino.maintenance.storage.service.OccupancyClaim;import org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService;@@ -84,16 +83,7 @@ class TestMaintenanceSparkSubmitPipeline {TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);CronSubmitGate gate = (tableId, policyId) -> tableId == 11L;- Map<String, String> shared = new LinkedHashMap<>();- shared.put(MaintenanceJobTemplates.MAINTENANCE_TYPES_KEY, "expire_snapshots");- shared.put("updater_options", "{\"gravitino_uri\":\"http://localhost:8090\"}");- MaintenanceJobSpec batch =- new MaintenanceJobSpec(- List.of(- new TableTarget(10L, List.of("metalake", "iceberg", "db", "t1")),- new TableTarget(11L, List.of("metalake", "iceberg", "db", "t2"))),- List.of(new Operation(POLICY_ID, "expire_snapshots")),- shared);+ MaintenanceJobSpec batch = batchSpec(10L, 11L, "expire_snapshots");pipeline(gate, actions, submitter).submit(MaintenanceTaskIds.forCronBatch(0L, POLICY_ID), batch);@@ -206,17 +196,7 @@ class TestMaintenanceSparkSubmitPipeline {when(actions.tryAcquireInFlight(11L, POLICY_ID, CLAIM_TIMEOUT_MS)).thenReturn(Optional.of(claimB));- Map<String, String> shared = new LinkedHashMap<>();- shared.put(MaintenanceJobTemplates.MAINTENANCE_TYPES_KEY, "expire_snapshots");- shared.put("updater_options", "{\"gravitino_uri\":\"http://localhost:8090\"}");-- MaintenanceJobSpec batch =- new MaintenanceJobSpec(- List.of(- new TableTarget(10L, List.of("metalake", "iceberg", "db", "t1")),- new TableTarget(11L, List.of("metalake", "iceberg", "db", "t2"))),- List.of(new Operation(POLICY_ID, "expire_snapshots")),- shared);+ MaintenanceJobSpec batch = batchSpec(10L, 11L, "expire_snapshots");pipeline(mockGate(false), actions, submitter).submit(MaintenanceTaskIds.forCronBatch(0L, POLICY_ID), batch);@@ -253,15 +233,14 @@ class TestMaintenanceSparkSubmitPipeline {when(actions.tryAcquireInFlight(TABLE_ID, POLICY_ID, CLAIM_TIMEOUT_MS)).thenReturn(Optional.of(new OccupancyClaim(1L, 1L)));- Map<String, String> jobConf = new LinkedHashMap<>();- jobConf.put(MaintenanceJobTemplates.MAINTENANCE_TYPES_KEY, "rewrite_data_files");- jobConf.put("strategy", "binpack");- jobConf.put(- "updater_options",- "{\"gravitino_uri\":\"http://localhost:8090\",\"metalake\":\"metalake\"}");- jobConf.put("spark_conf", "{\"spark.sql.catalog.iceberg.rest.auth.type\":\"basic\"}");+ Map<String, String> parameters = new LinkedHashMap<>();+ parameters.put("strategy", "binpack");+ parameters.put("catalog_name", "iceberg");+ parameters.put("table_identifier", "db.t");- pipeline(mockGate(false), actions, submitter).submit(INSTANCE, spec(jobConf));+ pipeline(mockGate(false), actions, submitter)+ .submit(+ INSTANCE, spec(parameters, "{\"spark.sql.catalog.iceberg.rest.auth.type\":\"basic\"}"));@SuppressWarnings("unchecked")ArgumentCaptor<Map<String, String>> confCaptor = ArgumentCaptor.forClass(Map.class);@@ -309,16 +288,38 @@ class TestMaintenanceSparkSubmitPipeline {}private static MaintenanceJobSpec spec() {- Map<String, String> jobConf = new LinkedHashMap<>();- jobConf.put(MaintenanceJobTemplates.MAINTENANCE_TYPES_KEY, "rewrite_data_files");- jobConf.put("updater_options", "{\"gravitino_uri\":\"http://localhost:8090\"}");- return spec(jobConf);+ Map<String, String> parameters = new LinkedHashMap<>();+ parameters.put("catalog_name", "iceberg");+ parameters.put("table_identifier", "db.t");+ return spec(parameters, null);+ }++ private static MaintenanceJobSpec spec(Map<String, String> parameters) {+ return spec(parameters, null);+ }++ private static MaintenanceJobSpec spec(Map<String, String> parameters, String sparkConf) {+ Map<String, String> params = new LinkedHashMap<>(parameters);+ params.putIfAbsent("catalog_name", "iceberg");+ params.putIfAbsent("table_identifier", "db.t");+ return new MaintenanceJobSpec(+ List.of(new Task(TABLE_ID, POLICY_ID, "rewrite_data_files", null, params)),+ "{\"gravitino_uri\":\"http://localhost:8090\",\"metalake\":\"metalake\"}",+ sparkConf);}- private static MaintenanceJobSpec spec(Map<String, String> jobConf) {+ private static MaintenanceJobSpec batchSpec(long table1, long table2, String type) {+ Map<String, String> p1 = new LinkedHashMap<>();+ p1.put("catalog_name", "iceberg");+ p1.put("table_identifier", "db.t1");+ Map<String, String> p2 = new LinkedHashMap<>();+ p2.put("catalog_name", "iceberg");+ p2.put("table_identifier", "db.t2");return new MaintenanceJobSpec(- List.of(new TableTarget(TABLE_ID, List.of("metalake", "iceberg", "db", "t"))),- List.of(new Operation(POLICY_ID, "rewrite_data_files")),- jobConf);+ List.of(+ new Task(table1, POLICY_ID, type, null, p1),+ new Task(table2, POLICY_ID, type, null, p2)),+ "{\"gravitino_uri\":\"http://localhost:8090\",\"metalake\":\"metalake\"}",+ null);}}diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/storage/TableMaintenanceActionTestUtils.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/storage/TableMaintenanceActionTestUtils.javaindex a2913aece3..daf91ddc61 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/storage/TableMaintenanceActionTestUtils.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/storage/TableMaintenanceActionTestUtils.java@@ -48,11 +48,11 @@ public final class TableMaintenanceActionTestUtils {.getConnection().prepareStatement("UPDATE table_maintenance_action SET created_at = ? "- + "WHERE id = ? AND job_id IS NULL AND finished_at = 0")) {+ + "WHERE action_id = ? AND job_id IS NULL AND finished_at = 0")) {statement.setLong(1, expiredAt);- statement.setLong(2, claim.id());+ statement.setLong(2, claim.actionId());Assertions.assertEquals(1, statement.executeUpdate());}- return new OccupancyClaim(claim.id(), expiredAt);+ return new OccupancyClaim(claim.actionId(), expiredAt);}}diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/storage/service/TestTableMaintenanceActionMetaService.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/storage/service/TestTableMaintenanceActionMetaService.javaindex 515b59b6bb..c4844eef1c 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/storage/service/TestTableMaintenanceActionMetaService.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/storage/service/TestTableMaintenanceActionMetaService.java@@ -41,12 +41,12 @@ class TestTableMaintenanceActionMetaService extends TestJDBCBackend {actionService.insertInFlight(10L, 20L, TableMaintenanceConfig.forTest(1, 1, 1, 500L, 1_000L, 4, 10));long after = System.currentTimeMillis();- Assertions.assertNull(actionService.getById(claim.id()).jobId());- Assertions.assertEquals(0L, actionService.getById(claim.id()).finishedAt());+ Assertions.assertNull(actionService.getById(claim.actionId()).jobId());+ Assertions.assertEquals(0L, actionService.getById(claim.actionId()).finishedAt());// DB clock may skew slightly from the JVM; allow a small window.Assertions.assertTrue(claim.createdAt() >= before - 5_000L);Assertions.assertTrue(claim.createdAt() <= after + 5_000L);- Assertions.assertEquals(claim.createdAt(), actionService.getById(claim.id()).createdAt());+ Assertions.assertEquals(claim.createdAt(), actionService.getById(claim.actionId()).createdAt());long jobId = 999L;long tableId = 10L;@@ -55,31 +55,31 @@ class TestTableMaintenanceActionMetaService extends TestJDBCBackend {Assertions.assertEquals(jobId, actionService.getByJobIdAndTableId(jobId, tableId).jobId());Assertions.assertEquals(0L, actionService.getByJobIdAndTableId(jobId, tableId).finishedAt());- actionService.recordBeforeSnapshot(jobId, tableId, policyId, 100L);+ long beforeMetricsId = metricsService.insertMetrics(tableId, policyId, 100L, "{\"mse\":1}");+ long actionId = claim.actionId();+ actionService.recordBeforeMetrics(actionId, beforeMetricsId);Assertions.assertEquals(- 100L, actionService.getByJobIdAndTableId(jobId, tableId).beforeSnapshotId());- actionService.recordBeforeSnapshot(jobId, tableId, policyId, 100L);+ beforeMetricsId, actionService.getByJobIdAndTableId(jobId, tableId).beforeMetricsId());+ actionService.recordBeforeMetrics(actionId, beforeMetricsId);Assertions.assertEquals(- 100L, actionService.getByJobIdAndTableId(jobId, tableId).beforeSnapshotId());+ beforeMetricsId, actionService.getByJobIdAndTableId(jobId, tableId).beforeMetricsId());Assertions.assertThrows(IllegalStateException.class,- () -> actionService.recordBeforeSnapshot(jobId, tableId, policyId, 101L));+ () -> actionService.recordBeforeMetrics(actionId, beforeMetricsId + 1));- metricsService.insertMetrics(tableId, policyId, 100L, "{\"mse\":1}");- actionService.markFinished(jobId, tableId, policyId, 200L, System.currentTimeMillis());- Assertions.assertThrows(- IllegalStateException.class,- () ->- actionService.markFinished(jobId, tableId, policyId, 201L, System.currentTimeMillis()));- metricsService.insertMetrics(tableId, policyId, 200L, "{\"mse\":2}");+ long afterMetricsId = metricsService.insertMetrics(tableId, policyId, 200L, "{\"mse\":2}");+ actionService.recordAfterMetrics(actionId, afterMetricsId);+ actionService.markFinished(actionId, System.currentTimeMillis());+ // Idempotent finish when already closed.+ actionService.markFinished(actionId, System.currentTimeMillis() + 1);actionService.deleteByJobId(jobId);Assertions.assertTrue(actionService.listByJobId(jobId).isEmpty());Assertions.assertEquals(- "{\"mse\":1}", metricsService.getMetrics(tableId, policyId, 100L).metricsValue());+ "{\"mse\":1}", metricsService.getMetrics(beforeMetricsId).metricsValue());Assertions.assertEquals(- "{\"mse\":2}", metricsService.getMetrics(tableId, policyId, 200L).metricsValue());+ "{\"mse\":2}", metricsService.getMetrics(afterMetricsId).metricsValue());}@TestTemplate@@ -95,50 +95,21 @@ class TestTableMaintenanceActionMetaService extends TestJDBCBackend {Assertions.assertEquals(2, actions.listByJobId(jobId).size());Assertions.assertThrows(IllegalStateException.class, () -> actions.getByJobId(jobId));- actions.recordBeforeSnapshot(jobId, 101L, 201L, 11L);- actions.recordBeforeSnapshot(jobId, 102L, 202L, 22L);+ actions.recordBeforeMetrics(claimA.actionId(), 11L);+ actions.recordBeforeMetrics(claimB.actionId(), 22L);long finishedAtA = System.currentTimeMillis();- actions.markFinished(jobId, 101L, 201L, null, finishedAtA);+ actions.markFinished(claimA.actionId(), finishedAtA);Assertions.assertEquals(finishedAtA, actions.getByJobIdAndTableId(jobId, 101L).finishedAt());Assertions.assertEquals(0L, actions.getByJobIdAndTableId(jobId, 102L).finishedAt());long finishedAtB = finishedAtA + 10;- actions.markFinished(jobId, 102L, 202L, 33L, finishedAtB);+ actions.recordAfterMetrics(claimB.actionId(), 33L);+ actions.markFinished(claimB.actionId(), finishedAtB);Assertions.assertEquals(finishedAtB, actions.getByJobIdAndTableId(jobId, 102L).finishedAt());- Assertions.assertEquals(33L, actions.getByJobIdAndTableId(jobId, 102L).afterSnapshotId());- // Idempotent null-after finish for already closed A.- actions.markFinished(jobId, 101L, 201L, null, finishedAtA + 1);- }-- @TestTemplate- void testMarkFinishedBackfillsAfterSnapshotWhenAlreadyClosed() {- TableMaintenanceActionMetaService actionService =- TableMaintenanceActionMetaService.getInstance();- long jobId = 1999L;- long tableId = 12L;- long policyId = 22L;- OccupancyClaim claim =- actionService.insertInFlight(- tableId, policyId, TableMaintenanceConfig.forTest(1, 1, 1, 500L, 1_000L, 4, 10));- actionService.bindJobId(claim, jobId);- actionService.recordBeforeSnapshot(jobId, tableId, policyId, 100L);-- long reclaimFinishedAt = System.currentTimeMillis();- actionService.markFinished(jobId, tableId, policyId, null, reclaimFinishedAt);- Assertions.assertEquals(- reclaimFinishedAt, actionService.getByJobIdAndTableId(jobId, tableId).finishedAt());- Assertions.assertNull(actionService.getByJobIdAndTableId(jobId, tableId).afterSnapshotId());-- actionService.markFinished(jobId, tableId, policyId, 200L, System.currentTimeMillis());- Assertions.assertEquals(- 200L, actionService.getByJobIdAndTableId(jobId, tableId).afterSnapshotId());- Assertions.assertEquals(- reclaimFinishedAt, actionService.getByJobIdAndTableId(jobId, tableId).finishedAt());- Assertions.assertThrows(- IllegalStateException.class,- () ->- actionService.markFinished(jobId, tableId, policyId, 201L, System.currentTimeMillis()));+ Assertions.assertEquals(33L, actions.getByJobIdAndTableId(jobId, 102L).afterMetricsId());+ // Idempotent finish for already closed A.+ actions.markFinished(claimA.actionId(), finishedAtA + 1);}@TestTemplate@@ -169,8 +140,8 @@ class TestTableMaintenanceActionMetaService extends TestJDBCBackend {actions.bindJobId(claimB, jobId);// Spark may lazy-bind before commit-chain submit-side bindJobIds.actions.bindJobIds(List.of(claimA, claimB), jobId);- Assertions.assertEquals(jobId, actions.getById(claimA.id()).jobId());- Assertions.assertEquals(jobId, actions.getById(claimB.id()).jobId());+ Assertions.assertEquals(jobId, actions.getById(claimA.actionId()).jobId());+ Assertions.assertEquals(jobId, actions.getById(claimB.actionId()).jobId());}@TestTemplate@@ -232,15 +203,15 @@ class TestTableMaintenanceActionMetaService extends TestJDBCBackend {actions.bindJobId(claimA, jobId);actions.bindJobId(claimB, jobId);- actions.recordBeforeSnapshot(jobId, tableId, policyA, 11L);- actions.recordBeforeSnapshot(jobId, tableId, policyB, 22L);+ actions.recordBeforeMetrics(claimA.actionId(), 11L);+ actions.recordBeforeMetrics(claimB.actionId(), 22L);Assertions.assertEquals(- 11L, actions.getByJobIdAndTableIdAndPolicyId(jobId, tableId, policyA).beforeSnapshotId());+ 11L, actions.getByJobIdAndTableIdAndPolicyId(jobId, tableId, policyA).beforeMetricsId());Assertions.assertEquals(- 22L, actions.getByJobIdAndTableIdAndPolicyId(jobId, tableId, policyB).beforeSnapshotId());+ 22L, actions.getByJobIdAndTableIdAndPolicyId(jobId, tableId, policyB).beforeMetricsId());long finishedAt = System.currentTimeMillis();- actions.markFinished(jobId, tableId, policyA, null, finishedAt);+ actions.markFinished(claimA.actionId(), finishedAt);Assertions.assertEquals(finishedAt, actions.getByJobIdAndTableIdAndPolicyId(jobId, tableId, policyA).finishedAt());Assertions.assertEquals(@@ -262,7 +233,7 @@ class TestTableMaintenanceActionMetaService extends TestJDBCBackend {Optional<OccupancyClaim> first = actions.tryAcquireInFlight(tableId, policyId, timeoutMs);Assertions.assertTrue(first.isPresent());- Assertions.assertEquals(0L, actions.getById(first.get().id()).finishedAt());+ Assertions.assertEquals(0L, actions.getById(first.get().actionId()).finishedAt());Assertions.assertTrue(actions.tryAcquireInFlight(tableId, policyId, timeoutMs).isEmpty());OccupancyClaim expired = expireClaim(first.get(), timeoutMs);@@ -271,13 +242,14 @@ class TestTableMaintenanceActionMetaService extends TestJDBCBackend {Optional<OccupancyClaim> reclaimed = actions.tryAcquireInFlight(tableId, policyId, timeoutMs);Assertions.assertTrue(reclaimed.isPresent());- Assertions.assertEquals(first.get().id(), reclaimed.get().id());+ Assertions.assertNotEquals(first.get().actionId(), reclaimed.get().actionId());+ Assertions.assertTrue(actions.getById(first.get().actionId()).finishedAt() > 0);Assertions.assertTrue(reclaimed.get().createdAt() > expired.createdAt());- Assertions.assertEquals(0L, actions.getById(reclaimed.get().id()).finishedAt());+ Assertions.assertEquals(0L, actions.getById(reclaimed.get().actionId()).finishedAt());Assertions.assertThrows(IllegalStateException.class, () -> actions.bindJobId(expired, 1001L));actions.bindJobId(reclaimed.get(), 1002L);- Assertions.assertEquals(1002L, actions.getById(reclaimed.get().id()).jobId());+ Assertions.assertEquals(1002L, actions.getById(reclaimed.get().actionId()).jobId());}@TestTemplate@@ -290,7 +262,7 @@ class TestTableMaintenanceActionMetaService extends TestJDBCBackend {Optional<OccupancyClaim> first = actions.tryAcquireInFlight(tableId, policyId, timeoutMs);Assertions.assertTrue(first.isPresent());Assertions.assertTrue(actions.deleteUnboundClaim(first.get()));- Assertions.assertNull(actions.getById(first.get().id()));+ Assertions.assertNull(actions.getById(first.get().actionId()));Optional<OccupancyClaim> second = actions.tryAcquireInFlight(tableId, policyId, timeoutMs);Assertions.assertTrue(second.isPresent());@@ -299,18 +271,19 @@ class TestTableMaintenanceActionMetaService extends TestJDBCBackend {Thread.sleep(2L);Optional<OccupancyClaim> reclaimed = actions.tryAcquireInFlight(tableId, policyId, timeoutMs);Assertions.assertTrue(reclaimed.isPresent());- Assertions.assertEquals(second.get().id(), reclaimed.get().id());+ Assertions.assertNotEquals(second.get().actionId(), reclaimed.get().actionId());+ Assertions.assertTrue(actions.getById(second.get().actionId()).finishedAt() > 0);Assertions.assertTrue(reclaimed.get().createdAt() > expired.createdAt());Assertions.assertNotEquals(second.get().createdAt(), reclaimed.get().createdAt());// Stale submitter cleanup must not delete the reclaimed live claim.Assertions.assertFalse(actions.deleteUnboundClaim(second.get()));- Assertions.assertNotNull(actions.getById(reclaimed.get().id()));- Assertions.assertNull(actions.getById(reclaimed.get().id()).jobId());- Assertions.assertEquals(0L, actions.getById(reclaimed.get().id()).finishedAt());+ Assertions.assertNotNull(actions.getById(reclaimed.get().actionId()));+ Assertions.assertNull(actions.getById(reclaimed.get().actionId()).jobId());+ Assertions.assertEquals(0L, actions.getById(reclaimed.get().actionId()).finishedAt());Assertions.assertTrue(actions.deleteUnboundClaim(reclaimed.get()));- Assertions.assertNull(actions.getById(reclaimed.get().id()));+ Assertions.assertNull(actions.getById(reclaimed.get().actionId()));}@TestTemplate@@ -327,17 +300,18 @@ class TestTableMaintenanceActionMetaService extends TestJDBCBackend {Thread.sleep(2L);Optional<OccupancyClaim> reclaimed = actions.tryAcquireInFlight(tableId, policyId, timeoutMs);Assertions.assertTrue(reclaimed.isPresent());- Assertions.assertEquals(first.get().id(), reclaimed.get().id());+ Assertions.assertNotEquals(first.get().actionId(), reclaimed.get().actionId());+ Assertions.assertTrue(actions.getById(first.get().actionId()).finishedAt() > 0);Assertions.assertTrue(reclaimed.get().createdAt() > expired.createdAt());// Failed submit cleanup uses deleteClaims; stale created_at must not remove live claim.actions.deleteClaims(List.of(first.get()));- Assertions.assertNotNull(actions.getById(reclaimed.get().id()));- Assertions.assertNull(actions.getById(reclaimed.get().id()).jobId());- Assertions.assertEquals(0L, actions.getById(reclaimed.get().id()).finishedAt());+ Assertions.assertNotNull(actions.getById(reclaimed.get().actionId()));+ Assertions.assertNull(actions.getById(reclaimed.get().actionId()).jobId());+ Assertions.assertEquals(0L, actions.getById(reclaimed.get().actionId()).finishedAt());actions.deleteClaims(List.of(reclaimed.get()));- Assertions.assertNull(actions.getById(reclaimed.get().id()));+ Assertions.assertNull(actions.getById(reclaimed.get().actionId()));}@TestTemplate@@ -352,8 +326,8 @@ class TestTableMaintenanceActionMetaService extends TestJDBCBackend {actions.tryAcquireInFlightBatch(tableId, List.of(policyA, policyB), timeoutMs);Assertions.assertTrue(batch.isPresent());Assertions.assertEquals(2, batch.get().size());- Assertions.assertEquals(0L, actions.getById(batch.get().get(0).id()).finishedAt());- Assertions.assertEquals(0L, actions.getById(batch.get().get(1).id()).finishedAt());+ Assertions.assertEquals(0L, actions.getById(batch.get().get(0).actionId()).finishedAt());+ Assertions.assertEquals(0L, actions.getById(batch.get().get(1).actionId()).finishedAt());// Partial hold blocks the whole chain.Assertions.assertTrue(@@ -362,13 +336,13 @@ class TestTableMaintenanceActionMetaService extends TestJDBCBackend {long jobId = 3100L;actions.bindJobIds(batch.get(), jobId);- Assertions.assertEquals(jobId, actions.getById(batch.get().get(0).id()).jobId());- Assertions.assertEquals(jobId, actions.getById(batch.get().get(1).id()).jobId());+ Assertions.assertEquals(jobId, actions.getById(batch.get().get(0).actionId()).jobId());+ Assertions.assertEquals(jobId, actions.getById(batch.get().get(1).actionId()).jobId());long finishedAt = System.currentTimeMillis();- actions.markFinished(jobId, tableId, policyA, 500L, finishedAt);- actions.markFinished(jobId, tableId, policyB, 501L, finishedAt + 1);- Assertions.assertTrue(actions.getById(batch.get().get(0).id()).finishedAt() > 0);- Assertions.assertTrue(actions.getById(batch.get().get(1).id()).finishedAt() > 0);+ actions.markFinished(batch.get().get(0).actionId(), finishedAt);+ actions.markFinished(batch.get().get(1).actionId(), finishedAt + 1);+ Assertions.assertTrue(actions.getById(batch.get().get(0).actionId()).finishedAt() > 0);+ Assertions.assertTrue(actions.getById(batch.get().get(1).actionId()).finishedAt() > 0);}}diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/storage/service/TestTableSnapshotMetricsMetaService.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/storage/service/TestTableSnapshotMetricsMetaService.javaindex ca1fc00c79..6a042288d4 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/storage/service/TestTableSnapshotMetricsMetaService.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/storage/service/TestTableSnapshotMetricsMetaService.java@@ -29,18 +29,21 @@ class TestTableSnapshotMetricsMetaService extends TestJDBCBackend {void testInsertAndGetMetrics() {TableSnapshotMetricsMetaService service = TableSnapshotMetricsMetaService.getInstance();long before = System.currentTimeMillis();- service.insertMetrics(1L, 2L, 99L, "{\"mse\":1}");+ long metricsId = service.insertMetrics(1L, 2L, 99L, "{\"mse\":1}");long after = System.currentTimeMillis();- Assertions.assertEquals("{\"mse\":1}", service.getMetrics(1L, 2L, 99L).metricsValue());- Assertions.assertTrue(service.getMetrics(1L, 2L, 99L).createdAt() >= before);- Assertions.assertTrue(service.getMetrics(1L, 2L, 99L).createdAt() <= after);+ Assertions.assertEquals("{\"mse\":1}", service.getMetrics(metricsId).metricsValue());+ Assertions.assertEquals(99L, service.getMetrics(metricsId).snapshotId());+ Assertions.assertTrue(service.getMetrics(metricsId).createdAt() >= before);+ Assertions.assertTrue(service.getMetrics(metricsId).createdAt() <= after);}@TestTemplate- void testInsertMetricsIsIdempotent() {+ void testSameSnapshotCanHaveMultipleMetricsRows() {TableSnapshotMetricsMetaService service = TableSnapshotMetricsMetaService.getInstance();- service.insertMetrics(3L, 4L, 88L, "{\"mse\":1}");- service.insertMetrics(3L, 4L, 88L, "{\"mse\":2}");- Assertions.assertEquals("{\"mse\":1}", service.getMetrics(3L, 4L, 88L).metricsValue());+ long first = service.insertMetrics(3L, 4L, 88L, "{\"mse\":1}");+ long second = service.insertMetrics(3L, 4L, 88L, "{\"mse\":2}");+ Assertions.assertNotEquals(first, second);+ Assertions.assertEquals("{\"mse\":1}", service.getMetrics(first).metricsValue());+ Assertions.assertEquals("{\"mse\":2}", service.getMetrics(second).metricsValue());}}diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/web/rest/TestTableMaintenanceActionOperations.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/web/rest/TestTableMaintenanceActionOperations.javaindex ad86568cd1..a6a87604c9 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/web/rest/TestTableMaintenanceActionOperations.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/web/rest/TestTableMaintenanceActionOperations.java@@ -21,12 +21,12 @@ package org.apache.gravitino.maintenance.web.rest;import static org.mockito.ArgumentMatchers.anyLong;import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.ArgumentMatchers.eq;-import static org.mockito.ArgumentMatchers.isNull;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;+import java.lang.reflect.Field;import java.util.function.LongFunction;import javax.servlet.http.HttpServletRequest;import javax.ws.rs.core.Response;@@ -44,82 +44,85 @@ import org.junit.jupiter.api.Test;class TestTableMaintenanceActionOperations {private static final String METALAKE = "ml";- private static final long JOB_ID = 42L;+ private static final long ACTION_ID = 9001L;private static final long TABLE_ID = 10L;private static final long POLICY_ID = 20L;+ private static final long JOB_ID = 7001L;private TableMaintenanceActionMetaService actions;private TableSnapshotMetricsMetaService metrics;private TableMaintenanceActionOperations ops;@BeforeEach- void setUp() {+ void setUp() throws Exception {actions = mock(TableMaintenanceActionMetaService.class);metrics = mock(TableSnapshotMetricsMetaService.class);- ops = operations(tableId -> METALAKE);- ops.setHttpRequest(mock(HttpServletRequest.class));+ ops = operations(id -> METALAKE);+ Field httpRequest = TableMaintenanceActionOperations.class.getDeclaredField("httpRequest");+ httpRequest.setAccessible(true);+ httpRequest.set(ops, mock(HttpServletRequest.class));}@Test- void testReportBeforePersistsAndRecordsBeforeSnapshot() {- when(actions.getByJobIdAndTableIdAndPolicyId(JOB_ID, TABLE_ID, POLICY_ID))- .thenReturn(action(TABLE_ID, POLICY_ID));+ void testReportBeforePersistsAndRecordsBeforeMetrics() {+ when(actions.getById(ACTION_ID)).thenReturn(action(TABLE_ID, POLICY_ID));+ when(metrics.insertMetrics(TABLE_ID, POLICY_ID, 100L, "{\"m\":1}")).thenReturn(501L);Response response =ops.reportBeforeMetrics(METALAKE,- JOB_ID,+ ACTION_ID,/*finish=*/ false,new MaintenanceActionMetricsRequest(TABLE_ID, POLICY_ID, 100L, "{\"m\":1}"));Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());verify(metrics).insertMetrics(TABLE_ID, POLICY_ID, 100L, "{\"m\":1}");- verify(actions).recordBeforeSnapshot(JOB_ID, TABLE_ID, POLICY_ID, 100L);- verify(actions, never()).markFinished(anyLong(), anyLong(), anyLong(), anyLong(), anyLong());+ verify(actions).recordBeforeMetrics(ACTION_ID, 501L);+ verify(actions, never()).markFinished(anyLong(), anyLong());}@Test- void testReportBeforeWithFinishClosesSoftSlotWithoutAfterSnapshot() {- when(actions.getByJobIdAndTableIdAndPolicyId(JOB_ID, TABLE_ID, POLICY_ID))- .thenReturn(action(TABLE_ID, POLICY_ID));+ void testReportBeforeWithFinishClosesSoftSlotWithoutAfterMetrics() {+ when(actions.getById(ACTION_ID)).thenReturn(action(TABLE_ID, POLICY_ID));+ when(metrics.insertMetrics(TABLE_ID, POLICY_ID, 100L, "{\"m\":1}")).thenReturn(501L);Response response =ops.reportBeforeMetrics(METALAKE,- JOB_ID,+ ACTION_ID,/*finish=*/ true,new MaintenanceActionMetricsRequest(TABLE_ID, POLICY_ID, 100L, "{\"m\":1}"));Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());- verify(actions).markFinished(eq(JOB_ID), eq(TABLE_ID), eq(POLICY_ID), isNull(), anyLong());+ verify(actions).markFinished(eq(ACTION_ID), anyLong());}@Test- void testReportAfterWithFinishClosesSoftSlotWithAfterSnapshot() {- when(actions.getByJobIdAndTableIdAndPolicyId(JOB_ID, TABLE_ID, POLICY_ID))- .thenReturn(action(TABLE_ID, POLICY_ID));+ void testReportAfterWithFinishClosesSoftSlotWithAfterMetrics() {+ when(actions.getById(ACTION_ID)).thenReturn(action(TABLE_ID, POLICY_ID));+ when(metrics.insertMetrics(TABLE_ID, POLICY_ID, 200L, "{\"m\":2}")).thenReturn(502L);Response response =ops.reportAfterMetrics(METALAKE,- JOB_ID,+ ACTION_ID,/*finish=*/ true,new MaintenanceActionMetricsRequest(TABLE_ID, POLICY_ID, 200L, "{\"m\":2}"));Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());verify(metrics).insertMetrics(TABLE_ID, POLICY_ID, 200L, "{\"m\":2}");- verify(actions).markFinished(eq(JOB_ID), eq(TABLE_ID), eq(POLICY_ID), eq(200L), anyLong());+ verify(actions).recordAfterMetrics(ACTION_ID, 502L);+ verify(actions).markFinished(eq(ACTION_ID), anyLong());}@Testvoid testReportBeforeMissingActionReturns404() {- when(actions.getByJobIdAndTableIdAndPolicyId(JOB_ID, TABLE_ID, POLICY_ID)).thenReturn(null);- when(actions.bindJobIdIfUnbound(TABLE_ID, POLICY_ID, JOB_ID)).thenReturn(false);+ when(actions.getById(ACTION_ID)).thenReturn(null);Response response =ops.reportBeforeMetrics(METALAKE,- JOB_ID,+ ACTION_ID,/*finish=*/ false,new MaintenanceActionMetricsRequest(TABLE_ID, POLICY_ID, 100L, "{\"m\":1}"));@@ -128,50 +131,41 @@ class TestTableMaintenanceActionOperations {}@Test- void testReportBeforeLazyBindsUnboundClaim() {- when(actions.getByJobIdAndTableIdAndPolicyId(JOB_ID, TABLE_ID, POLICY_ID))- .thenReturn(null)- .thenReturn(action(TABLE_ID, POLICY_ID));- when(actions.bindJobIdIfUnbound(TABLE_ID, POLICY_ID, JOB_ID)).thenReturn(true);+ void testReportBeforeUnboundActionReturns404() {+ when(actions.getById(ACTION_ID)).thenReturn(action(TABLE_ID, POLICY_ID, 0L, /*jobId=*/ null));Response response =ops.reportBeforeMetrics(METALAKE,- JOB_ID,+ ACTION_ID,/*finish=*/ false,new MaintenanceActionMetricsRequest(TABLE_ID, POLICY_ID, 100L, "{\"m\":1}"));- Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());- verify(actions).bindJobIdIfUnbound(TABLE_ID, POLICY_ID, JOB_ID);- verify(metrics).insertMetrics(TABLE_ID, POLICY_ID, 100L, "{\"m\":1}");- verify(actions).recordBeforeSnapshot(JOB_ID, TABLE_ID, POLICY_ID, 100L);+ Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());+ verify(metrics, never()).insertMetrics(anyLong(), anyLong(), anyLong(), anyString());}@Test- void testFinishLazyBindsUnboundClaim() {- when(actions.getByJobIdAndTableIdAndPolicyId(JOB_ID, TABLE_ID, POLICY_ID))- .thenReturn(null)- .thenReturn(action(TABLE_ID, POLICY_ID));- when(actions.bindJobIdIfUnbound(TABLE_ID, POLICY_ID, JOB_ID)).thenReturn(true);+ void testFinishClosesSoftSlotWithoutMetrics() {+ when(actions.getById(ACTION_ID)).thenReturn(action(TABLE_ID, POLICY_ID));Response response =ops.finishAction(- METALAKE, JOB_ID, new MaintenanceActionFinishRequest(TABLE_ID, POLICY_ID, null));+ METALAKE, ACTION_ID, new MaintenanceActionFinishRequest(TABLE_ID, POLICY_ID));Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());- verify(actions).bindJobIdIfUnbound(TABLE_ID, POLICY_ID, JOB_ID);- verify(actions).markFinished(eq(JOB_ID), eq(TABLE_ID), eq(POLICY_ID), isNull(), anyLong());+ verify(metrics, never()).insertMetrics(anyLong(), anyLong(), anyLong(), anyString());+ verify(actions).markFinished(eq(ACTION_ID), anyLong());}@Testvoid testReportAfterAlreadyFinishedReturns404() {- when(actions.getByJobIdAndTableIdAndPolicyId(JOB_ID, TABLE_ID, POLICY_ID))- .thenReturn(action(TABLE_ID, POLICY_ID, /*finishedAt=*/ 9L));+ when(actions.getById(ACTION_ID)).thenReturn(action(TABLE_ID, POLICY_ID, /*finishedAt=*/ 9L));Response response =ops.reportAfterMetrics(METALAKE,- JOB_ID,+ ACTION_ID,/*finish=*/ false,new MaintenanceActionMetricsRequest(TABLE_ID, POLICY_ID, 100L, "{\"m\":1}"));@@ -181,54 +175,31 @@ class TestTableMaintenanceActionOperations {@Testvoid testReportBeforeNullBodyReturns400() {- Response response = ops.reportBeforeMetrics(METALAKE, JOB_ID, /*finish=*/ false, null);+ Response response = ops.reportBeforeMetrics(METALAKE, ACTION_ID, /*finish=*/ false, null);Assertions.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());}- @Test- void testFinishClosesSoftSlotWithoutMetrics() {- when(actions.getByJobIdAndTableIdAndPolicyId(JOB_ID, TABLE_ID, POLICY_ID))- .thenReturn(action(TABLE_ID, POLICY_ID));-- Response response =- ops.finishAction(- METALAKE, JOB_ID, new MaintenanceActionFinishRequest(TABLE_ID, POLICY_ID, null));-- Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());- verify(metrics, never()).insertMetrics(anyLong(), anyLong(), anyLong(), anyString());- verify(actions).markFinished(eq(JOB_ID), eq(TABLE_ID), eq(POLICY_ID), isNull(), anyLong());- }-- @Test- void testFinishWithAfterSnapshotId() {- when(actions.getByJobIdAndTableIdAndPolicyId(JOB_ID, TABLE_ID, POLICY_ID))- .thenReturn(action(TABLE_ID, POLICY_ID));-- Response response =- ops.finishAction(- METALAKE, JOB_ID, new MaintenanceActionFinishRequest(TABLE_ID, POLICY_ID, 300L));-- Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());- verify(actions).markFinished(eq(JOB_ID), eq(TABLE_ID), eq(POLICY_ID), eq(300L), anyLong());- }-private TableMaintenanceActionOperations operations(LongFunction<String> lookup) {return new TableMaintenanceActionOperations(new MaintenanceMetricsService(actions, metrics, lookup));}private static TableMaintenanceActionPO action(long tableId, long policyId) {- return action(tableId, policyId, 0L);+ return action(tableId, policyId, 0L, JOB_ID);}private static TableMaintenanceActionPO action(long tableId, long policyId, long finishedAt) {+ return action(tableId, policyId, finishedAt, JOB_ID);+ }++ private static TableMaintenanceActionPO action(+ long tableId, long policyId, long finishedAt, Long jobId) {return TableMaintenanceActionPO.builder()- .withId(1L)- .withJobId(JOB_ID)+ .withActionId(ACTION_ID)+ .withJobId(jobId).withTableId(tableId).withPolicyId(policyId).withFinishedAt(finishedAt)- .withCreatedAt(1L).build();}}diff --git a/scripts/h2/schema-2.0.0-h2.sql b/scripts/h2/schema-2.0.0-h2.sqlindex 1e1d2954f7..82496f0cf8 100644--- a/scripts/h2/schema-2.0.0-h2.sql+++ b/scripts/h2/schema-2.0.0-h2.sql@@ -753,31 +753,31 @@ CREATE INDEX IF NOT EXISTS `scheduled_commit_tasks_execution_time_idx` ON `schedCREATE INDEX IF NOT EXISTS `scheduled_commit_tasks_last_heartbeat_idx` ON `scheduled_commit_tasks`(`last_heartbeat`);CREATE TABLE IF NOT EXISTS `table_maintenance_action` (- `id` BIGINT AUTO_INCREMENT NOT NULL COMMENT 'auto increment id',+ `action_id` BIGINT AUTO_INCREMENT NOT NULL COMMENT 'maintenance action id',`job_id` BIGINT COMMENT 'job run id, maps to job_run_meta.job_run_id',`table_id` BIGINT NOT NULL COMMENT 'table id from table_meta',`policy_id` BIGINT NOT NULL COMMENT 'policy id from policy_meta',- `before_snapshot_id` BIGINT COMMENT 'Iceberg snapshot id before maintenance, null until sampled',- `after_snapshot_id` BIGINT COMMENT 'Iceberg snapshot id after maintenance, null while pending',- `finished_at` BIGINT NOT NULL DEFAULT 0 COMMENT 'finish millis, 0 = soft in-flight slot (one per table/policy)',+ `before_metrics_id` BIGINT COMMENT 'table_snapshot_metrics.metrics_id for S0 sample',+ `after_metrics_id` BIGINT COMMENT 'table_snapshot_metrics.metrics_id for S1 sample',`created_at` BIGINT NOT NULL COMMENT 'creation timestamp in milliseconds',- PRIMARY KEY (`id`)+ `finished_at` BIGINT NOT NULL DEFAULT 0 COMMENT 'finish millis, 0 = soft in-flight slot (one per table/policy)',+ PRIMARY KEY (`action_id`)) COMMENT='table maintenance action metadata';CREATE INDEX IF NOT EXISTS `idx_tma_job_id` ON `table_maintenance_action`(`job_id`);-- Soft slot: finished_at=0 is exclusive per table/policy (one in-flight finish).CREATE UNIQUE INDEX IF NOT EXISTS `uk_tma_table_policy_finished` ON `table_maintenance_action`(`table_id`, `policy_id`, `finished_at`);-CREATE INDEX IF NOT EXISTS `idx_tma_before_sid` ON `table_maintenance_action`(`table_id`, `before_snapshot_id`);-CREATE INDEX IF NOT EXISTS `idx_tma_after_sid` ON `table_maintenance_action`(`table_id`, `after_snapshot_id`);+CREATE INDEX IF NOT EXISTS `idx_tma_before_metrics` ON `table_maintenance_action`(`before_metrics_id`);+CREATE INDEX IF NOT EXISTS `idx_tma_after_metrics` ON `table_maintenance_action`(`after_metrics_id`);CREATE INDEX IF NOT EXISTS `idx_tma_created_at` ON `table_maintenance_action`(`created_at`);CREATE TABLE IF NOT EXISTS `table_snapshot_metrics` (- `id` BIGINT AUTO_INCREMENT NOT NULL COMMENT 'auto increment id',+ `metrics_id` BIGINT AUTO_INCREMENT NOT NULL COMMENT 'metrics row id',`table_id` BIGINT NOT NULL COMMENT 'table id from table_meta',`policy_id` BIGINT NOT NULL COMMENT 'policy id from policy_meta',`snapshot_id` BIGINT NOT NULL COMMENT 'Iceberg snapshot id',`metrics_value` CLOB NOT NULL COMMENT 'metrics value as JSON',`created_at` BIGINT NOT NULL COMMENT 'creation timestamp in milliseconds',- PRIMARY KEY (`id`)+ PRIMARY KEY (`metrics_id`)) COMMENT='table snapshot metrics metadata';-CREATE UNIQUE INDEX IF NOT EXISTS `uk_tid_pid_sid` ON `table_snapshot_metrics`(`table_id`, `policy_id`, `snapshot_id`);+CREATE INDEX IF NOT EXISTS `idx_tsm_tid_pid_sid` ON `table_snapshot_metrics`(`table_id`, `policy_id`, `snapshot_id`);CREATE INDEX IF NOT EXISTS `idx_tsm_created_at` ON `table_snapshot_metrics`(`created_at`);diff --git a/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql b/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sqlindex 542d229459..3bb896304e 100644--- a/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql+++ b/scripts/h2/upgrade-1.3.0-to-2.0.0-h2.sql@@ -173,33 +173,33 @@ CREATE INDEX IF NOT EXISTS `scheduled_commit_tasks_execution_time_idx` ON `schedCREATE INDEX IF NOT EXISTS `scheduled_commit_tasks_last_heartbeat_idx` ON `scheduled_commit_tasks`(`last_heartbeat`);CREATE TABLE IF NOT EXISTS `table_maintenance_action` (- `id` BIGINT AUTO_INCREMENT NOT NULL COMMENT 'auto increment id',+ `action_id` BIGINT AUTO_INCREMENT NOT NULL COMMENT 'maintenance action id',`job_id` BIGINT COMMENT 'job run id, maps to job_run_meta.job_run_id',`table_id` BIGINT NOT NULL COMMENT 'table id from table_meta',`policy_id` BIGINT NOT NULL COMMENT 'policy id from policy_meta',- `before_snapshot_id` BIGINT COMMENT 'Iceberg snapshot id before maintenance, null until sampled',- `after_snapshot_id` BIGINT COMMENT 'Iceberg snapshot id after maintenance, null while pending',- `finished_at` BIGINT NOT NULL DEFAULT 0 COMMENT 'finish millis, 0 = soft in-flight slot (one per table/policy)',+ `before_metrics_id` BIGINT COMMENT 'table_snapshot_metrics.metrics_id for S0 sample',+ `after_metrics_id` BIGINT COMMENT 'table_snapshot_metrics.metrics_id for S1 sample',`created_at` BIGINT NOT NULL COMMENT 'creation timestamp in milliseconds',- PRIMARY KEY (`id`)+ `finished_at` BIGINT NOT NULL DEFAULT 0 COMMENT 'finish millis, 0 = soft in-flight slot (one per table/policy)',+ PRIMARY KEY (`action_id`)) COMMENT='table maintenance action metadata';CREATE INDEX IF NOT EXISTS `idx_tma_job_id` ON `table_maintenance_action`(`job_id`);-- Soft slot: finished_at=0 is exclusive per table/policy (one in-flight finish).CREATE UNIQUE INDEX IF NOT EXISTS `uk_tma_table_policy_finished` ON `table_maintenance_action`(`table_id`, `policy_id`, `finished_at`);-CREATE INDEX IF NOT EXISTS `idx_tma_before_sid` ON `table_maintenance_action`(`table_id`, `before_snapshot_id`);-CREATE INDEX IF NOT EXISTS `idx_tma_after_sid` ON `table_maintenance_action`(`table_id`, `after_snapshot_id`);+CREATE INDEX IF NOT EXISTS `idx_tma_before_metrics` ON `table_maintenance_action`(`before_metrics_id`);+CREATE INDEX IF NOT EXISTS `idx_tma_after_metrics` ON `table_maintenance_action`(`after_metrics_id`);CREATE INDEX IF NOT EXISTS `idx_tma_created_at` ON `table_maintenance_action`(`created_at`);CREATE TABLE IF NOT EXISTS `table_snapshot_metrics` (- `id` BIGINT AUTO_INCREMENT NOT NULL COMMENT 'auto increment id',+ `metrics_id` BIGINT AUTO_INCREMENT NOT NULL COMMENT 'metrics row id',`table_id` BIGINT NOT NULL COMMENT 'table id from table_meta',`policy_id` BIGINT NOT NULL COMMENT 'policy id from policy_meta',`snapshot_id` BIGINT NOT NULL COMMENT 'Iceberg snapshot id',`metrics_value` CLOB NOT NULL COMMENT 'metrics value as JSON',`created_at` BIGINT NOT NULL COMMENT 'creation timestamp in milliseconds',- PRIMARY KEY (`id`)+ PRIMARY KEY (`metrics_id`)) COMMENT='table snapshot metrics metadata';-CREATE UNIQUE INDEX IF NOT EXISTS `uk_tid_pid_sid` ON `table_snapshot_metrics`(`table_id`, `policy_id`, `snapshot_id`);+CREATE INDEX IF NOT EXISTS `idx_tsm_tid_pid_sid` ON `table_snapshot_metrics`(`table_id`, `policy_id`, `snapshot_id`);CREATE INDEX IF NOT EXISTS `idx_tsm_created_at` ON `table_snapshot_metrics`(`created_at`);-- Merge duplicate live owners left by concurrent assignments: the newest live rowdiff --git a/scripts/mysql/schema-2.0.0-mysql.sql b/scripts/mysql/schema-2.0.0-mysql.sqlindex f868bfe339..630754a99a 100644--- a/scripts/mysql/schema-2.0.0-mysql.sql+++ b/scripts/mysql/schema-2.0.0-mysql.sql@@ -740,31 +740,31 @@ CREATE TABLE IF NOT EXISTS `scheduled_commit_tasks` () ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'table maintenance commit schedule metadata';CREATE TABLE IF NOT EXISTS `table_maintenance_action` (- `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',+ `action_id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'maintenance action id',`job_id` BIGINT(20) UNSIGNED NULL COMMENT 'job run id, maps to job_run_meta.job_run_id',`table_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'table id from table_meta',`policy_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'policy id from policy_meta',- `before_snapshot_id` BIGINT(20) NULL COMMENT 'Iceberg snapshot id before maintenance, null until sampled',- `after_snapshot_id` BIGINT(20) NULL COMMENT 'Iceberg snapshot id after maintenance, null while pending',- `finished_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'finish millis, 0 = soft in-flight slot (one per table/policy)',+ `before_metrics_id` BIGINT(20) UNSIGNED NULL COMMENT 'table_snapshot_metrics.metrics_id for S0 sample',+ `after_metrics_id` BIGINT(20) UNSIGNED NULL COMMENT 'table_snapshot_metrics.metrics_id for S1 sample',`created_at` BIGINT(20) UNSIGNED NOT NULL COMMENT 'creation timestamp in milliseconds',- PRIMARY KEY (`id`),+ `finished_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'finish millis, 0 = soft in-flight slot (one per table/policy)',+ PRIMARY KEY (`action_id`),KEY `idx_tma_job_id` (`job_id`),-- Soft slot: finished_at=0 is exclusive per table/policy (one in-flight finish).UNIQUE KEY `uk_tma_table_policy_finished` (`table_id`, `policy_id`, `finished_at`),- KEY `idx_tma_before_sid` (`table_id`, `before_snapshot_id`),- KEY `idx_tma_after_sid` (`table_id`, `after_snapshot_id`),+ KEY `idx_tma_before_metrics` (`before_metrics_id`),+ KEY `idx_tma_after_metrics` (`after_metrics_id`),KEY `idx_tma_created_at` (`created_at`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'table maintenance action metadata';CREATE TABLE IF NOT EXISTS `table_snapshot_metrics` (- `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',+ `metrics_id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'metrics row id',`table_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'table id from table_meta',`policy_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'policy id from policy_meta',`snapshot_id` BIGINT(20) NOT NULL COMMENT 'Iceberg snapshot id',`metrics_value` MEDIUMTEXT NOT NULL COMMENT 'metrics value as JSON',`created_at` BIGINT(20) UNSIGNED NOT NULL COMMENT 'creation timestamp in milliseconds',- PRIMARY KEY (`id`),- UNIQUE KEY `uk_tid_pid_sid` (`table_id`, `policy_id`, `snapshot_id`),+ PRIMARY KEY (`metrics_id`),+ KEY `idx_tsm_tid_pid_sid` (`table_id`, `policy_id`, `snapshot_id`),KEY `idx_tsm_created_at` (`created_at`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'table snapshot metrics metadata';diff --git a/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql b/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sqlindex 2a71058df3..870aea6395 100644--- a/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql+++ b/scripts/mysql/upgrade-1.3.0-to-2.0.0-mysql.sql@@ -620,32 +620,32 @@ CREATE TABLE IF NOT EXISTS `scheduled_commit_tasks` () ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'table maintenance commit schedule metadata';CREATE TABLE IF NOT EXISTS `table_maintenance_action` (- `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',+ `action_id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'maintenance action id',`job_id` BIGINT(20) UNSIGNED NULL COMMENT 'job run id, maps to job_run_meta.job_run_id',`table_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'table id from table_meta',`policy_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'policy id from policy_meta',- `before_snapshot_id` BIGINT(20) NULL COMMENT 'Iceberg snapshot id before maintenance, null until sampled',- `after_snapshot_id` BIGINT(20) NULL COMMENT 'Iceberg snapshot id after maintenance, null while pending',- `finished_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'finish millis, 0 = soft in-flight slot (one per table/policy)',+ `before_metrics_id` BIGINT(20) UNSIGNED NULL COMMENT 'table_snapshot_metrics.metrics_id for S0 sample',+ `after_metrics_id` BIGINT(20) UNSIGNED NULL COMMENT 'table_snapshot_metrics.metrics_id for S1 sample',`created_at` BIGINT(20) UNSIGNED NOT NULL COMMENT 'creation timestamp in milliseconds',- PRIMARY KEY (`id`),+ `finished_at` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT 'finish millis, 0 = soft in-flight slot (one per table/policy)',+ PRIMARY KEY (`action_id`),KEY `idx_tma_job_id` (`job_id`),-- Soft slot: finished_at=0 is exclusive per table/policy (one in-flight finish).UNIQUE KEY `uk_tma_table_policy_finished` (`table_id`, `policy_id`, `finished_at`),- KEY `idx_tma_before_sid` (`table_id`, `before_snapshot_id`),- KEY `idx_tma_after_sid` (`table_id`, `after_snapshot_id`),+ KEY `idx_tma_before_metrics` (`before_metrics_id`),+ KEY `idx_tma_after_metrics` (`after_metrics_id`),KEY `idx_tma_created_at` (`created_at`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'table maintenance action metadata';CREATE TABLE IF NOT EXISTS `table_snapshot_metrics` (- `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'auto increment id',+ `metrics_id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'metrics row id',`table_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'table id from table_meta',`policy_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'policy id from policy_meta',`snapshot_id` BIGINT(20) NOT NULL COMMENT 'Iceberg snapshot id',`metrics_value` MEDIUMTEXT NOT NULL COMMENT 'metrics value as JSON',`created_at` BIGINT(20) UNSIGNED NOT NULL COMMENT 'creation timestamp in milliseconds',- PRIMARY KEY (`id`),- UNIQUE KEY `uk_tid_pid_sid` (`table_id`, `policy_id`, `snapshot_id`),+ PRIMARY KEY (`metrics_id`),+ KEY `idx_tsm_tid_pid_sid` (`table_id`, `policy_id`, `snapshot_id`),KEY `idx_tsm_created_at` (`created_at`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT 'table snapshot metrics metadata';diff --git a/scripts/postgresql/schema-2.0.0-postgresql.sql b/scripts/postgresql/schema-2.0.0-postgresql.sqlindex 788e4a15d6..6047a316a8 100644--- a/scripts/postgresql/schema-2.0.0-postgresql.sql+++ b/scripts/postgresql/schema-2.0.0-postgresql.sql@@ -1297,43 +1297,43 @@ COMMENT ON COLUMN scheduled_commit_tasks.last_success IS 'last successful executCOMMENT ON COLUMN scheduled_commit_tasks.last_failure IS 'last failed execution time';CREATE TABLE IF NOT EXISTS table_maintenance_action (- id BIGSERIAL PRIMARY KEY,+ action_id BIGSERIAL PRIMARY KEY,job_id BIGINT,table_id BIGINT NOT NULL,policy_id BIGINT NOT NULL,- before_snapshot_id BIGINT,- after_snapshot_id BIGINT,- finished_at BIGINT NOT NULL DEFAULT 0,- created_at BIGINT NOT NULL+ before_metrics_id BIGINT,+ after_metrics_id BIGINT,+ created_at BIGINT NOT NULL,+ finished_at BIGINT NOT NULL DEFAULT 0);CREATE INDEX IF NOT EXISTS idx_tma_job_id ON table_maintenance_action (job_id);-- Soft slot: finished_at=0 is exclusive per table/policy (one in-flight finish).CREATE UNIQUE INDEX IF NOT EXISTS uk_tma_table_policy_finished ON table_maintenance_action (table_id, policy_id, finished_at);-CREATE INDEX IF NOT EXISTS idx_tma_before_sid ON table_maintenance_action (table_id, before_snapshot_id);-CREATE INDEX IF NOT EXISTS idx_tma_after_sid ON table_maintenance_action (table_id, after_snapshot_id);+CREATE INDEX IF NOT EXISTS idx_tma_before_metrics ON table_maintenance_action (before_metrics_id);+CREATE INDEX IF NOT EXISTS idx_tma_after_metrics ON table_maintenance_action (after_metrics_id);CREATE INDEX IF NOT EXISTS idx_tma_created_at ON table_maintenance_action (created_at);COMMENT ON TABLE table_maintenance_action IS 'table maintenance action metadata';-COMMENT ON COLUMN table_maintenance_action.id IS 'auto increment id';+COMMENT ON COLUMN table_maintenance_action.action_id IS 'maintenance action id';COMMENT ON COLUMN table_maintenance_action.job_id IS 'job run id, maps to job_run_meta.job_run_id';COMMENT ON COLUMN table_maintenance_action.table_id IS 'table id from table_meta';COMMENT ON COLUMN table_maintenance_action.policy_id IS 'policy id from policy_meta';-COMMENT ON COLUMN table_maintenance_action.before_snapshot_id IS 'Iceberg snapshot id before maintenance, null until sampled';-COMMENT ON COLUMN table_maintenance_action.after_snapshot_id IS 'Iceberg snapshot id after maintenance, null while pending';-COMMENT ON COLUMN table_maintenance_action.finished_at IS 'finish millis, 0 = soft in-flight slot (one per table/policy)';+COMMENT ON COLUMN table_maintenance_action.before_metrics_id IS 'table_snapshot_metrics.metrics_id for S0 sample';+COMMENT ON COLUMN table_maintenance_action.after_metrics_id IS 'table_snapshot_metrics.metrics_id for S1 sample';COMMENT ON COLUMN table_maintenance_action.created_at IS 'creation timestamp in milliseconds';+COMMENT ON COLUMN table_maintenance_action.finished_at IS 'finish millis, 0 = soft in-flight slot (one per table/policy)';CREATE TABLE IF NOT EXISTS table_snapshot_metrics (- id BIGSERIAL PRIMARY KEY,+ metrics_id BIGSERIAL PRIMARY KEY,table_id BIGINT NOT NULL,policy_id BIGINT NOT NULL,snapshot_id BIGINT NOT NULL,metrics_value TEXT NOT NULL,created_at BIGINT NOT NULL);-CREATE UNIQUE INDEX IF NOT EXISTS uk_tid_pid_sid ON table_snapshot_metrics (table_id, policy_id, snapshot_id);+CREATE INDEX IF NOT EXISTS idx_tsm_tid_pid_sid ON table_snapshot_metrics (table_id, policy_id, snapshot_id);CREATE INDEX IF NOT EXISTS idx_tsm_created_at ON table_snapshot_metrics (created_at);COMMENT ON TABLE table_snapshot_metrics IS 'table snapshot metrics metadata';-COMMENT ON COLUMN table_snapshot_metrics.id IS 'auto increment id';+COMMENT ON COLUMN table_snapshot_metrics.metrics_id IS 'metrics row id';COMMENT ON COLUMN table_snapshot_metrics.table_id IS 'table id from table_meta';COMMENT ON COLUMN table_snapshot_metrics.policy_id IS 'policy id from policy_meta';COMMENT ON COLUMN table_snapshot_metrics.snapshot_id IS 'Iceberg snapshot id';diff --git a/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql b/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sqlindex 237902df9f..828f7454ea 100644--- a/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql+++ b/scripts/postgresql/upgrade-1.3.0-to-2.0.0-postgresql.sql@@ -270,43 +270,43 @@ COMMENT ON COLUMN scheduled_commit_tasks.last_success IS 'last successful executCOMMENT ON COLUMN scheduled_commit_tasks.last_failure IS 'last failed execution time';CREATE TABLE IF NOT EXISTS table_maintenance_action (- id BIGSERIAL PRIMARY KEY,+ action_id BIGSERIAL PRIMARY KEY,job_id BIGINT,table_id BIGINT NOT NULL,policy_id BIGINT NOT NULL,- before_snapshot_id BIGINT,- after_snapshot_id BIGINT,- finished_at BIGINT NOT NULL DEFAULT 0,- created_at BIGINT NOT NULL+ before_metrics_id BIGINT,+ after_metrics_id BIGINT,+ created_at BIGINT NOT NULL,+ finished_at BIGINT NOT NULL DEFAULT 0);CREATE INDEX IF NOT EXISTS idx_tma_job_id ON table_maintenance_action (job_id);-- Soft slot: finished_at=0 is exclusive per table/policy (one in-flight finish).CREATE UNIQUE INDEX IF NOT EXISTS uk_tma_table_policy_finished ON table_maintenance_action (table_id, policy_id, finished_at);-CREATE INDEX IF NOT EXISTS idx_tma_before_sid ON table_maintenance_action (table_id, before_snapshot_id);-CREATE INDEX IF NOT EXISTS idx_tma_after_sid ON table_maintenance_action (table_id, after_snapshot_id);+CREATE INDEX IF NOT EXISTS idx_tma_before_metrics ON table_maintenance_action (before_metrics_id);+CREATE INDEX IF NOT EXISTS idx_tma_after_metrics ON table_maintenance_action (after_metrics_id);CREATE INDEX IF NOT EXISTS idx_tma_created_at ON table_maintenance_action (created_at);COMMENT ON TABLE table_maintenance_action IS 'table maintenance action metadata';-COMMENT ON COLUMN table_maintenance_action.id IS 'auto increment id';+COMMENT ON COLUMN table_maintenance_action.action_id IS 'maintenance action id';COMMENT ON COLUMN table_maintenance_action.job_id IS 'job run id, maps to job_run_meta.job_run_id';COMMENT ON COLUMN table_maintenance_action.table_id IS 'table id from table_meta';COMMENT ON COLUMN table_maintenance_action.policy_id IS 'policy id from policy_meta';-COMMENT ON COLUMN table_maintenance_action.before_snapshot_id IS 'Iceberg snapshot id before maintenance, null until sampled';-COMMENT ON COLUMN table_maintenance_action.after_snapshot_id IS 'Iceberg snapshot id after maintenance, null while pending';-COMMENT ON COLUMN table_maintenance_action.finished_at IS 'finish millis, 0 = soft in-flight slot (one per table/policy)';+COMMENT ON COLUMN table_maintenance_action.before_metrics_id IS 'table_snapshot_metrics.metrics_id for S0 sample';+COMMENT ON COLUMN table_maintenance_action.after_metrics_id IS 'table_snapshot_metrics.metrics_id for S1 sample';COMMENT ON COLUMN table_maintenance_action.created_at IS 'creation timestamp in milliseconds';+COMMENT ON COLUMN table_maintenance_action.finished_at IS 'finish millis, 0 = soft in-flight slot (one per table/policy)';CREATE TABLE IF NOT EXISTS table_snapshot_metrics (- id BIGSERIAL PRIMARY KEY,+ metrics_id BIGSERIAL PRIMARY KEY,table_id BIGINT NOT NULL,policy_id BIGINT NOT NULL,snapshot_id BIGINT NOT NULL,metrics_value TEXT NOT NULL,created_at BIGINT NOT NULL);-CREATE UNIQUE INDEX IF NOT EXISTS uk_tid_pid_sid ON table_snapshot_metrics (table_id, policy_id, snapshot_id);+CREATE INDEX IF NOT EXISTS idx_tsm_tid_pid_sid ON table_snapshot_metrics (table_id, policy_id, snapshot_id);CREATE INDEX IF NOT EXISTS idx_tsm_created_at ON table_snapshot_metrics (created_at);COMMENT ON TABLE table_snapshot_metrics IS 'table snapshot metrics metadata';-COMMENT ON COLUMN table_snapshot_metrics.id IS 'auto increment id';+COMMENT ON COLUMN table_snapshot_metrics.metrics_id IS 'metrics row id';COMMENT ON COLUMN table_snapshot_metrics.table_id IS 'table id from table_meta';COMMENT ON COLUMN table_snapshot_metrics.policy_id IS 'policy id from policy_meta';COMMENT ON COLUMN table_snapshot_metrics.snapshot_id IS 'Iceberg snapshot id';