World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[MINOR] refactor(tms): Restructure TMS Managers and schedule Client/Planner/Expand (#14471)
MaSai4108cc040c01
diff --git a/core/src/main/java/org/apache/gravitino/maintenance/policy/MaintenancePolicyDefinitions.java b/core/src/main/java/org/apache/gravitino/maintenance/policy/MaintenancePolicyDefinitions.javaindex bfa3eeae8a..2a3e8539c2 100644--- a/core/src/main/java/org/apache/gravitino/maintenance/policy/MaintenancePolicyDefinitions.java+++ b/core/src/main/java/org/apache/gravitino/maintenance/policy/MaintenancePolicyDefinitions.java@@ -23,8 +23,11 @@ import com.google.common.collect.ImmutableMap;import java.util.Collection;import java.util.EnumMap;import java.util.Map;+import javax.annotation.Nullable;import org.apache.gravitino.config.ConfigEntry;+import org.apache.gravitino.policy.ExecutablePolicyContent;import org.apache.gravitino.policy.Policy;+import org.apache.gravitino.policy.PolicyContent;/*** Core registry of Iceberg maintenance policy definitions.@@ -91,6 +94,34 @@ public final class MaintenancePolicyDefinitions {return builtInType != null && BY_TYPE.containsKey(builtInType);}+ /**+ * @param content policy content, may be null+ * @return whether {@code content} is an instance of a registered maintenance content class+ */+ public static boolean isMaintenance(@Nullable PolicyContent content) {+ if (content == null) {+ return false;+ }+ for (Policy.BuiltInType type : BY_TYPE.keySet()) {+ if (type.contentClass().isInstance(content)) {+ return true;+ }+ }+ return false;+ }++ /**+ * @param content policy content, may be null+ * @return {@code timeTrigger} from an executable content, or null when absent+ */+ @Nullable+ public static String timeTrigger(@Nullable PolicyContent content) {+ if (!(content instanceof ExecutablePolicyContent)) {+ return null;+ }+ return ((ExecutablePolicyContent) content).executionSpec().timeTrigger();+ }+private static void register(EnumMap<Policy.BuiltInType, MaintenancePolicyDefinition> map,Policy.BuiltInType builtInType,diff --git a/core/src/test/java/org/apache/gravitino/maintenance/policy/TestMaintenanceMinIntervalConfigs.java b/core/src/test/java/org/apache/gravitino/maintenance/policy/TestMaintenanceMinIntervalConfigs.javaindex 9caf1ff493..bce9f320d2 100644--- a/core/src/test/java/org/apache/gravitino/maintenance/policy/TestMaintenanceMinIntervalConfigs.java+++ b/core/src/test/java/org/apache/gravitino/maintenance/policy/TestMaintenanceMinIntervalConfigs.java@@ -18,8 +18,13 @@*/package org.apache.gravitino.maintenance.policy;+import java.util.Set;import org.apache.gravitino.Config;+import org.apache.gravitino.MetadataObject;+import org.apache.gravitino.policy.IcebergDataCompactionContent;import org.apache.gravitino.policy.Policy;+import org.apache.gravitino.policy.PolicyContent;+import org.apache.gravitino.policy.PolicyContents;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Test;@@ -131,4 +136,32 @@ public class TestMaintenanceMinIntervalConfigs {MaintenanceMinIntervalConfigs.COMPACTION_MIN_INTERVAL_MS_KEY,compaction.minIntervalMsKey());}++ @Test+ void testContentHelpers() {+ Assertions.assertFalse(MaintenancePolicyDefinitions.isMaintenance((PolicyContent) null));+ Assertions.assertNull(MaintenancePolicyDefinitions.timeTrigger(null));+ Assertions.assertFalse(+ MaintenancePolicyDefinitions.isMaintenance(+ PolicyContents.custom(java.util.Map.of(), Set.of(MetadataObject.Type.TABLE), null)));++ IcebergDataCompactionContent content =+ (IcebergDataCompactionContent)+ PolicyContents.icebergDataCompaction(+ IcebergDataCompactionContent.DEFAULT_MIN_DATA_FILE_MSE,+ IcebergDataCompactionContent.DEFAULT_MIN_DELETE_FILE_NUMBER,+ IcebergDataCompactionContent.DEFAULT_DATA_FILE_MSE_WEIGHT,+ IcebergDataCompactionContent.DEFAULT_DELETE_FILE_NUMBER_WEIGHT,+ IcebergDataCompactionContent.DEFAULT_MAX_PARTITION_NUM,+ IcebergDataCompactionContent.DEFAULT_REWRITE_STRATEGY,+ IcebergDataCompactionContent.DEFAULT_SORT_ORDER,+ IcebergDataCompactionContent.DEFAULT_REWRITE_OPTIONS,+ "0 0 2 * * ?",+ null,+ null,+ null,+ null);+ Assertions.assertTrue(MaintenancePolicyDefinitions.isMaintenance(content));+ Assertions.assertEquals("0 0 2 * * ?", MaintenancePolicyDefinitions.timeTrigger(content));+ }}diff --git a/design-docs/table-maintenance-service-design.md b/design-docs/table-maintenance-service-design.mdindex 3fa9cd8883..b2bd1ce444 100644--- a/design-docs/table-maintenance-service-design.md+++ b/design-docs/table-maintenance-service-design.md@@ -39,7 +39,7 @@ multi-node-safe scheduler for expand and submit, and Spark still on the Job fram## 2. Goals1. Run TMS **in-process** on the main server so IRC can wake maintenance without HTTP.-2. After a successful Iceberg commit, **enqueue** commit-triggered work.+2. After a successful Iceberg commit, **schedule** commit-triggered work.3. **Reuse** the optimizer core (`Updater` / `Recommender` / job submit) inside that process.4. Keep Spark execution on the **Gravitino Job framework**; record each run for gates andValidation.@@ -123,7 +123,7 @@ TMS runs in-process on the Gravitino main server and uses db-scheduler. This chaparts:1. **Policy** — what to maintain, when to trigger, and non-sensitive job settings.-2. **Scheduling and commit** — how work is enqueued, claimed, and recorded.+2. **Scheduling and commit** — how work is scheduled, claimed, and recorded.### 5.0 Terminology: policy identity vs scheduler task kind@@ -153,10 +153,10 @@ task kind” for expand / cron-job / commit-job.TMS has two trigger paths that stay separate:- **crontab** — expand a policy into one-shot Spark submits (one type per submit).-- **onCommit** — after an IRC commit, enqueue one per-table commit-job; one pick runs a+- **onCommit** — after an IRC commit, schedule one per-table commit-job; one pick runs achained Spark Job for the allowed types.-Both paths **build an enqueue-time job snapshot** (tables, chain steps, merged `jobConf`) into+Both paths **build a schedule-time job snapshot** (tables, chain steps, merged `jobConf`) intodb-scheduler `task_data` before insert. The cron / commit pool pick **consumes that snapshot** —soft-slot claim, light in-flight checks, then `runJob` — and does **not** re-collect policies orrebuild `jobConf`. Both paths end with a short control-plane `runJob` on the Gravitino Job@@ -291,8 +291,8 @@ subject as `key:value` pairs separated by `;` (`:` only inside a pair):| --------------- | ------------------------------------- | ----------------------------------------------- || `policy-expand` | `policy:{policy_id}` | One long-lived lease per policy || `cron-job` | `table:{table_id};policy:{policy_id}` | One table + one policy |-| `cron-job` | `batch:{batch_id};policy:{policy_id}` | Snapshot-expiry coalesce; tables in `task_data` |-| `commit-job` | `table:{table_id}` | One coalesce key per table (no policy segment) |+| `cron-job` | `batch:{batch_id};policy:{policy_id}` | Snapshot-expiry merge; tables in `task_data` |+| `commit-job` | `table:{table_id}` | One merge key per table (no policy segment) |Merging extra tables into an open snapshot-expiry row **does not rename** `task_instance`; itupdates `task_data` (or inserts a new `batch:…` row and cancels the old `table:…` rows).@@ -368,19 +368,19 @@ When expand is due (expand pool):```mermaidflowchart TD- A[List attached tables in batches] --> B["Enqueue up to expand.enqueueBatchSize cron-jobs (default 100)"]+ A[List attached tables in batches] --> B["Schedule up to expand.scheduleBatchSize cron-jobs (default 100)"]B --> C[Keep expand row; set next crontab]```Example with `timeTrigger` `0 0 2 * * ?`: create inserts expand due next 02:00; at 02:00 expand insertsmany cron-jobs due now, then schedules itself for the next 02:00. Expand's due time is when-**enqueue** happens — not when Spark runs.+**schedule** happens — not when Spark runs.#### 5.2.2 `cron-job`-Expand writes these one-shot rows **with an enqueue-time job snapshot** in `task_data`+Expand writes these one-shot rows **with a schedule-time job snapshot** in `task_data`(metalake, table targets, one chain step, merged `jobConf` including auth overlays).-`minIntervalMs` is gated at expand / enqueue so cooled-down tables are not scheduled.+`minIntervalMs` is gated at expand / schedule so cooled-down tables are not scheduled.Most types use one table per job (`table:{table_id};policy:{policy_id}`). Batched**snapshot-expiry** may use `batch:{batch_id};policy:{policy_id}` (one snapshot covering severalsame-catalog tables; member table ids live in `task_data`).@@ -391,7 +391,7 @@ pick (no partial submits) before the one-shot row is removed:```mermaidflowchart TD- A[Read enqueue-time snapshot from task_data] --> B{Any snapshot table in-flight?}+ A[Read schedule-time snapshot from task_data] --> B{Any snapshot table in-flight?}B -->|yes| Z[Delete cron-job; stop]B -->|no| C[For each table: insert table_maintenance_job + runJob]C --> D[Delete cron-job; return]@@ -417,18 +417,18 @@ A later wake-up sees the fresher state.After a successful IRC table update in the same JVM, an `EventListenerPlugin` upserts onecommit-job for that table (`table:{table_id}`). Register it with `gravitino.eventListener.names` /-`{name}.class`. The listener does **not** submit Spark; enqueue (on the listener thread path)+`{name}.class`. The listener does **not** submit Spark; schedule (on the listener thread path)builds the onCommit chain and snapshot, then inserts the row.-**Enqueue** (before the commit-job row exists):+**Schedule** (before the commit-job row exists):1. Collect nearest policies with `commitTrigger=true` in order compaction →manifest-rewrite → snapshot-expiry (orphan cleanup is timeTrigger-only).2. Drop members still inside `minIntervalMs`.3. Fail closed if effective Gravitino / IRC auth bags disagree across the remaining chain.-4. Build an enqueue-time job snapshot (table target, ordered chain steps, merged `jobConf`)+4. Build a schedule-time job snapshot (table target, ordered chain steps, merged `jobConf`)into `task_data`.-5. `scheduleIfNotExists` due now. Bursts coalesce: an existing row keeps its original+5. `scheduleIfNotExists` due now. Bursts merge: an existing row keeps its original`task_data` (no overwrite).If the chain is empty after gates, or snapshot build fails, **skip** — do not insert a row.@@ -437,7 +437,7 @@ When a commit-job is due (commit pool) — keep the callback short; Spark runs e```mermaidflowchart TD- A[Read enqueue-time snapshot from task_data] --> B{Any snapshot type in-flight?}+ A[Read schedule-time snapshot from task_data] --> B{Any snapshot type in-flight?}B -->|yes| Z[Delete commit-job; stop]B -->|no| C[Claim soft slots for every chain policy]C --> D[runJob from snapshot jobConf / chain]@@ -537,7 +537,7 @@ onCommit does not. HTTP / Kafka commit ingress is out of scope.| `gravitino.maintenance.scheduler.pollingIntervalMs` | `10000` | Poll interval || `gravitino.maintenance.scheduler.heartbeatIntervalMs` | `60000` | Heartbeat while callback runs || `gravitino.maintenance.scheduler.missedHeartbeatsLimit` | `6` | Misses before dead |-| `gravitino.maintenance.expand.enqueueBatchSize` | `100` | Max cron-jobs per expand pick |+| `gravitino.maintenance.expand.scheduleBatchSize` | `100` | Max cron-jobs per expand pick |### 7.3 Minimum interval@@ -602,7 +602,7 @@ gravitino.maintenance.ircAuth.oauthCredential = client_id:client_secret| Phase | Work || ----- | ------------------------------------------------------------------------------------- || 1 | `TableMaintenanceRESTFeature`; start/stop three db-scheduler pools |-| 2 | `PolicyExpandPipeline` + `MaintenanceSparkSubmitPipeline` + gates |+| 2 | `PolicyExpandPipeline` + `MaintenanceCronSubmitPipeline` + gates || 3 | Migrations: `scheduled_*_tasks`, `table_maintenance_action`, `table_snapshot_metrics` || 4 | IRC EventListener upserts commit-job; policy create → INSERT expand; Job listener || 5 | Metrics, shutdown, docs; `gravitino.conf` client auth; privilege docs |@@ -616,7 +616,7 @@ Implementation checklist:**inside** the Spark Job; then DELETE the scheduled row.- [ ] Validation reads metrics per type in the run; purge unreferenced history by TTL/N.- [ ] Commit path: one chained Job; soft slot per chain policy (same `job_id`); full chain in- `maintenance_types` / `policy_ids`; orphan crontab-only; coalesce on `table:{table_id}`; Spark+ `maintenance_types` / `policy_ids`; orphan crontab-only; merge on `table:{table_id}`; Spark`jobOptions` merge uses max.- [ ] Client auth from `gravitino.conf` only; reject credential-shaped keys in policy`jobOptions`.diff --git a/docs/table-maintenance-service/optimizer-configuration.md b/docs/table-maintenance-service/optimizer-configuration.mdindex 599aeef16e..f1b0e2f2ec 100644--- a/docs/table-maintenance-service/optimizer-configuration.md+++ b/docs/table-maintenance-service/optimizer-configuration.md@@ -40,7 +40,7 @@ For in-process Table Maintenance Service (TMS), client credentials are **clusterthe prefixes below in `gravitino.conf`. Do not store passwords, OAuth secrets, or keytab paths in policycontent. Values may be plaintext or secret-manager references when the deployment supports them.-When building the enqueue-time job snapshot, `gravitino.maintenance.gravitinoAuth.*` overlays+When building the schedule-time job snapshot, `gravitino.maintenance.gravitinoAuth.*` overlayspolicy `updaterOptions` (serialized into `updater_options` for Spark → Gravitino callbacks), and`gravitino.maintenance.ircAuth.*` overlays policy `jobOptions`. Auth wins on duplicate keys.Non-template IRC keys are then packed into `spark_conf` as `spark.sql.catalog.<catalog>.*` so@@ -61,11 +61,11 @@ gravitino.maintenance.gravitinoAuth.uri = http://localhost:8090### TMS commit-job (IRC update → chained Spark)When Iceberg REST runs as an auxiliary service in the same JVM, register the TMS listener so a-successful IRC table update upserts a one-shot `commit-job` / `{table_id}` (bursts coalesce and-keep the first snapshot). **At enqueue**, TMS collects nearest policies with+successful IRC table update upserts a one-shot `commit-job` / `{table_id}` (bursts merge and+keep the first snapshot). **At schedule**, TMS collects nearest policies with`commitTrigger=true` in order compaction → manifest-rewrite → snapshot-expiry, drops membersstill inside `minIntervalMs`, **fails closed when effective `gravitinoAuth` / `ircAuth` bags-disagree across the chain**, and writes an enqueue-time job snapshot (`task_data`: tables,+disagree across the chain**, and writes a schedule-time job snapshot (`task_data`: tables,operations, merged `jobConf`). The commit pool **consumes that snapshot**: if any snapshottype is still in-flight it deletes the row and stops; otherwise it claims a soft slot for**every** chain policy and submits one chained `builtin-iceberg-maintenance-task` Spark job.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 401f006fbf..4f36d36e36 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@@ -67,6 +67,18 @@ public final class MaintenanceActionHttpClient implements AutoCloseable {private static final int DEFAULT_OAUTH_EXPIRES_IN_SECONDS = 300;private static final int ERROR_BODY_TRUNCATE = 512;+ /**+ * Shared mapper for TMS HTTP JSON (requests + OAuth token responses).+ *+ * <p>Copied from {@link JsonUtils#objectMapper()} with unknown properties ignored so IdP token+ * payloads (e.g. Keycloak {@code refresh_expires_in}) do not fail deserialization — same stance+ * as client-java {@code ObjectMapperProvider}.+ */+ private static final ObjectMapper MAPPER =+ JsonUtils.objectMapper()+ .copy()+ .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);+private final ObjectMapper mapper;private final String baseUri;private final String metalakeName;@@ -102,13 +114,7 @@ public final class MaintenanceActionHttpClient implements AutoCloseable {Preconditions.checkArgument(StringUtils.isNotBlank(metalake), "updater_options must contain metalake");GravitinoAuthSettings auth = GravitinoAuthSettings.from(new OptimizerConfig(properties));- // 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);+ return new MaintenanceActionHttpClient(MAPPER, uri.trim(), metalake.trim(), auth);}/**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 5844312e8c..0f1d2752a0 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@@ -50,60 +50,36 @@ import org.slf4j.Logger;import org.slf4j.LoggerFactory;/**- * TMS Spark entry for cron (§5.2.2) and commit-chain (§5.2.3) {@code runJob} submits.+ * TMS Spark job: sample before-metrics → gate → run Iceberg procedure → close soft slot.*- * <p>Not a user-facing CLI. Operators / optimizer keep using the four standalone {@code- * Iceberg*Job} templates. This class is launched only via the built-in job template; program- * arguments are template-expanded {@code jobConf} values.- *- * <p>Dispatches by {@code maintenance_types} (one wire name or a comma-separated commit chain).- * Reuses procedure SQL builders from the standalone {@code Iceberg*Job} classes. Continue / stop- * (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} 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.+ * <p>Started only from the built-in template (cron or commit-chain). {@code maintenance_types} is+ * one type or a comma-separated chain; {@code policy_ids} / {@code action_ids} align 1:1 with those+ * types. Soft-slot HTTP callbacks use {@code action_ids}.*/public class IcebergMaintenanceJob implements BuiltInJob {private static final Logger LOG = LoggerFactory.getLogger(IcebergMaintenanceJob.class);- /** Built-in template name submitted by TMS cron / commit. */+ /** Built-in template name used by TMS submit. */public static final String NAME =JobTemplateProvider.BUILTIN_NAME_PREFIX + "iceberg-maintenance-task";- /**- * JobConf key for procedure dispatch ({@code maintenance_types}). One wire name, or a- * comma-separated commit chain. Required; no template default.- */+ // Bump when template behavior / args / class wiring changes (required by built-in registration).+ private static final String VERSION = "v1";++ /** JobConf: one wire name, or comma-separated commit chain. */public static final String MAINTENANCE_TYPES_KEY = "maintenance_types";- /**- * JobConf key for table targets ({@code tables}): JSON array of {@code table_id}, {@code- * catalog_name}, {@code table_identifier}. Single- and multi-table TMS submits use the same- * shape; {@code table_id} is system-filled by enqueue/submit.- */+ /** JobConf: JSON array of {@code table_id}, {@code catalog_name}, {@code table_identifier}. */public static final String TABLES_KEY = "tables";- /**- * JobConf key for policy entity ids parallel to {@link #MAINTENANCE_TYPES_KEY} (comma-separated).- * Required so metrics/finish callbacks can attribute soft slots when one job binds multiple- * policies.- */+ /** JobConf: policy ids parallel to {@link #MAINTENANCE_TYPES_KEY}. */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.- */+ /** JobConf: soft-slot action ids parallel to {@link #POLICY_IDS_KEY}. */public static final String ACTION_IDS_KEY = "action_ids";- private static final String VERSION = "v1";-- /** Supported {@code maintenance_types} wire values. */+ /** Values accepted in {@code maintenance_types}. */public enum MaintenanceType {REWRITE_DATA_FILES("rewrite_data_files"),REWRITE_MANIFESTS("rewrite_manifests"),@@ -117,14 +93,14 @@ public class IcebergMaintenanceJob implements BuiltInJob {}/**- * @return wire value used in jobConf+ * @return jobConf wire value*/public String wireName() {return wireName;}/**- * @param raw jobConf {@code maintenance_types} segment+ * @param raw one segment from {@code maintenance_types}* @return parsed type*/public static MaintenanceType fromWire(@Nullable String raw) {@@ -149,12 +125,10 @@ public class IcebergMaintenanceJob implements BuiltInJob {public SparkJobTemplate jobTemplate() {return SparkJobTemplate.builder().withName(NAME)- .withComment(- "TMS Iceberg maintenance: S0 sample/gate, procedure dispatch (single or commit-chain),"- + " S1 finish")+ .withComment("TMS Iceberg maintenance (before-metrics gate, procedure, finish soft slot)").withExecutable(resolveExecutable(IcebergMaintenanceJob.class)).withClassName(IcebergMaintenanceJob.class.getName())- .withArguments(buildArguments())+ .withArguments(templateArguments()).withConfigs(IcebergSparkConfigUtils.buildTemplateSparkConfigs()).withCustomFields(Collections.singletonMap(JobTemplateProvider.PROPERTY_VERSION_KEY, VERSION))@@ -162,10 +136,9 @@ public class IcebergMaintenanceJob implements BuiltInJob {}/**- * Spark application entry used by the job executor after template expansion. Not a supported- * operator CLI.+ * Spark entry after template expansion.*- * @param args template-expanded jobConf as named arguments+ * @param args named jobConf arguments*/public static void main(String[] args) {int code = run(args);@@ -175,25 +148,25 @@ public class IcebergMaintenanceJob implements BuiltInJob {}/**- * @param args template-expanded jobConf as named arguments- * @return process exit code ({@code 0} success, {@code 1} failure)+ * @param args named jobConf arguments+ * @return {@code 0} on success, {@code 1} on failure*/static int run(String[] args) {- Map<String, String> argMap = IcebergJobUtils.parseArguments(args);+ Map<String, String> argsByName = IcebergJobUtils.parseArguments(args);List<MaintenanceType> types;List<Long> policyIds;List<Long> actionIds;- List<TableTarget> tables;+ List<TargetTable> tables;Map<String, String> updaterOptions;try {- types = parseMaintenanceTypes(argMap.get("maintenance-types"));- policyIds = parsePolicyIds(argMap.get("policy-ids"), types.size());- actionIds = parseActionIds(argMap.get("action-ids"), types.size());- tables = parseTables(IcebergJobUtils.nullIfUnresolvedPlaceholder(argMap.get("tables")));+ types = parseMaintenanceTypes(argsByName.get("maintenance-types"));+ policyIds = parseIdList("policy_ids", argsByName.get("policy-ids"), types.size());+ actionIds = parseIdList("action_ids", argsByName.get("action-ids"), types.size());+ tables = parseTables(IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("tables")));updaterOptions =parseUpdaterOptions(- IcebergJobUtils.nullIfUnresolvedPlaceholder(argMap.get("updater-options")));+ IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("updater-options")));} catch (IllegalArgumentException | IllegalStateException e) {LOG.error("Invalid TMS maintenance arguments: {}", e.getMessage());return 1;@@ -205,7 +178,8 @@ public class IcebergMaintenanceJob implements BuiltInJob {: "chain:" + types.stream().map(t -> t.wireName).collect(Collectors.joining(","));SparkSession.Builder sparkBuilder =SparkSession.builder().appName("Gravitino Iceberg Maintenance Task (" + appLabel + ")");- String sparkConfJson = IcebergJobUtils.nullIfUnresolvedPlaceholder(argMap.get("spark-conf"));+ String sparkConfJson =+ IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("spark-conf"));if (sparkConfJson != null && !sparkConfJson.isEmpty()) {IcebergJobUtils.parseCustomSparkConfigs(sparkConfJson).forEach(sparkBuilder::config);}@@ -214,61 +188,53 @@ public class IcebergMaintenanceJob implements BuiltInJob {IcebergJobUtils.requireIcebergSparkRuntimeOrExit(spark);try (MaintenanceActionHttpClient client =MaintenanceActionHttpClient.fromUpdaterOptions(updaterOptions)) {- // 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<>();+ // Close every soft slot even if a later type/table never runs.+ Set<String> closedSlots = new HashSet<>();try {- for (TableTarget table : tables) {+ for (TargetTable table : tables) {for (int i = 0; i < types.size(); i++) {MaintenanceType type = types.get(i);long policyId = policyIds.get(i);long actionId = actionIds.get(i);+ String slot = table.tableId + ":" + policyId;try {- SnapshotSample s0 =- sampleSnapshot(spark, table.catalogName, table.tableIdentifier, type);- if (!reportBeforeMetrics(client, actionId, table.tableId, policyId, s0)) {+ BeforeSample before =+ sampleBefore(spark, table.catalogName, table.tableIdentifier, type);+ if (!tryReportBeforeMetrics(client, actionId, table.tableId, policyId, before)) {LOG.info(- "TMS type {} stopped for action_id {} table {} policy {}:"- + " before-metrics claim failed (abandoned or unbound)",+ "TMS type {} stopped for action_id {} table {} policy {}: before-metrics"+ + " failed (abandoned or unbound)",type.wireName,actionId,table.tableId,policyId);continue;}-- if (s0.snapshotId != s0.headSnapshotId) {+ if (before.snapshotId != before.headSnapshotId) {LOG.info(- "TMS type {} skipped for action_id {} table {} policy {} due to snapshot drift"- + " (s0={} head={})",+ "TMS type {} skipped for action_id {} table {} policy {}: snapshot drifted"+ + " (sampled={} head={})",type.wireName,actionId,table.tableId,policyId,- s0.snapshotId,- s0.headSnapshotId);+ before.snapshotId,+ before.headSnapshotId);continue;}-- if (!MaintenanceTriggerGate.shouldMaintain(type, argMap, s0.metricsJson)) {+ if (!MaintenanceTriggerGate.shouldMaintain(type, argsByName, before.metricsJson)) {LOG.info(- "TMS type {} skipped for action_id {} table {} policy {} due to in-Spark"- + " recommend skip",+ "TMS type {} skipped for action_id {} table {} policy {}: trigger-expr skip",type.wireName,actionId,table.tableId,policyId);continue;}-- runProcedure(spark, type, table.catalogName, table.tableIdentifier, argMap);- SnapshotSample s1 =- sampleSnapshot(spark, table.catalogName, table.tableIdentifier, type);- reportMetricsQuietly(- client, actionId, table.tableId, policyId, s1, /*after=*/ true);+ runProcedure(spark, type, table.catalogName, table.tableIdentifier, argsByName);} finally {- finishQuietly(client, actionId, table.tableId, policyId);- finishedSlots.add(slotKey(table.tableId, policyId));+ closeSoftSlot(client, actionId, table.tableId, policyId);+ closedSlots.add(slot);}}}@@ -277,12 +243,12 @@ public class IcebergMaintenanceJob implements BuiltInJob {LOG.error("TMS Iceberg maintenance failed for action_ids {}", actionIds, e);return 1;} finally {- for (TableTarget table : tables) {+ for (TargetTable table : tables) {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, actionId, table.tableId, policyId);+ if (!closedSlots.contains(table.tableId + ":" + policyId)) {+ closeSoftSlot(client, actionId, table.tableId, policyId);}}}@@ -291,7 +257,7 @@ public class IcebergMaintenanceJob implements BuiltInJob {}}- private static List<TableTarget> parseTables(@Nullable String tablesJson) {+ private static List<TargetTable> parseTables(@Nullable String tablesJson) {if (tablesJson == null || tablesJson.trim().isEmpty()) {throw new IllegalArgumentException("tables JSON is required (array of table_id, catalog_name, table_identifier)");@@ -303,7 +269,7 @@ public class IcebergMaintenanceJob implements BuiltInJob {if (raw == null || raw.isEmpty()) {throw new IllegalArgumentException("tables must not be empty");}- List<TableTarget> tables = new ArrayList<>(raw.size());+ List<TargetTable> tables = new ArrayList<>(raw.size());for (Map<String, Object> entry : raw) {if (entry == null) {throw new IllegalArgumentException("tables entry must not be null");@@ -325,7 +291,7 @@ public class IcebergMaintenanceJob implements BuiltInJob {throw new IllegalArgumentException("tables catalog_name and table_identifier must not be blank");}- tables.add(new TableTarget(tableId, catalogName, tableIdentifier));+ tables.add(new TargetTable(tableId, catalogName, tableIdentifier));}return tables;} catch (JsonProcessingException e) {@@ -355,38 +321,34 @@ public class IcebergMaintenanceJob implements BuiltInJob {return types;}- private static List<Long> parsePolicyIds(@Nullable String policyIds, int expectedCount) {- String raw = IcebergJobUtils.nullIfUnresolvedPlaceholder(policyIds);- if (raw == null || raw.trim().isEmpty()) {- throw new IllegalArgumentException("policy_ids is required");+ private static List<Long> parseIdList(String fieldName, @Nullable String raw, int expectedCount) {+ String value = IcebergJobUtils.nullIfUnresolvedPlaceholder(raw);+ if (value == null || value.trim().isEmpty()) {+ throw new IllegalArgumentException(fieldName + " is required");}- List<Long> parsed = new ArrayList<>();- for (String part : raw.split(",")) {+ List<Long> ids = new ArrayList<>();+ for (String part : value.split(",")) {String trimmed = part.trim();if (trimmed.isEmpty()) {continue;}try {- long policyId = Long.parseLong(trimmed);- if (policyId <= 0) {- throw new IllegalArgumentException("policy_ids must be positive longs: " + trimmed);+ long id = Long.parseLong(trimmed);+ if (id <= 0) {+ throw new IllegalArgumentException(fieldName + " must be positive longs: " + trimmed);}- parsed.add(policyId);+ ids.add(id);} catch (NumberFormatException e) {- throw new IllegalArgumentException("policy_ids must be longs: " + trimmed, e);+ throw new IllegalArgumentException(fieldName + " must be longs: " + trimmed, e);}}- if (parsed.size() != expectedCount) {+ if (ids.size() != expectedCount) {throw new IllegalArgumentException(String.format(- "policy_ids count %s must match maintenance_types count %s",- parsed.size(), expectedCount));+ "%s count %s must match maintenance_types count %s",+ fieldName, ids.size(), expectedCount));}- return parsed;- }-- private static String slotKey(long tableId, long policyId) {- return tableId + ":" + policyId;+ return ids;}private static void runProcedure(@@ -394,20 +356,23 @@ public class IcebergMaintenanceJob implements BuiltInJob {MaintenanceType type,String catalogName,String tableIdentifier,- Map<String, String> argMap)+ Map<String, String> argsByName)throws Exception {switch (type) {case REWRITE_DATA_FILES:{- String strategy = firstNonBlank(argMap.get("strategy"), "binpack");+ String strategy = IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("strategy"));+ if (strategy == null || strategy.isEmpty()) {+ strategy = "binpack";+ }String sql =IcebergRewriteDataFilesJob.buildProcedureCall(catalogName,tableIdentifier,strategy,- IcebergJobUtils.nullIfUnresolvedPlaceholder(argMap.get("sort-order")),- IcebergJobUtils.nullIfUnresolvedPlaceholder(argMap.get("where")),- IcebergJobUtils.nullIfUnresolvedPlaceholder(argMap.get("options")));+ IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("sort-order")),+ IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("where")),+ IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("options")));LOG.info("Executing TMS rewrite_data_files: {}", sql);spark.sql(sql).collect();break;@@ -415,15 +380,15 @@ public class IcebergMaintenanceJob implements BuiltInJob {case REWRITE_MANIFESTS:{IcebergRewriteManifestsJob.validateUseCaching(- IcebergJobUtils.nullIfUnresolvedPlaceholder(argMap.get("use-caching")));+ IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("use-caching")));IcebergRewriteManifestsJob.validateSpecId(- IcebergJobUtils.nullIfUnresolvedPlaceholder(argMap.get("spec-id")));+ IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("spec-id")));String sql =IcebergRewriteManifestsJob.buildProcedureCall(catalogName,tableIdentifier,- IcebergJobUtils.nullIfUnresolvedPlaceholder(argMap.get("use-caching")),- IcebergJobUtils.nullIfUnresolvedPlaceholder(argMap.get("spec-id")));+ IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("use-caching")),+ IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("spec-id")));LOG.info("Executing TMS rewrite_manifests: {}", sql);spark.sql(sql).collect();break;@@ -431,16 +396,16 @@ public class IcebergMaintenanceJob implements BuiltInJob {case EXPIRE_SNAPSHOTS:{String retainLast =- IcebergJobUtils.nullIfUnresolvedPlaceholder(argMap.get("retain-last"));+ IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("retain-last"));IcebergExpireSnapshotsJob.validateRetainLast(retainLast);boolean streamResults =IcebergExpireSnapshotsJob.parseStreamResults(- IcebergJobUtils.nullIfUnresolvedPlaceholder(argMap.get("stream-results")));+ IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("stream-results")));String sql =IcebergExpireSnapshotsJob.buildProcedureCall(catalogName,tableIdentifier,- IcebergJobUtils.nullIfUnresolvedPlaceholder(argMap.get("older-than")),+ IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("older-than")),retainLast,streamResults);LOG.info("Executing TMS expire_snapshots: {}", sql);@@ -459,9 +424,9 @@ public class IcebergMaintenanceJob implements BuiltInJob {Map<String, String> orphanOpts = new HashMap<>();orphanOpts.put("catalog", catalogName);orphanOpts.put("table", tableIdentifier);- putIfPresent(orphanOpts, "older-than", argMap.get("older-than"));- putIfPresent(orphanOpts, "location", argMap.get("location"));- putIfPresent(orphanOpts, "dry-run", argMap.get("dry-run"));+ putIfPresent(orphanOpts, "older-than", argsByName.get("older-than"));+ putIfPresent(orphanOpts, "location", argsByName.get("location"));+ putIfPresent(orphanOpts, "dry-run", argsByName.get("dry-run"));IcebergRemoveOrphanFilesJob.execute(spark, orphanOpts);break;}@@ -470,9 +435,12 @@ public class IcebergMaintenanceJob implements BuiltInJob {}}- private static SnapshotSample sampleSnapshot(+ /**+ * Samples snapshot + metrics for the before-metrics gate. Re-reads HEAD after metrics so drift+ * can be detected.+ */+ private static BeforeSample sampleBefore(SparkSession spark, String catalogName, String tableIdentifier, MaintenanceType type) {- // Capture S0 first, then collect metrics (may take time), then re-read HEAD for the drift gate.long snapshotId = currentSnapshotId(spark, catalogName, tableIdentifier);Map<String, Object> payload = new HashMap<>();payload.put("maintenanceType", type.wireName());@@ -482,7 +450,7 @@ public class IcebergMaintenanceJob implements BuiltInJob {}long headSnapshotId = currentSnapshotId(spark, catalogName, tableIdentifier);try {- return new SnapshotSample(+ return new BeforeSample(snapshotId, headSnapshotId, JsonUtils.anyFieldMapper().writeValueAsString(payload));} catch (JsonProcessingException e) {throw new IllegalStateException("Failed to serialize metrics JSON", e);@@ -491,8 +459,8 @@ public class IcebergMaintenanceJob implements BuiltInJob {/*** Compaction metrics from the Iceberg files metadata table (same formulas as {@link- * IcebergUpdateStatsAndMetricsJob}). For partitioned tables, uses max partition MSE and sum of- * delete-file counts so any hot partition can trip {@code trigger-expr}.+ * IcebergUpdateStatsAndMetricsJob}). Partitioned tables use max partition MSE and sum of delete+ * files so any hot partition can trip {@code trigger-expr}.*/private static Map<String, Object> collectCompactionMetrics(SparkSession spark, String catalogName, String tableIdentifier) {@@ -543,8 +511,8 @@ public class IcebergMaintenanceJob implements BuiltInJob {private static long currentSnapshotId(SparkSession spark, String catalogName, String tableIdentifier) {- // Catch Exception (not Spark NoSuchTableException) so BuiltInJobTemplateProvider can load this- // class on the Gravitino server classpath, which does not ship Spark catalyst types.+ // Catch Exception (not Spark NoSuchTableException) so the Gravitino server can load this class+ // without Spark catalyst on the classpath.try {Table table =Spark3Util.loadIcebergTable(spark, String.format("%s.%s", catalogName, tableIdentifier));@@ -562,7 +530,7 @@ public class IcebergMaintenanceJob implements BuiltInJob {}}- private static void finishQuietly(+ private static void closeSoftSlot(MaintenanceActionHttpClient client, long actionId, long tableId, long policyId) {try {client.finish(actionId, new MaintenanceActionFinishRequest(tableId, policyId));@@ -577,16 +545,16 @@ public class IcebergMaintenanceJob implements BuiltInJob {}/**- * S0 metrics are a hard gate: failure means the soft slot is abandoned/unbound, so maintenance- * must not run.+ * Reports before-metrics. Failure means the soft slot is abandoned/unbound — do not run the+ * procedure.*/- private static boolean reportBeforeMetrics(+ private static boolean tryReportBeforeMetrics(MaintenanceActionHttpClient client,long actionId,long tableId,long policyId,- SnapshotSample sample) {- if (sample == null || sample.metricsJson == null || sample.metricsJson.trim().isEmpty()) {+ BeforeSample sample) {+ if (sample.metricsJson == null || sample.metricsJson.trim().isEmpty()) {return false;}try {@@ -607,37 +575,6 @@ public class IcebergMaintenanceJob implements BuiltInJob {}}- private static void reportMetricsQuietly(- MaintenanceActionHttpClient client,- long actionId,- long tableId,- long policyId,- SnapshotSample sample,- boolean after) {- if (sample == null || sample.metricsJson == null || sample.metricsJson.trim().isEmpty()) {- return;- }- try {- MaintenanceActionMetricsRequest request =- new MaintenanceActionMetricsRequest(- tableId, policyId, sample.snapshotId, sample.metricsJson);- if (after) {- client.reportAfterMetrics(actionId, request);- } else {- client.reportBeforeMetrics(actionId, request);- }- } catch (Exception e) {- LOG.warn(- "Best-effort TMS {} metrics report failed for action_id {} table {} policy {} snapshot {}",- after ? "after" : "before",- actionId,- tableId,- policyId,- sample.snapshotId,- e);- }- }-private static Map<String, String> parseUpdaterOptions(@Nullable String json) {if (json == null || json.trim().isEmpty()) {return Collections.emptyMap();@@ -651,36 +588,6 @@ public class IcebergMaintenanceJob implements BuiltInJob {}}- 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(trimmed);- if (parsed <= 0) {- throw new IllegalArgumentException("action_ids must be positive longs: " + trimmed);- }- ids.add(parsed);- } catch (NumberFormatException e) {- throw new IllegalArgumentException("action_ids must be longs: " + trimmed, e);- }- }- if (ids.size() != expectedCount) {- throw new IllegalArgumentException(- String.format(- "action_ids count %s must match maintenance_types count %s",- ids.size(), expectedCount));- }- return ids;- }-private static void putIfPresent(Map<String, String> target, String key, @Nullable String raw) {String value = IcebergJobUtils.nullIfUnresolvedPlaceholder(raw);if (value != null && !value.isEmpty()) {@@ -688,13 +595,7 @@ public class IcebergMaintenanceJob implements BuiltInJob {}}- private static String firstNonBlank(@Nullable String value, String defaultValue) {- String normalized = IcebergJobUtils.nullIfUnresolvedPlaceholder(value);- return normalized == null || normalized.isEmpty() ? defaultValue : normalized;- }-- private static List<String> buildArguments() {- // Named args are the Spark job-executor wiring for expanded jobConf — not a user CLI.+ private static List<String> templateArguments() {return Arrays.asList("--maintenance-types","{{maintenance_types}}",@@ -734,24 +635,26 @@ public class IcebergMaintenanceJob implements BuiltInJob {"{{rules:-}}");}- private static final class TableTarget {+ /** One table this job should maintain. */+ private static final class TargetTable {private final long tableId;private final String catalogName;private final String tableIdentifier;- private TableTarget(long tableId, String catalogName, String tableIdentifier) {+ private TargetTable(long tableId, String catalogName, String tableIdentifier) {this.tableId = tableId;this.catalogName = catalogName;this.tableIdentifier = tableIdentifier;}}- private static final class SnapshotSample {+ /** Before-metrics sample: snapshot at sample time, HEAD after metrics, and metrics JSON. */+ private static final class BeforeSample {private final long snapshotId;private final long headSnapshotId;private final String metricsJson;- private SnapshotSample(long snapshotId, long headSnapshotId, String metricsJson) {+ private BeforeSample(long snapshotId, long headSnapshotId, String metricsJson) {this.snapshotId = snapshotId;this.headSnapshotId = headSnapshotId;this.metricsJson = metricsJson;diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/TestBuiltInJobTemplateProvider.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/TestBuiltInJobTemplateProvider.javaindex cf590b32d6..0fb7adeeb2 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@@ -78,21 +78,34 @@ public class TestBuiltInJobTemplateProvider {List<? extends JobTemplate> templates = provider.jobTemplates();for (JobTemplate template : templates) {- String version = template.customFields().get(JobTemplateProvider.PROPERTY_VERSION_KEY);- assertNotNull(version, "Template should have version property: " + template.name());+ Map<String, String> fields = template.customFields();+ assertTrue(+ fields != null && fields.containsKey(JobTemplateProvider.PROPERTY_VERSION_KEY),+ "Template missing version: " + template.name());+ String version = fields.get(JobTemplateProvider.PROPERTY_VERSION_KEY);assertTrue(version.matches(JobTemplateProvider.VERSION_VALUE_PATTERN),"Version should match pattern v\\d+: " + version);}}+ @Test+ public void testIcebergMaintenanceTaskHasVersion() {+ JobTemplate template =+ new BuiltInJobTemplateProvider()+ .jobTemplates().stream()+ .filter(t -> t.name().equals("builtin-iceberg-maintenance-task"))+ .findFirst()+ .orElseThrow();+ assertEquals("v1", template.customFields().get(JobTemplateProvider.PROPERTY_VERSION_KEY));+ }+@Testpublic void testTemplatesOnlyRequireTheParametersTheyHaveTo() {// 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. The TMS maintenance task also requires action_ids: the scheduler injects the- // soft-slot ids and the placeholder has no default.+ // required.Map<String, Set<String>> expected = new HashMap<>();Set<String> icebergCatalog =ImmutableSet.of(@@ -116,7 +129,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", "action_ids")+ .add("maintenance_types", "policy_ids", "action_ids", "tables").build());for (JobTemplate template : new BuiltInJobTemplateProvider().jobTemplates()) {diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/occupancy/OccupancyGate.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/MaintenanceActionManager.javasimilarity index 55%rename from plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/occupancy/OccupancyGate.javarename to plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/MaintenanceActionManager.javaindex a817b02f2c..251f32b1d6 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/occupancy/OccupancyGate.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/MaintenanceActionManager.java@@ -16,55 +16,79 @@* specific language governing permissions and limitations* under the License.*/-package org.apache.gravitino.maintenance.occupancy;+package org.apache.gravitino.maintenance;import com.google.common.base.Preconditions;import javax.annotation.Nullable;-import org.apache.gravitino.maintenance.TableMaintenanceConfig;+import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.maintenance.storage.po.TableMaintenanceActionPO;import org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService;/**- * Expand / submit occupancy checks against {@code table_maintenance_action} (§5.2).+ * Decides whether a maintenance action for one table and policy can start.*- * <p>Unbound rows ({@code job_id} null, {@code finished_at = 0}) are a short claim: occupied while- * still within TTL on the <strong>database</strong> clock. Bound rows occupy the soft slot until- * Spark closes them via before/after metrics with {@code ?finish=true}. This gate does not reclaim- * on Gravitino job terminal state.+ * <p>Reads {@code table_maintenance_action} through {@link TableMaintenanceActionMetaService}.+ * Unbound rows ({@code job_id} null, {@code finished_at = 0}) occupy the soft slot while still+ * within TTL on the database clock. Bound rows stay occupied until Spark closes them via+ * before/after metrics with {@code ?finish=true}. This manager does not reclaim on Gravitino job+ * terminal state, and it does not acquire or release the slot.*/-public final class OccupancyGate {+public final class MaintenanceActionManager {++ private static final TableMaintenanceActionMetaService ACTION_SERVICE =+ TableMaintenanceActionMetaService.getInstance();++ private static volatile MaintenanceActionManager instance;private final TableMaintenanceActionMetaService actionMetaService;private final long claimTimeoutMs;/**- * @param actionMetaService maintenance action DAO+ * Returns the shared action manager for the server process.+ *+ * @return singleton manager+ */+ public static MaintenanceActionManager getInstance() {+ if (instance == null) {+ synchronized (MaintenanceActionManager.class) {+ if (instance == null) {+ long claimTimeoutMs =+ TableMaintenanceConfig.from(GravitinoEnv.getInstance().config()).claimTimeoutMs();+ instance = new MaintenanceActionManager(ACTION_SERVICE, claimTimeoutMs);+ }+ }+ }+ return instance;+ }++ /**+ * Test / override constructor. Production code should use {@link #getInstance()}.+ *+ * @param actionMetaService maintenance action store* @param claimTimeoutMs unbound claim TTL*/- public OccupancyGate(TableMaintenanceActionMetaService actionMetaService, long claimTimeoutMs) {+ public MaintenanceActionManager(+ TableMaintenanceActionMetaService actionMetaService, long claimTimeoutMs) {Preconditions.checkArgument(claimTimeoutMs > 0, "claimTimeoutMs must be positive");this.actionMetaService = Preconditions.checkNotNull(actionMetaService);this.claimTimeoutMs = claimTimeoutMs;}/**- * @param actionMetaService maintenance action DAO+ * Test / override constructor with the default claim timeout.+ *+ * @param actionMetaService maintenance action store*/- public OccupancyGate(TableMaintenanceActionMetaService actionMetaService) {+ public MaintenanceActionManager(TableMaintenanceActionMetaService actionMetaService) {this(actionMetaService, TableMaintenanceConfig.DEFAULT_CLAIM_TIMEOUT_MS);}- /** Uses {@link TableMaintenanceActionMetaService#getInstance()} and default claim timeout. */- public OccupancyGate() {- this(TableMaintenanceActionMetaService.getInstance());- }-/*** @param tableId table entity id* @param policyId policy entity id* @return true when any open row is a live unbound claim or a still-bound soft-slot row*/- public boolean isInFlight(long tableId, long policyId) {+ public boolean isOccupied(long tableId, long policyId) {if (actionMetaService.hasLiveUnboundClaim(tableId, policyId, claimTimeoutMs)) {return true;}@@ -83,7 +107,7 @@ public final class OccupancyGate {* @param nowMs current epoch millis used only for cooldown (not unbound TTL)* @return true when the last known finish is still inside the cooldown window*/- public boolean withinMinInterval(long tableId, long policyId, long minIntervalMs, long nowMs) {+ public boolean isCoolingDown(long tableId, long policyId, long minIntervalMs, long nowMs) {if (minIntervalMs <= 0) {return false;}@@ -92,17 +116,15 @@ public final class OccupancyGate {}/**- * Expand / submit should skip when occupied or still cooling down.- ** @param tableId table entity id* @param policyId policy entity id* @param minIntervalMs resolved minimum interval* @param nowMs current epoch millis used only for cooldown (not unbound TTL)- * @return true when enqueue / submit must be skipped+ * @return true when the soft slot is free and the cooldown has elapsed*/- public boolean shouldSkip(long tableId, long policyId, long minIntervalMs, long nowMs) {- return isInFlight(tableId, policyId)- || withinMinInterval(tableId, policyId, minIntervalMs, nowMs);+ public boolean canStart(long tableId, long policyId, long minIntervalMs, long nowMs) {+ return !isOccupied(tableId, policyId)+ && !isCoolingDown(tableId, policyId, minIntervalMs, nowMs);}@Nullablediff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/MaintenanceJobManager.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/MaintenanceJobManager.javanew file mode 100644index 0000000000..623c8fd805--- /dev/null+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/MaintenanceJobManager.java@@ -0,0 +1,126 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.maintenance;++import com.google.common.base.Preconditions;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.stream.Collectors;+import org.apache.gravitino.GravitinoEnv;+import org.apache.gravitino.job.JobHandle;+import org.apache.gravitino.job.JobOperationDispatcher;+import org.apache.gravitino.maintenance.model.OccupancyClaim;+import org.apache.gravitino.maintenance.scheduler.job.MaintenanceJobTemplates;+import org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService;+import org.apache.gravitino.meta.JobEntity;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * Submits TMS Spark jobs and binds the resulting job run id onto soft-slot claims.+ *+ * <p>{@link #submitAndBind} injects {@code action_ids}, calls {@code runJob}, then binds {@code+ * job_id}. If {@code runJob} succeeds but bind fails, the orphaned Spark job is cancelled and+ * unbound claims are released. Callers that fail before {@code runJob} must release claims+ * themselves.+ */+public class MaintenanceJobManager {++ private static final Logger LOG = LoggerFactory.getLogger(MaintenanceJobManager.class);++ private static final TableMaintenanceActionMetaService ACTION_SERVICE =+ TableMaintenanceActionMetaService.getInstance();++ private static volatile MaintenanceJobManager instance;++ private final JobOperationDispatcher jobOperationDispatcher;++ /**+ * Returns the shared TMS job manager for the server process.+ *+ * @return singleton manager+ */+ public static MaintenanceJobManager getInstance() {+ if (instance == null) {+ synchronized (MaintenanceJobManager.class) {+ if (instance == null) {+ instance = new MaintenanceJobManager(GravitinoEnv.getInstance().jobOperationDispatcher());+ }+ }+ }+ return instance;+ }++ private MaintenanceJobManager(JobOperationDispatcher jobOperationDispatcher) {+ this.jobOperationDispatcher = Preconditions.checkNotNull(jobOperationDispatcher);+ }++ /**+ * Injects {@code action_ids}, runs the TMS maintenance template, and binds {@code job_id} on the+ * claims (one claim for cron, several for a commit chain).+ *+ * @param metalake metalake name+ * @param jobConf mutable runtime jobConf (policy options already resolved)+ * @param claims soft-slot claims from acquire (non-empty)+ * @return job run id when run+bind succeeded; empty when submit or bind failed (claims released)+ */+ public Optional<Long> submitAndBind(+ String metalake, Map<String, String> jobConf, List<OccupancyClaim> claims) {+ Preconditions.checkNotNull(metalake, "metalake");+ Preconditions.checkNotNull(jobConf, "jobConf");+ Preconditions.checkArgument(claims != null && !claims.isEmpty(), "claims must be non-empty");++ jobConf.put(+ MaintenanceJobTemplates.ACTION_IDS_KEY,+ claims.stream().map(c -> Long.toString(c.actionId())).collect(Collectors.joining(",")));++ Long jobId = null;+ try {+ JobEntity job =+ jobOperationDispatcher.runJob(+ metalake, MaintenanceJobTemplates.ICEBERG_MAINTENANCE_TEMPLATE, jobConf);+ jobId = job.id();+ ACTION_SERVICE.bindJobIds(claims, jobId);+ return Optional.of(jobId);+ } catch (RuntimeException e) {+ if (jobId != null) {+ try {+ jobOperationDispatcher.cancelJob(metalake, JobHandle.JOB_ID_PREFIX + jobId);+ } catch (RuntimeException cancelError) {+ LOG.warn(+ "Failed to cancel orphaned TMS Spark job {} under metalake {} after bind failure",+ jobId,+ metalake,+ cancelError);+ }+ }+ try {+ ACTION_SERVICE.deleteClaims(claims);+ } catch (RuntimeException releaseError) {+ LOG.warn("Failed to release occupancy claims after submit failure", releaseError);+ }+ LOG.warn(+ "Failed TMS job submitAndBind for action_ids {}: {}",+ claims.stream().map(c -> Long.toString(c.actionId())).collect(Collectors.joining(",")),+ e.toString());+ return Optional.empty();+ }+ }+}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/MaintenanceMetricsService.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/MaintenanceMetricsManager.javasimilarity index 61%rename from plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/MaintenanceMetricsService.javarename to plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/MaintenanceMetricsManager.javaindex b194f3a2f7..217c88c90a 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/MaintenanceMetricsService.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/MaintenanceMetricsManager.java@@ -19,7 +19,6 @@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;import org.apache.gravitino.maintenance.dto.requests.MaintenanceActionMetricsRequest;@@ -40,42 +39,35 @@ import org.slf4j.LoggerFactory;* <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 {+public class MaintenanceMetricsManager {- private static final Logger LOG = LoggerFactory.getLogger(MaintenanceMetricsService.class);+ private static final Logger LOG = LoggerFactory.getLogger(MaintenanceMetricsManager.class);++ private static final TableMaintenanceActionMetaService ACTION_SERVICE =+ TableMaintenanceActionMetaService.getInstance();+ private static final TableSnapshotMetricsMetaService METRICS_SERVICE =+ TableSnapshotMetricsMetaService.getInstance();private static final TableMetaService TABLE_SERVICE = TableMetaService.getInstance();- private final TableMaintenanceActionMetaService actionMetaService;- private final TableSnapshotMetricsMetaService metricsMetaService;- private final LongFunction<String> metalakeLookup;+ private static volatile MaintenanceMetricsManager instance;/**- * Production wiring.+ * Returns the shared TMS metrics manager for the server process.*- * @return service bound into the Jersey feature+ * @return singleton manager*/- public static MaintenanceMetricsService create() {- return new MaintenanceMetricsService(- TableMaintenanceActionMetaService.getInstance(),- TableSnapshotMetricsMetaService.getInstance(),- TABLE_SERVICE::getMetalakeNameByTableId);+ public static MaintenanceMetricsManager getInstance() {+ if (instance == null) {+ synchronized (MaintenanceMetricsManager.class) {+ if (instance == null) {+ instance = new MaintenanceMetricsManager();+ }+ }+ }+ return instance;}- /**- * Creates a service with explicit collaborators.- *- * @param actionMetaService action rows- * @param metricsMetaService snapshot metrics rows- * @param metalakeLookup resolves a table id to its metalake name- */- public MaintenanceMetricsService(- TableMaintenanceActionMetaService actionMetaService,- TableSnapshotMetricsMetaService metricsMetaService,- LongFunction<String> metalakeLookup) {- this.actionMetaService = actionMetaService;- this.metricsMetaService = metricsMetaService;- this.metalakeLookup = metalakeLookup;- }+ private MaintenanceMetricsManager() {}/*** S0 report: stores metrics, records {@code before_metrics_id}, optionally closes the soft slot@@ -88,17 +80,36 @@ public class MaintenanceMetricsService {*/public void reportBeforeMetrics(String metalake, long actionId, boolean finish, MaintenanceActionMetricsRequest request) {- TableMaintenanceActionPO action = loadInFlight(metalake, actionId, request);+ TableMaintenanceActionPO action =+ loadInFlight(metalake, actionId, request.getTableId(), request.getPolicyId());long metricsId =action.beforeMetricsId() != null? action.beforeMetricsId()- : metricsMetaService.insertMetrics(+ : METRICS_SERVICE.insertMetrics(action.tableId(),action.policyId(),request.getSnapshotId(),request.getMetricsJson());- actionMetaService.recordBeforeMetrics(actionId, metricsId);- maybeFinish(actionId, action, finish, "before", metalake, metricsId);+ ACTION_SERVICE.recordBeforeMetrics(actionId, metricsId);+ if (finish) {+ ACTION_SERVICE.markFinished(actionId, System.currentTimeMillis());+ LOG.info(+ "before metrics reported and action finished for action_id {} metalake {} table {}"+ + " policy {} metricsId {}",+ actionId,+ metalake,+ action.tableId(),+ action.policyId(),+ metricsId);+ } else {+ LOG.info(+ "before metrics reported for action_id {} metalake {} table {} policy {} metricsId {}",+ actionId,+ metalake,+ action.tableId(),+ action.policyId(),+ metricsId);+ }}/**@@ -111,17 +122,36 @@ public class MaintenanceMetricsService {*/public void reportAfterMetrics(String metalake, long actionId, boolean finish, MaintenanceActionMetricsRequest request) {- TableMaintenanceActionPO action = loadInFlight(metalake, actionId, request);+ TableMaintenanceActionPO action =+ loadInFlight(metalake, actionId, request.getTableId(), request.getPolicyId());long metricsId =action.afterMetricsId() != null? action.afterMetricsId()- : metricsMetaService.insertMetrics(+ : METRICS_SERVICE.insertMetrics(action.tableId(),action.policyId(),request.getSnapshotId(),request.getMetricsJson());- actionMetaService.recordAfterMetrics(actionId, metricsId);- maybeFinish(actionId, action, finish, "after", metalake, metricsId);+ ACTION_SERVICE.recordAfterMetrics(actionId, metricsId);+ if (finish) {+ ACTION_SERVICE.markFinished(actionId, System.currentTimeMillis());+ LOG.info(+ "after metrics reported and action finished for action_id {} metalake {} table {}"+ + " policy {} metricsId {}",+ actionId,+ metalake,+ action.tableId(),+ action.policyId(),+ metricsId);+ } else {+ LOG.info(+ "after metrics reported for action_id {} metalake {} table {} policy {} metricsId {}",+ actionId,+ metalake,+ action.tableId(),+ action.policyId(),+ metricsId);+ }}/**@@ -133,13 +163,8 @@ public class MaintenanceMetricsService {*/public void finishAction(String metalake, long actionId, MaintenanceActionFinishRequest request) {TableMaintenanceActionPO action =- loadInFlight(- metalake,- actionId,- request.getTableId(),- request.getPolicyId(),- /*requireBound=*/ true);- actionMetaService.markFinished(actionId, System.currentTimeMillis());+ loadInFlight(metalake, actionId, request.getTableId(), request.getPolicyId());+ ACTION_SERVICE.markFinished(actionId, System.currentTimeMillis());LOG.info("action finished for action_id {} metalake {} table {} policy {}",actionId,@@ -148,44 +173,9 @@ public class MaintenanceMetricsService {action.policyId());}- private void maybeFinish(- long actionId,- TableMaintenanceActionPO action,- boolean finish,- String phase,- String metalake,- long metricsId) {- if (!finish) {- LOG.info(- "{} metrics reported for action_id {} metalake {} table {} policy {} metricsId {}",- phase,- actionId,- metalake,- action.tableId(),- action.policyId(),- metricsId);- return;- }- actionMetaService.markFinished(actionId, System.currentTimeMillis());- LOG.info(- "{} metrics reported and action finished for action_id {} metalake {} table {} policy {} metricsId {}",- phase,- actionId,- metalake,- action.tableId(),- action.policyId(),- metricsId);- }-- private TableMaintenanceActionPO loadInFlight(- 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);+ private static TableMaintenanceActionPO loadInFlight(+ String metalake, long actionId, long tableId, long policyId) {+ TableMaintenanceActionPO action = ACTION_SERVICE.getById(actionId);if (action == null) {throw new NoSuchEntityException("no maintenance action for action_id=%s", actionId);}@@ -194,24 +184,15 @@ public class MaintenanceMetricsService {throw new NoSuchEntityException("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;- }-- private static void requireActionInFlight(TableMaintenanceActionPO action) {if (action.finishedAt() == null || action.finishedAt() != 0L) {throw new NoSuchEntityException("no in-flight maintenance action for action_id=%s", action.actionId());}- }-- private void requireActionInMetalake(TableMaintenanceActionPO action, String metalake) {- String actionMetalake = metalakeLookup.apply(action.tableId());+ if (action.jobId() == null) {+ throw new NoSuchEntityException(+ "maintenance action action_id=%s is not bound to a job yet", actionId);+ }+ String actionMetalake = TABLE_SERVICE.getMetalakeNameByTableId(action.tableId());if (actionMetalake == null) {throw new NoSuchEntityException("no metalake for table_id=%s (action_id=%s)", action.tableId(), action.actionId());@@ -220,5 +201,6 @@ public class MaintenanceMetricsService {throw new NoSuchEntityException("no maintenance action for action_id=%s under metalake %s", action.actionId(), metalake);}+ return action;}}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/TableMaintenanceConfig.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/TableMaintenanceConfig.javaindex a69c04d6a2..f5a40dd950 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/TableMaintenanceConfig.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/TableMaintenanceConfig.java@@ -74,9 +74,9 @@ public final class TableMaintenanceConfig {.checkValue(value -> value > 0, ConfigConstants.POSITIVE_NUMBER_ERROR_MSG).createWithDefault(6);- public static final ConfigEntry<Integer> EXPAND_ENQUEUE_BATCH_SIZE =- new ConfigBuilder("gravitino.maintenance.expand.enqueueBatchSize")- .doc("Maximum cron-jobs enqueued per policy-expand pick")+ public static final ConfigEntry<Integer> EXPAND_SCHEDULE_BATCH_SIZE =+ new ConfigBuilder("gravitino.maintenance.expand.scheduleBatchSize")+ .doc("Maximum cron-jobs scheduled per policy-expand pick").version(ConfigConstants.VERSION_2_0_0).intConf().checkValue(value -> value > 0, ConfigConstants.POSITIVE_NUMBER_ERROR_MSG)@@ -101,7 +101,7 @@ public final class TableMaintenanceConfig {private final long pollingIntervalMs;private final long heartbeatIntervalMs;private final int missedHeartbeatsLimit;- private final int expandEnqueueBatchSize;+ private final int expandScheduleBatchSize;private final long claimTimeoutMs;private TableMaintenanceConfig(@@ -111,7 +111,7 @@ public final class TableMaintenanceConfig {long pollingIntervalMs,long heartbeatIntervalMs,int missedHeartbeatsLimit,- int expandEnqueueBatchSize,+ int expandScheduleBatchSize,long claimTimeoutMs) {this.expandThreads = expandThreads;this.cronThreads = cronThreads;@@ -119,7 +119,7 @@ public final class TableMaintenanceConfig {this.pollingIntervalMs = pollingIntervalMs;this.heartbeatIntervalMs = heartbeatIntervalMs;this.missedHeartbeatsLimit = missedHeartbeatsLimit;- this.expandEnqueueBatchSize = expandEnqueueBatchSize;+ this.expandScheduleBatchSize = expandScheduleBatchSize;this.claimTimeoutMs = claimTimeoutMs;}@@ -137,7 +137,7 @@ public final class TableMaintenanceConfig {config.get(SCHEDULER_POLLING_INTERVAL_MS),config.get(SCHEDULER_HEARTBEAT_INTERVAL_MS),config.get(SCHEDULER_MISSED_HEARTBEATS_LIMIT),- config.get(EXPAND_ENQUEUE_BATCH_SIZE),+ config.get(EXPAND_SCHEDULE_BATCH_SIZE),config.get(OCCUPANCY_CLAIM_TIMEOUT_MS));}@@ -184,10 +184,10 @@ public final class TableMaintenanceConfig {}/**- * @return expand enqueue batch size+ * @return expand schedule batch size*/- public int expandEnqueueBatchSize() {- return expandEnqueueBatchSize;+ public int expandScheduleBatchSize() {+ return expandScheduleBatchSize;}/**@@ -206,7 +206,7 @@ public final class TableMaintenanceConfig {* @param pollingIntervalMs poll interval* @param heartbeatIntervalMs heartbeat interval* @param missedHeartbeatsLimit missed heartbeat limit- * @param expandEnqueueBatchSize expand batch size+ * @param expandScheduleBatchSize expand batch size* @return config instance*/public static TableMaintenanceConfig forTest(@@ -216,7 +216,7 @@ public final class TableMaintenanceConfig {long pollingIntervalMs,long heartbeatIntervalMs,int missedHeartbeatsLimit,- int expandEnqueueBatchSize) {+ int expandScheduleBatchSize) {return forTest(expandThreads,cronThreads,@@ -224,7 +224,7 @@ public final class TableMaintenanceConfig {pollingIntervalMs,heartbeatIntervalMs,missedHeartbeatsLimit,- expandEnqueueBatchSize,+ expandScheduleBatchSize,DEFAULT_CLAIM_TIMEOUT_MS);}@@ -237,7 +237,7 @@ public final class TableMaintenanceConfig {* @param pollingIntervalMs poll interval* @param heartbeatIntervalMs heartbeat interval* @param missedHeartbeatsLimit missed heartbeat limit- * @param expandEnqueueBatchSize expand batch size+ * @param expandScheduleBatchSize expand batch size* @param claimTimeoutMs unbound claim timeout* @return config instance*/@@ -248,7 +248,7 @@ public final class TableMaintenanceConfig {long pollingIntervalMs,long heartbeatIntervalMs,int missedHeartbeatsLimit,- int expandEnqueueBatchSize,+ int expandScheduleBatchSize,long claimTimeoutMs) {return new TableMaintenanceConfig(expandThreads,@@ -257,7 +257,7 @@ public final class TableMaintenanceConfig {pollingIntervalMs,heartbeatIntervalMs,missedHeartbeatsLimit,- expandEnqueueBatchSize,+ expandScheduleBatchSize,claimTimeoutMs);}}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/AlwaysMaintainInJobRecommender.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/AlwaysMaintainInJobRecommender.javadeleted file mode 100644index 9c15d273be..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/AlwaysMaintainInJobRecommender.java+++ /dev/null@@ -1,41 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.injob;--/**- * In-job recommender that always returns {@link RecommendDecision#MAINTAIN}.- *- * <p>Production {@link TypeDispatchingInJobRecommender} uses this for expire / rewrite-manifests:- * cron already scheduled the work, so the in-job gate always maintains. Also available for tests- * and injectable overrides.- */-public final class AlwaysMaintainInJobRecommender implements InJobRecommender {-- /** Shared instance. */- public static final AlwaysMaintainInJobRecommender INSTANCE =- new AlwaysMaintainInJobRecommender();-- private AlwaysMaintainInJobRecommender() {}-- @Override- public RecommendDecision recommend(- long tableId, long policyId, long sampledSnapshotId, String metricsJson) {- return RecommendDecision.MAINTAIN;- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/CompactionInJobRecommender.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/CompactionInJobRecommender.javadeleted file mode 100644index ebf33c72f9..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/CompactionInJobRecommender.java+++ /dev/null@@ -1,122 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.injob;--import com.google.common.base.Preconditions;-import java.util.Map;-import java.util.Optional;-import java.util.function.Function;-import javax.annotation.Nullable;-import org.apache.gravitino.maintenance.optimizer.recommender.handler.compaction.CompactionTriggerEvaluator;-import org.apache.gravitino.meta.PolicyEntity;-import org.apache.gravitino.policy.IcebergDataCompactionContent;-import org.apache.gravitino.policy.PolicyContent;-import org.apache.gravitino.storage.relational.service.PolicyMetaService;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--/**- * In-job recommender for Iceberg compaction. Evaluates {@code trigger-expr} via {@link- * CompactionTriggerEvaluator} (same QL path as the optimizer strategy handler).- */-public final class CompactionInJobRecommender implements InJobRecommender {-- private static final Logger LOG = LoggerFactory.getLogger(CompactionInJobRecommender.class);- private static final PolicyMetaService POLICY_SERVICE = PolicyMetaService.getInstance();-- private final Function<Long, Optional<PolicyEntity>> policyLoader;-- /** Loads policies through {@link PolicyMetaService}. */- public CompactionInJobRecommender() {- this(CompactionInJobRecommender::loadPolicy);- }-- /**- * @param policyLoader loads a policy by id when the caller did not supply a policy entity- */- CompactionInJobRecommender(Function<Long, Optional<PolicyEntity>> policyLoader) {- this.policyLoader = Preconditions.checkNotNull(policyLoader);- }-- @Override- public RecommendDecision recommend(- long tableId, long policyId, long sampledSnapshotId, String metricsJson) {- return recommend(tableId, policyId, sampledSnapshotId, metricsJson, null);- }-- @Override- public RecommendDecision recommend(- long tableId,- long policyId,- long sampledSnapshotId,- String metricsJson,- @Nullable PolicyEntity policy) {- IcebergDataCompactionContent compaction = resolveCompactionContent(tableId, policyId, policy);- if (compaction == null) {- return RecommendDecision.SKIP;- }- Map<String, Object> metrics = MetricsJson.parseNumericValues(metricsJson);- if (metrics.isEmpty()- || !metrics.containsKey(IcebergDataCompactionContent.DATA_FILE_MSE_METRIC)- || !metrics.containsKey(IcebergDataCompactionContent.DELETE_FILE_NUMBER_METRIC)) {- LOG.warn(- "Compaction recommend skip: metrics JSON missing compaction fields for table {} policy {}",- tableId,- policyId);- return RecommendDecision.SKIP;- }- boolean maintain = CompactionTriggerEvaluator.shouldMaintain(compaction, metrics);- LOG.info(- "Compaction recommend table={} policy={} snapshot={} metrics={} -> {}",- tableId,- policyId,- sampledSnapshotId,- metrics,- maintain ? "MAINTAIN" : "SKIP");- return maintain ? RecommendDecision.MAINTAIN : RecommendDecision.SKIP;- }-- @Nullable- private IcebergDataCompactionContent resolveCompactionContent(- long tableId, long policyId, @Nullable PolicyEntity policy) {- PolicyContent content;- if (policy != null) {- content = policy.content();- } else {- Optional<PolicyEntity> loaded = policyLoader.apply(policyId);- if (loaded.isEmpty()) {- LOG.warn("Compaction recommend skip: policy {} not found (table={})", policyId, tableId);- return null;- }- content = loaded.get().content();- }- if (!(content instanceof IcebergDataCompactionContent)) {- LOG.warn(- "Compaction recommend skip: policy {} is not IcebergDataCompactionContent (table={})",- policyId,- tableId);- return null;- }- return (IcebergDataCompactionContent) content;- }-- private static Optional<PolicyEntity> loadPolicy(long policyId) {- return Optional.ofNullable(POLICY_SERVICE.getPolicyById(policyId));- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/InJobGateOutcome.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/InJobGateOutcome.javadeleted file mode 100644index 61cb521881..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/InJobGateOutcome.java+++ /dev/null@@ -1,99 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.injob;--import com.google.common.base.Preconditions;-import javax.annotation.Nullable;--/** Result of the in-job sample / drift / recommend gates (§5.2.2). */-public final class InJobGateOutcome {-- /** Why maintenance should not continue. */- public enum StopReason {- /** HEAD snapshot id differs from {@code S0}; do not re-sample in a loop. */- SNAPSHOT_DRIFT,- /** Recommender decided not to maintain; end early without running work. */- RECOMMENDER_SKIP- }-- private final boolean continueMaintenance;- @Nullable private final StopReason stopReason;- private final long sampledSnapshotId;- private final long headSnapshotId;-- private InJobGateOutcome(- boolean continueMaintenance,- @Nullable StopReason stopReason,- long sampledSnapshotId,- long headSnapshotId) {- this.continueMaintenance = continueMaintenance;- this.stopReason = stopReason;- this.sampledSnapshotId = sampledSnapshotId;- this.headSnapshotId = headSnapshotId;- }-- /**- * @param sampledSnapshotId {@code S0}- * @return outcome when maintenance may proceed- */- public static InJobGateOutcome continueMaintenance(long sampledSnapshotId) {- return new InJobGateOutcome(true, null, sampledSnapshotId, sampledSnapshotId);- }-- /**- * @param reason why the job or type should stop- * @param sampledSnapshotId {@code S0}- * @param headSnapshotId current HEAD when stopping- * @return outcome when maintenance must not continue- */- public static InJobGateOutcome stop(- StopReason reason, long sampledSnapshotId, long headSnapshotId) {- Preconditions.checkNotNull(reason);- return new InJobGateOutcome(false, reason, sampledSnapshotId, headSnapshotId);- }-- /**- * @return whether the Spark Job should run work for this type- */- public boolean continueMaintenance() {- return continueMaintenance;- }-- /**- * @return stop reason when {@link #continueMaintenance()} is false- */- @Nullable- public StopReason stopReason() {- return stopReason;- }-- /**- * @return sampled snapshot id ({@code S0})- */- public long sampledSnapshotId() {- return sampledSnapshotId;- }-- /**- * @return HEAD snapshot id observed for the gate- */- public long headSnapshotId() {- return headSnapshotId;- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/InJobRecommender.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/InJobRecommender.javadeleted file mode 100644index 7425e020ca..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/InJobRecommender.java+++ /dev/null@@ -1,62 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.injob;--import javax.annotation.Nullable;-import org.apache.gravitino.meta.PolicyEntity;--/**- * Decides whether maintenance should run after metrics were sampled at {@code S0}.- *- * <p>Production wiring uses {@link TypeDispatchingInJobRecommender}: compaction via {@link- * CompactionInJobRecommender}, orphan cleanup via {@link TriggerExprInJobRecommender}, and expire /- * rewrite-manifests placeholders via {@link AlwaysMaintainInJobRecommender}.- */-public interface InJobRecommender {-- /**- * @param tableId table entity id- * @param policyId policy entity id- * @param sampledSnapshotId Iceberg snapshot id at sample time- * @param metricsJson serialized metrics for that snapshot- * @return maintain or skip- */- RecommendDecision recommend(- long tableId, long policyId, long sampledSnapshotId, String metricsJson);-- /**- * Same as {@link #recommend(long, long, long, String)} when the caller already loaded the policy- * (avoids a second store round-trip in type-dispatching recommenders).- *- * @param tableId table entity id- * @param policyId policy entity id- * @param sampledSnapshotId Iceberg snapshot id at sample time- * @param metricsJson serialized metrics for that snapshot- * @param policy already-loaded policy, or {@code null} to fall back to id lookup- * @return maintain or skip- */- default RecommendDecision recommend(- long tableId,- long policyId,- long sampledSnapshotId,- String metricsJson,- @Nullable PolicyEntity policy) {- return recommend(tableId, policyId, sampledSnapshotId, metricsJson);- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/MetricsJson.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/MetricsJson.javadeleted file mode 100644index 98530be898..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/MetricsJson.java+++ /dev/null@@ -1,70 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.injob;--import com.fasterxml.jackson.databind.JsonNode;-import java.io.IOException;-import java.util.HashMap;-import java.util.Iterator;-import java.util.Map;-import java.util.Map.Entry;-import javax.annotation.Nullable;-import org.apache.gravitino.json.JsonUtils;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--/** Parses numeric fields from in-job metrics JSON payloads. */-final class MetricsJson {-- private static final Logger LOG = LoggerFactory.getLogger(MetricsJson.class);-- private MetricsJson() {}-- /**- * @param metricsJson JSON object, possibly null/blank- * @return numeric field bindings (integral → {@link Long}, otherwise {@link Double}); empty on- * parse failure- */- static Map<String, Object> parseNumericValues(@Nullable String metricsJson) {- Map<String, Object> metrics = new HashMap<>();- if (metricsJson == null || metricsJson.trim().isEmpty()) {- return metrics;- }- try {- JsonNode root = JsonUtils.anyFieldMapper().readTree(metricsJson);- Iterator<Entry<String, JsonNode>> fields = root.fields();- while (fields.hasNext()) {- Entry<String, JsonNode> field = fields.next();- JsonNode value = field.getValue();- if (value == null || value.isNull() || !value.isNumber()) {- continue;- }- if (value.isIntegralNumber()) {- metrics.put(field.getKey(), value.longValue());- } else {- metrics.put(field.getKey(), value.doubleValue());- }- }- return metrics;- } catch (IOException | RuntimeException e) {- LOG.warn("Failed to parse metrics JSON: {}", e.toString());- return metrics;- }- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/RecommendDecision.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/RecommendDecision.javadeleted file mode 100644index 9c337fd40d..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/RecommendDecision.java+++ /dev/null@@ -1,30 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.injob;--/**- * Whether the in-job path should run maintenance work after a successful {@code S0} sample- * (§5.2.2). Produced by {@link TypeDispatchingInJobRecommender} and type-specific recommenders.- */-public enum RecommendDecision {- /** Proceed to execute maintenance work. */- MAINTAIN,- /** End this job or type early; do not run maintenance work. */- SKIP-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/SnapshotHead.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/SnapshotHead.javadeleted file mode 100644index 04e6f089b8..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/SnapshotHead.java+++ /dev/null@@ -1,33 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.injob;--/**- * Supplies the Iceberg table HEAD snapshot id from inside a Spark Job (§4.3, §5.2.2).- *- * <p>Implementations typically delegate to {@code Table#currentSnapshot()}.- */-@FunctionalInterface-public interface SnapshotHead {-- /**- * @return current Iceberg snapshot id at table HEAD- */- long currentSnapshotId();-}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.javadeleted file mode 100644index 3a149b84f1..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/TableMaintenanceInJobPipeline.java+++ /dev/null@@ -1,105 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.injob;--import com.google.common.base.Preconditions;--/**- * Cron / commit-chain in-job gates: sample at {@code S0}, stop on snapshot drift, then apply the- * recommend maintain? gate (§5.2.2). Does not execute the four maintenance types.- */-public class TableMaintenanceInJobPipeline {-- private final TableMaintenanceInJobSampler sampler;- private final InJobRecommender recommender;-- /**- * @param sampler S0 sample + drift gate- * @param recommender maintain vs skip after a clean sample- */- public TableMaintenanceInJobPipeline(- TableMaintenanceInJobSampler sampler, InJobRecommender recommender) {- this.sampler = Preconditions.checkNotNull(sampler);- this.recommender = Preconditions.checkNotNull(recommender);- }-- /**- * Runs sample → drift → recommend for a cron Spark Job.- *- * @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}- * @param metricsJson metrics payload- * @param head current HEAD supplier after persistence- * @return continue only when HEAD matches {@code S0} and recommender says maintain- */- public InJobGateOutcome gateCronJob(- long actionId,- long tableId,- long policyId,- long sampledSnapshotId,- String metricsJson,- SnapshotHead head) {- InJobGateOutcome afterSample =- sampler.sampleAndGateCronJob(- actionId, tableId, policyId, sampledSnapshotId, metricsJson, head);- if (!afterSample.continueMaintenance()) {- return afterSample;- }-- RecommendDecision decision =- recommender.recommend(tableId, policyId, sampledSnapshotId, metricsJson);- if (decision == RecommendDecision.SKIP) {- return InJobGateOutcome.stop(- InJobGateOutcome.StopReason.RECOMMENDER_SKIP,- sampledSnapshotId,- afterSample.headSnapshotId());- }- return afterSample;- }-- /**- * Drift then recommend for one type inside a commit-chain job (§5.2.3). Caller ends only the- * current type on stop; does not re-sample.- *- * @param tableId table entity id- * @param policyId policy entity id- * @param sampledSnapshotId {@code S0} for this type- * @param metricsJson metrics for this type's sample- * @param head current HEAD after this type's sample persistence- * @return continue vs stop for this type- */- public InJobGateOutcome gateCommitChainType(- long tableId, long policyId, long sampledSnapshotId, String metricsJson, SnapshotHead head) {- InJobGateOutcome afterDrift = sampler.gateCommitChainType(sampledSnapshotId, head);- if (!afterDrift.continueMaintenance()) {- return afterDrift;- }- RecommendDecision decision =- recommender.recommend(tableId, policyId, sampledSnapshotId, metricsJson);- if (decision == RecommendDecision.SKIP) {- return InJobGateOutcome.stop(- InJobGateOutcome.StopReason.RECOMMENDER_SKIP,- sampledSnapshotId,- afterDrift.headSnapshotId());- }- return afterDrift;- }-}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.javadeleted file mode 100644index 14f7d12fee..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/TableMaintenanceInJobSampler.java+++ /dev/null@@ -1,123 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.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_metrics_id}, then gate on snapshot drift without re-sampling.- */-public class TableMaintenanceInJobSampler {-- private final TableSnapshotMetricsMetaService metricsMetaService;- private final TableMaintenanceActionMetaService actionMetaService;-- /** Creates a sampler using the default relational meta services. */- public TableMaintenanceInJobSampler() {- this(- TableSnapshotMetricsMetaService.getInstance(),- TableMaintenanceActionMetaService.getInstance());- }-- /**- * @param metricsMetaService metrics DAO- * @param actionMetaService maintenance action DAO- */- public TableMaintenanceInJobSampler(- TableSnapshotMetricsMetaService metricsMetaService,- TableMaintenanceActionMetaService actionMetaService) {- this.metricsMetaService = Preconditions.checkNotNull(metricsMetaService);- this.actionMetaService = Preconditions.checkNotNull(actionMetaService);- }-- /**- * 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 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})- * @param metricsJson serialized metrics payload for {@code table_snapshot_metrics}- * @param head supplies current HEAD after persistence- * @return continue vs drift stop outcome- */- public InJobGateOutcome sampleAndGateCronJob(- long actionId,- long tableId,- long policyId,- long sampledSnapshotId,- String metricsJson,- SnapshotHead head) {- Preconditions.checkNotNull(metricsJson, "metricsJson");- Preconditions.checkNotNull(head, "head");-- 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) {- return InJobGateOutcome.stop(- InJobGateOutcome.StopReason.SNAPSHOT_DRIFT, sampledSnapshotId, headSnapshotId);- }- return InJobGateOutcome.continueMaintenance(sampledSnapshotId);- }-- /**- * Evaluates drift for a commit-chain maintenance type after that type's sample at {@code S0}- * (§5.2.3). When drift is detected the caller ends only the current type and continues the chain.- *- * @param sampledSnapshotId {@code S0} for the current type- * @param head supplies current HEAD after persistence for this type- * @return continue vs drift stop outcome- */- public InJobGateOutcome gateCommitChainType(long sampledSnapshotId, SnapshotHead head) {- Preconditions.checkNotNull(head, "head");- long headSnapshotId = head.currentSnapshotId();- if (sampledSnapshotId != headSnapshotId) {- return InJobGateOutcome.stop(- InJobGateOutcome.StopReason.SNAPSHOT_DRIFT, sampledSnapshotId, headSnapshotId);- }- return InJobGateOutcome.continueMaintenance(sampledSnapshotId);- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/TriggerExprInJobRecommender.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/TriggerExprInJobRecommender.javadeleted file mode 100644index 2f03ede0a8..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/TriggerExprInJobRecommender.java+++ /dev/null@@ -1,129 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.injob;--import com.google.common.base.Preconditions;-import java.util.HashMap;-import java.util.Map;-import java.util.Optional;-import java.util.function.Function;-import javax.annotation.Nullable;-import org.apache.gravitino.maintenance.optimizer.recommender.util.QLExpressionEvaluator;-import org.apache.gravitino.meta.PolicyEntity;-import org.apache.gravitino.policy.IcebergOrphanFileRemovalContent;-import org.apache.gravitino.policy.PolicyContent;-import org.apache.gravitino.storage.relational.service.PolicyMetaService;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--/**- * In-job recommender that evaluates policy {@code trigger-expr} with the shared QL stack (numeric- * rules + sampled metric bindings). Used for types whose content already exposes a real- * trigger-expr (for example orphan cleanup {@code true}). Missing {@code trigger-expr} defaults to- * {@code false} ({@link RecommendDecision#SKIP}). Expire / rewrite-manifests are dispatched to- * {@link AlwaysMaintainInJobRecommender} instead.- */-public final class TriggerExprInJobRecommender implements InJobRecommender {-- private static final Logger LOG = LoggerFactory.getLogger(TriggerExprInJobRecommender.class);- private static final PolicyMetaService POLICY_SERVICE = PolicyMetaService.getInstance();-- private final Function<Long, Optional<PolicyEntity>> policyLoader;- private final QLExpressionEvaluator evaluator;-- /** Loads policies through {@link PolicyMetaService}. */- public TriggerExprInJobRecommender() {- this(TriggerExprInJobRecommender::loadPolicy);- }-- /**- * @param policyLoader loads a policy by id when the caller did not supply a policy entity- */- TriggerExprInJobRecommender(Function<Long, Optional<PolicyEntity>> policyLoader) {- this.policyLoader = Preconditions.checkNotNull(policyLoader);- this.evaluator = new QLExpressionEvaluator();- }-- @Override- public RecommendDecision recommend(- long tableId, long policyId, long sampledSnapshotId, String metricsJson) {- return recommend(tableId, policyId, sampledSnapshotId, metricsJson, null);- }-- @Override- public RecommendDecision recommend(- long tableId,- long policyId,- long sampledSnapshotId,- String metricsJson,- @Nullable PolicyEntity policy) {- PolicyContent content = resolveContent(tableId, policyId, policy);- if (content == null) {- return RecommendDecision.SKIP;- }- Object trigger = content.rules().get(IcebergOrphanFileRemovalContent.TRIGGER_EXPR_KEY);- String expression =- trigger == null || trigger.toString().trim().isEmpty()- ? "false"- : trigger.toString().trim();-- Map<String, Object> context = new HashMap<>();- content- .rules()- .forEach(- (key, value) -> {- if (value == null) {- return;- }- try {- context.put(key, Long.parseLong(value.toString()));- } catch (NumberFormatException ignored) {- // Non-numeric rule values are not QL bindings.- }- });- context.putAll(MetricsJson.parseNumericValues(metricsJson));-- boolean maintain = evaluator.evaluateBool(expression, context);- LOG.info(- "Trigger-expr recommend table={} policy={} snapshot={} expr={} -> {}",- tableId,- policyId,- sampledSnapshotId,- expression,- maintain ? "MAINTAIN" : "SKIP");- return maintain ? RecommendDecision.MAINTAIN : RecommendDecision.SKIP;- }-- @Nullable- private PolicyContent resolveContent(long tableId, long policyId, @Nullable PolicyEntity policy) {- if (policy != null) {- return policy.content();- }- Optional<PolicyEntity> loaded = policyLoader.apply(policyId);- if (loaded.isEmpty()) {- LOG.warn("Trigger-expr recommend skip: policy {} not found (table={})", policyId, tableId);- return null;- }- return loaded.get().content();- }-- private static Optional<PolicyEntity> loadPolicy(long policyId) {- return Optional.ofNullable(POLICY_SERVICE.getPolicyById(policyId));- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/TypeDispatchingInJobRecommender.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/TypeDispatchingInJobRecommender.javadeleted file mode 100644index be45a544fb..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/injob/TypeDispatchingInJobRecommender.java+++ /dev/null@@ -1,138 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.injob;--import com.google.common.annotations.VisibleForTesting;-import com.google.common.base.Preconditions;-import java.util.Optional;-import java.util.function.Function;-import org.apache.gravitino.meta.PolicyEntity;-import org.apache.gravitino.policy.IcebergDataCompactionContent;-import org.apache.gravitino.policy.IcebergRewriteManifestsContent;-import org.apache.gravitino.policy.IcebergSnapshotExpirationContent;-import org.apache.gravitino.policy.Policy;-import org.apache.gravitino.storage.relational.service.PolicyMetaService;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--/**- * Dispatches in-job recommenders by policy type.- *- * <ul>- * <li>Compaction → threshold / {@code trigger-expr} evaluation- * <li>Orphan cleanup → policy {@code trigger-expr} ({@code true} by default)- * <li>Expire / rewrite-manifests placeholders → always maintain (cron already scheduled the work;- * content still ships {@code trigger-expr=false} for optimizer-only gating)- * </ul>- */-public final class TypeDispatchingInJobRecommender implements InJobRecommender {-- private static final Logger LOG = LoggerFactory.getLogger(TypeDispatchingInJobRecommender.class);- private static final PolicyMetaService POLICY_SERVICE = PolicyMetaService.getInstance();-- private final Function<Long, Optional<PolicyEntity>> policyLoader;- private final InJobRecommender compactionRecommender;- private final InJobRecommender triggerExprRecommender;- private final InJobRecommender placeholderRecommender;-- /** Production wiring. Loads policies through {@link PolicyMetaService}. */- public TypeDispatchingInJobRecommender() {- this(TypeDispatchingInJobRecommender::loadPolicy);- }-- private TypeDispatchingInJobRecommender(Function<Long, Optional<PolicyEntity>> policyLoader) {- this(- policyLoader,- new CompactionInJobRecommender(policyLoader),- new TriggerExprInJobRecommender(policyLoader),- AlwaysMaintainInJobRecommender.INSTANCE);- }-- /**- * @param policyLoader loads a policy by id- * @param compactionRecommender compaction thresholds- * @param triggerExprRecommender trigger-expr evaluation (orphan and similar)- * @param placeholderRecommender expire / rewrite-manifests placeholders until real thresholds- * land- */- TypeDispatchingInJobRecommender(- Function<Long, Optional<PolicyEntity>> policyLoader,- InJobRecommender compactionRecommender,- InJobRecommender triggerExprRecommender,- InJobRecommender placeholderRecommender) {- this.policyLoader = Preconditions.checkNotNull(policyLoader);- this.compactionRecommender = Preconditions.checkNotNull(compactionRecommender);- this.triggerExprRecommender = Preconditions.checkNotNull(triggerExprRecommender);- this.placeholderRecommender = Preconditions.checkNotNull(placeholderRecommender);- }-- /**- * Test wiring that routes expire / rewrite-manifests placeholders to {@link- * AlwaysMaintainInJobRecommender#INSTANCE}.- *- * @param policyLoader loads a policy by id- * @param compactionRecommender compaction thresholds- * @param triggerExprRecommender trigger-expr evaluation for orphan and similar- */- @VisibleForTesting- TypeDispatchingInJobRecommender(- Function<Long, Optional<PolicyEntity>> policyLoader,- InJobRecommender compactionRecommender,- InJobRecommender triggerExprRecommender) {- this(- policyLoader,- compactionRecommender,- triggerExprRecommender,- AlwaysMaintainInJobRecommender.INSTANCE);- }-- @Override- public RecommendDecision recommend(- long tableId, long policyId, long sampledSnapshotId, String metricsJson) {- Optional<PolicyEntity> loaded = policyLoader.apply(policyId);- if (loaded.isEmpty()) {- LOG.warn("In-job recommend: policy {} missing; skip (table={})", policyId, tableId);- return RecommendDecision.SKIP;- }- PolicyEntity policy = loaded.get();- if (policy.policyType() == Policy.BuiltInType.ICEBERG_COMPACTION- || policy.content() instanceof IcebergDataCompactionContent) {- return compactionRecommender.recommend(- tableId, policyId, sampledSnapshotId, metricsJson, policy);- }- if (isPlaceholderMaintenance(policy)) {- return placeholderRecommender.recommend(- tableId, policyId, sampledSnapshotId, metricsJson, policy);- }- return triggerExprRecommender.recommend(- tableId, policyId, sampledSnapshotId, metricsJson, policy);- }-- private static boolean isPlaceholderMaintenance(PolicyEntity policy) {- Policy.BuiltInType type = policy.policyType();- return type == Policy.BuiltInType.ICEBERG_SNAPSHOT_EXPIRATION- || type == Policy.BuiltInType.ICEBERG_REWRITE_MANIFESTS- || policy.content() instanceof IcebergSnapshotExpirationContent- || policy.content() instanceof IcebergRewriteManifestsContent;- }-- private static Optional<PolicyEntity> loadPolicy(long policyId) {- return Optional.ofNullable(POLICY_SERVICE.getPolicyById(policyId));- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/listener/PostCommitMaintenanceListener.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/listener/PostCommitMaintenanceListener.javaindex ade19680e0..55c5f0400c 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/listener/PostCommitMaintenanceListener.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/listener/PostCommitMaintenanceListener.java@@ -18,34 +18,30 @@*/package org.apache.gravitino.maintenance.listener;-import com.google.common.annotations.VisibleForTesting;import java.util.Map;-import java.util.function.Function;-import javax.sql.DataSource;import org.apache.gravitino.Config;import org.apache.gravitino.GravitinoEnv;-import org.apache.gravitino.NameIdentifier;-import org.apache.gravitino.exceptions.NoSuchEntityException;import org.apache.gravitino.listener.api.EventListenerPlugin;import org.apache.gravitino.listener.api.event.Event;+import org.apache.gravitino.maintenance.MaintenanceActionManager;+import org.apache.gravitino.maintenance.scheduler.AutocommitDataSources;import org.apache.gravitino.maintenance.scheduler.job.commit.CommitJobClient;-import org.apache.gravitino.maintenance.scheduler.job.commit.CommitJobEnqueueResult;-import org.apache.gravitino.meta.TableEntity;+import org.apache.gravitino.maintenance.scheduler.job.commit.CommitJobPlanner;+import org.apache.gravitino.storage.relational.service.PolicyMetaService;import org.apache.gravitino.storage.relational.service.TableMetaService;-import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/**- * Enqueues a one-shot {@code commit-job} / {@code {table_id}} after a successful IRC table update- * (§5.2.3).+ * Wakes commit maintenance after a successful IRC table update (§5.2.3): filters the event and+ * calls {@link CommitJobClient#scheduleNow}.*- * <p>Register with {@code gravitino.eventListener.names} / {@code .{name}.class}. Enqueue builds- * the onCommit chain spec (cooldown gate + jobConf) into {@code task_data}; the commit pool- * consumes that spec and submits Spark.+ * <p>Register with {@code gravitino.eventListener.names} / {@code .{name}.class}. Uses the event+ * class name (not a compile dependency on {@code iceberg-rest-server}) so TMS can load when IRC+ * events are absent from the classpath.*- * <p>Uses the event class name (not a compile dependency on {@code iceberg-rest-server}) so TMS can- * load when IRC events are absent from the classpath.+ * <p>This listener is a second composition root for the commit path (loaded by the event-listener+ * framework, not by {@code TableMaintenanceRESTFeature}).*/public class PostCommitMaintenanceListener implements EventListenerPlugin {@@ -56,7 +52,6 @@ public class PostCommitMaintenanceListener implements EventListenerPlugin {"org.apache.gravitino.listener.api.event.IcebergUpdateTableEvent";private CommitJobClient commitJobClient;- private Function<NameIdentifier, TableEntity> tableLookupOverride;@Overridepublic void init(Map<String, String> properties) throws RuntimeException {@@ -65,13 +60,20 @@ public class PostCommitMaintenanceListener implements EventListenerPlugin {@Overridepublic void start() throws RuntimeException {- DataSource dataSource = resolveEntityStoreDataSource();- Config gravitinoConfig = GravitinoEnv.getInstance().config();+ GravitinoEnv env = GravitinoEnv.getInstance();+ Config gravitinoConfig = env.config();if (gravitinoConfig == null) {throw new IllegalStateException("GravitinoEnv config is not available");}- this.commitJobClient = new CommitJobClient(dataSource, gravitinoConfig);- LOG.info("PostCommitMaintenanceListener started (commit-job enqueue with spec)");+ CommitJobPlanner planner =+ new CommitJobPlanner(+ gravitinoConfig,+ MaintenanceActionManager.getInstance(),+ TableMetaService.getInstance(),+ PolicyMetaService.getInstance(),+ env.entityStore());+ this.commitJobClient = new CommitJobClient(AutocommitDataSources.entityStore(), planner);+ LOG.info("PostCommitMaintenanceListener started");}@Override@@ -89,82 +91,11 @@ public class PostCommitMaintenanceListener implements EventListenerPlugin {if (postEvent == null || !ICEBERG_UPDATE_TABLE_EVENT.equals(postEvent.getClass().getName())) {return;}- enqueueCommitJob(postEvent.identifier());- }-- /**- * Resolves {@code identifier} to a table entity id and enqueues {@code commit-job}.- *- * @param identifier Gravitino table name identifier from the IRC event- */- @VisibleForTesting- void enqueueCommitJob(NameIdentifier identifier) {CommitJobClient client = commitJobClient;if (client == null) {LOG.debug("Ignoring IcebergUpdateTableEvent; commit-job client is not started");return;}- if (identifier == null) {- return;- }- try {- long tableId = resolveTableId(identifier);- CommitJobEnqueueResult result = client.enqueueNow(tableId);- switch (result) {- case INSERTED:- LOG.info("Enqueued commit-job for table {} ({})", tableId, identifier);- break;- case ALREADY_QUEUED:- LOG.debug("commit-job already queued for table {} ({})", tableId, identifier);- break;- case SKIPPED:- LOG.debug(- "Skipped commit-job enqueue for table {} ({}) (empty chain, unresolved table, auth, or jobConf build)",- tableId,- identifier);- break;- default:- throw new IllegalStateException("Unexpected commit-job enqueue result: " + result);- }- } catch (NoSuchEntityException e) {- LOG.debug("No Gravitino table for IRC update {}: {}", identifier, e.getMessage());- } catch (RuntimeException e) {- LOG.warn("Failed to enqueue commit-job for IRC update {}: {}", identifier, e.toString());- }- }-- @VisibleForTesting- void setCommitJobClient(CommitJobClient commitJobClient) {- this.commitJobClient = commitJobClient;- }-- @VisibleForTesting- void setTableLookup(Function<NameIdentifier, TableEntity> tableLookup) {- this.tableLookupOverride = tableLookup;- }-- private long resolveTableId(NameIdentifier identifier) {- if (tableLookupOverride != null) {- TableEntity table = tableLookupOverride.apply(identifier);- if (table == null) {- throw new NoSuchEntityException("table not found: %s", identifier);- }- return table.id();- }- TableEntity table = TableMetaService.getInstance().getTableByIdentifier(identifier);- return table.id();- }-- private static DataSource resolveEntityStoreDataSource() {- Object dataSource =- SqlSessionFactoryHelper.getInstance()- .getSqlSessionFactory()- .getConfiguration()- .getEnvironment()- .getDataSource();- if (!(dataSource instanceof DataSource)) {- throw new IllegalStateException("Entity store data source is not available");- }- return (DataSource) dataSource;+ client.scheduleNow(postEvent.identifier());}}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/model/OccupancyClaim.javasimilarity index 86%rename from plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/service/OccupancyClaim.javarename to plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/model/OccupancyClaim.javaindex 0684f60639..d74861375d 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/model/OccupancyClaim.java@@ -16,16 +16,18 @@* specific language governing permissions and limitations* under the License.*/-package org.apache.gravitino.maintenance.storage.service;+package org.apache.gravitino.maintenance.model;import java.util.Objects;/*** Immutable occupancy claim returned by acquire.*- * <p>Callers must pass {@link #createdAt()} to {@link TableMaintenanceActionMetaService#bindJobId}- * and {@link TableMaintenanceActionMetaService#deleteUnboundClaim} without re-reading {@code- * created_at} from the row.+ * <p>Callers must pass {@link #createdAt()} to {@link+ * org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService#bindJobId} and+ * {@link+ * org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService#deleteUnboundClaim}+ * without re-reading {@code created_at} from the row.** <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 claimdiff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/model/TableCandidate.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/model/TableCandidate.javanew file mode 100644index 0000000000..a6a16765c0--- /dev/null+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/model/TableCandidate.java@@ -0,0 +1,119 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.maintenance.model;++import com.google.common.base.Preconditions;+import com.google.common.collect.ImmutableList;+import java.util.List;+import java.util.Objects;+import org.apache.gravitino.meta.PolicyEntity;++/**+ * One table plus the maintenance policies to schedule for it. Used by both cron and commit {@code+ * MaintenanceJobSpec} builders; each table may carry a different policy list.+ */+public final class TableCandidate {++ private final long tableId;+ private final String catalogName;+ private final String tableIdentifier;+ private final List<PolicyEntity> policies;++ /**+ * @param tableId table entity id+ * @param catalogName catalog name+ * @param tableIdentifier {@code schema.table} Spark identifier+ * @param policies policies for this table (order preserved; must not be empty)+ */+ public TableCandidate(+ long tableId, String catalogName, String tableIdentifier, List<PolicyEntity> policies) {+ Preconditions.checkArgument(tableId > 0, "tableId must be positive");+ Preconditions.checkArgument(+ catalogName != null && !catalogName.isBlank(), "catalogName must not be blank");+ Preconditions.checkArgument(+ tableIdentifier != null && !tableIdentifier.isBlank(), "tableIdentifier must not be blank");+ Preconditions.checkArgument(+ policies != null && !policies.isEmpty(), "policies must not be empty");+ this.tableId = tableId;+ this.catalogName = catalogName;+ this.tableIdentifier = tableIdentifier;+ this.policies = ImmutableList.copyOf(policies);+ }++ /**+ * @return table entity id+ */+ public long tableId() {+ return tableId;+ }++ /**+ * @return catalog name+ */+ public String catalogName() {+ return catalogName;+ }++ /**+ * @return {@code schema.table} Spark identifier+ */+ public String tableIdentifier() {+ return tableIdentifier;+ }++ /**+ * @return policies for this table in schedule order+ */+ public List<PolicyEntity> policies() {+ return policies;+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) {+ return true;+ }+ if (!(o instanceof TableCandidate)) {+ return false;+ }+ TableCandidate that = (TableCandidate) o;+ return tableId == that.tableId+ && catalogName.equals(that.catalogName)+ && tableIdentifier.equals(that.tableIdentifier)+ && policies.equals(that.policies);+ }++ @Override+ public int hashCode() {+ return Objects.hash(tableId, catalogName, tableIdentifier, policies);+ }++ @Override+ public String toString() {+ return "TableCandidate{tableId="+ + tableId+ + ", catalogName="+ + catalogName+ + ", tableIdentifier="+ + tableIdentifier+ + ", policyIds="+ + policies.stream().map(PolicyEntity::id).toList()+ + '}';+ }+}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/policy/PolicyExpandLifecycleHook.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/policy/PolicyExpandLifecycleHook.javaindex 8c04bca777..6597d35276 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/policy/PolicyExpandLifecycleHook.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/policy/PolicyExpandLifecycleHook.java@@ -18,186 +18,42 @@*/package org.apache.gravitino.maintenance.policy;-import com.github.kagkarlsson.scheduler.task.ExecutionComplete;-import com.github.kagkarlsson.scheduler.task.ExecutionOperations;-import java.time.Instant;-import java.util.Optional;-import javax.annotation.Nullable;-import org.apache.gravitino.maintenance.scheduler.MaintenanceTaskIds;-import org.apache.gravitino.meta.BaseMetalake;+import com.google.common.base.Preconditions;+import org.apache.gravitino.maintenance.scheduler.policy.expand.PolicyExpandClient;import org.apache.gravitino.meta.PolicyEntity;-import org.apache.gravitino.policy.ExecutablePolicyContent;-import org.apache.gravitino.policy.Policy;-import org.apache.gravitino.policy.PolicyContent;import org.apache.gravitino.policy.hook.PolicyLifecycleHook;-import org.apache.gravitino.storage.relational.service.MetalakeMetaService;-import org.apache.gravitino.storage.relational.service.PolicyMetaService;-import org.apache.gravitino.utils.NamespaceUtil;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;/**- * Keeps the expand-pool row aligned with a maintenance policy inside the policy transaction.+ * Forwards policy create / alter / delete onto {@link PolicyExpandClient} inside the policy+ * transaction.*- * <p>An enabled maintenance policy with a non-blank {@code timeTrigger} is scheduled. Disable, a- * blank trigger, and a non-maintenance write remove the row. Delete removes the row by policy id.- * An invalid cron throws on write so the policy change rolls back; on startup reconcile the expand- * row is removed so scheduler state is corrected while the bad policy content remains to be edited.+ * <p>{@link PolicyExpandClient#sync} schedules or removes the expand row from policy content.+ * Delete removes the row by policy id. Invalid cron on write throws so the policy change rolls+ * back.*/public final class PolicyExpandLifecycleHook implements PolicyLifecycleHook {- private static final Logger LOG = LoggerFactory.getLogger(PolicyExpandLifecycleHook.class);-- private final PolicyExpandRegistrar registrar;+ private final PolicyExpandClient expandClient;/**- * @param registrar registers policy-expand task rows on the current SQL session+ * @param expandClient writes policy-expand rows on the current SQL session*/- public PolicyExpandLifecycleHook(PolicyExpandRegistrar registrar) {- this.registrar = registrar;+ public PolicyExpandLifecycleHook(PolicyExpandClient expandClient) {+ this.expandClient = Preconditions.checkNotNull(expandClient);}@Overridepublic void afterPersist(PolicyEntity policy) {- syncExpandRow(policy);+ expandClient.sync(policy);}@Overridepublic void afterUpdate(PolicyEntity policy) {- syncExpandRow(policy);+ expandClient.sync(policy);}@Overridepublic void beforeRemove(long policyId) {- registrar.remove(policyId);- }-- /**- * Aligns the {@code policy-expand} task for a stored policy (startup reconcile).- *- * <p>Only mutates expand tasks: inserts when missing; reschedules a <em>future</em> due that no- * longer matches the policy cron; leaves an overdue due (< now) alone so the expand pool can- * catch up after downtime. Removes the expand task when the policy must not run or the cron is- * invalid. Never deletes the policy itself.- *- * @param policy persisted policy- */- public void align(PolicyEntity policy) {- if (!isMaintenance(policy.content())) {- registrar.remove(policy.id());- return;- }- String trigger = timeTrigger(policy.content());- if (!policy.enabled() || trigger == null || trigger.isBlank()) {- registrar.remove(policy.id());- return;- }- Instant expectedNext;- try {- expectedNext = PolicyExpandRegistrar.nextExecution(trigger);- } catch (IllegalArgumentException e) {- registrar.remove(policy.id());- LOG.error(- "Cleared policy-expand task for policy id {} name {} with invalid timeTrigger; fix the policy content",- policy.id(),- policy.name(),- e);- return;- }- Optional<Instant> current = registrar.scheduledExecutionTime(policy.id());- Instant now = Instant.now();- if (current.isPresent() && current.get().isBefore(now)) {- // Overdue: keep so db-scheduler can catch up after a restart.- return;- }- if (current.isPresent() && current.get().equals(expectedNext)) {- return;- }- registrar.scheduleAt(policy.id(), expectedNext);- }-- /**- * Finishes one pick of {@code policy-expand}.- *- * <p>Reloads the policy and either removes the row or moves it to the next cron fire. An empty- * completion would leave the row picked, and db-scheduler then rejects alter and delete of that- * policy.- *- * @param instanceId db-scheduler task instance id ({@code policy:{policy_id}})- * @param complete the pick that just finished- * @param operations completion actions for that pick- */- public static void completePick(- String instanceId, ExecutionComplete complete, ExecutionOperations<Void> operations) {- Optional<Long> parsed = MaintenanceTaskIds.parseExpandPolicy(instanceId);- if (parsed.isEmpty()) {- operations.remove();- return;- }- long policyId = parsed.get();- PolicyEntity policy = findPolicy(policyId);- if (policy == null || !isMaintenance(policy.content())) {- operations.remove();- return;- }- String trigger = timeTrigger(policy.content());- if (!policy.enabled() || trigger == null || trigger.isBlank()) {- operations.remove();- return;- }- try {- operations.reschedule(complete, PolicyExpandRegistrar.nextExecution(trigger));- } catch (IllegalArgumentException e) {- LOG.error(- "Removing policy-expand {} after invalid timeTrigger on policy {}",- policyId,- policy.name(),- e);- operations.remove();- }- }-- private void syncExpandRow(PolicyEntity policy) {- if (!isMaintenance(policy.content())) {- registrar.remove(policy.id());- return;- }- registrar.sync(policy.id(), policy.enabled(), timeTrigger(policy.content()));- }-- private static boolean isMaintenance(@Nullable PolicyContent content) {- if (content == null) {- return false;- }- for (Policy.BuiltInType type : Policy.BuiltInType.values()) {- if (MaintenancePolicyDefinitions.isMaintenance(type)- && type.contentClass().isInstance(content)) {- return true;- }- }- return false;- }-- @Nullable- private static PolicyEntity findPolicy(long policyId) {- MetalakeMetaService metalakes = MetalakeMetaService.getInstance();- PolicyMetaService policies = PolicyMetaService.getInstance();- for (BaseMetalake metalake : metalakes.listMetalakes()) {- for (PolicyEntity policy :- policies.listPoliciesByNamespace(NamespaceUtil.ofPolicy(metalake.name()))) {- if (policy.id() == policyId) {- return policy;- }- }- }- return null;- }-- @Nullable- private static String timeTrigger(@Nullable PolicyContent content) {- if (!(content instanceof ExecutablePolicyContent)) {- return null;- }- return ((ExecutablePolicyContent) content).executionSpec().timeTrigger();+ expandClient.remove(policyId);}}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/policy/PolicyExpandReconciler.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/policy/PolicyExpandReconciler.javaindex fe8bbb5fa0..684327c670 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/policy/PolicyExpandReconciler.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/policy/PolicyExpandReconciler.java@@ -18,8 +18,10 @@*/package org.apache.gravitino.maintenance.policy;+import com.google.common.base.Preconditions;import java.util.HashSet;import java.util.Set;+import org.apache.gravitino.maintenance.scheduler.policy.expand.PolicyExpandClient;import org.apache.gravitino.meta.BaseMetalake;import org.apache.gravitino.meta.PolicyEntity;import org.apache.gravitino.storage.relational.service.MetalakeMetaService;@@ -49,36 +51,22 @@ public final class PolicyExpandReconciler {private static final Logger LOG = LoggerFactory.getLogger(PolicyExpandReconciler.class);- private final PolicyExpandLifecycleHook aligner;- private final PolicyExpandRegistrar registrar;+ private final PolicyExpandClient expandClient;private final MetalakeMetaService metalakeMetaService;private final PolicyMetaService policyMetaService;/**- * @param aligner same expand rules as the lifecycle hook- * @param registrar writer used for orphan cleanup; both must use {@link- * PolicyExpandRegistrar#joiningCurrentTransaction()}- */- public PolicyExpandReconciler(- PolicyExpandLifecycleHook aligner, PolicyExpandRegistrar registrar) {- this(aligner, registrar, MetalakeMetaService.getInstance(), PolicyMetaService.getInstance());- }-- /**- * @param aligner expand aligner- * @param registrar expand registrar for orphan deletes+ * @param expandClient expand writer used for {@link PolicyExpandClient#align} and orphan cleanup* @param metalakeMetaService metalake listing* @param policyMetaService policy listing*/public PolicyExpandReconciler(- PolicyExpandLifecycleHook aligner,- PolicyExpandRegistrar registrar,+ PolicyExpandClient expandClient,MetalakeMetaService metalakeMetaService,PolicyMetaService policyMetaService) {- this.aligner = aligner;- this.registrar = registrar;- this.metalakeMetaService = metalakeMetaService;- this.policyMetaService = policyMetaService;+ this.expandClient = Preconditions.checkNotNull(expandClient);+ this.metalakeMetaService = Preconditions.checkNotNull(metalakeMetaService);+ this.policyMetaService = Preconditions.checkNotNull(policyMetaService);}/**@@ -94,7 +82,7 @@ public final class PolicyExpandReconciler {for (PolicyEntity policy :policyMetaService.listPoliciesByNamespace(NamespaceUtil.ofPolicy(metalake.name()))) {knownPolicyIds.add(policy.id());- SessionUtils.doMultipleWithCommit(() -> aligner.align(policy));+ SessionUtils.doMultipleWithCommit(() -> expandClient.align(policy));aligned++;}}@@ -102,9 +90,9 @@ public final class PolicyExpandReconciler {int[] removedOrphans = {0};SessionUtils.doMultipleWithCommit(() -> {- for (long scheduledId : registrar.scheduledPolicyIds()) {+ for (long scheduledId : expandClient.scheduledPolicyIds()) {if (!knownPolicyIds.contains(scheduledId)) {- registrar.remove(scheduledId);+ expandClient.remove(scheduledId);removedOrphans[0]++;}}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/policy/PolicyExpandRegistrar.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/policy/PolicyExpandRegistrar.javadeleted file mode 100644index e61af6ea93..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/policy/PolicyExpandRegistrar.java+++ /dev/null@@ -1,331 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.policy;--import com.github.kagkarlsson.scheduler.SchedulerClient;-import com.github.kagkarlsson.scheduler.exceptions.TaskInstanceCurrentlyExecutingException;-import com.github.kagkarlsson.scheduler.task.ExecutionComplete;-import com.github.kagkarlsson.scheduler.task.TaskInstance;-import com.github.kagkarlsson.scheduler.task.TaskInstanceId;-import com.github.kagkarlsson.scheduler.task.schedule.CronSchedule;-import com.github.kagkarlsson.scheduler.task.schedule.CronStyle;-import com.github.kagkarlsson.scheduler.task.schedule.Schedule;-import com.google.common.annotations.VisibleForTesting;-import java.io.PrintWriter;-import java.lang.reflect.InvocationHandler;-import java.lang.reflect.InvocationTargetException;-import java.lang.reflect.Proxy;-import java.sql.Connection;-import java.sql.SQLException;-import java.sql.SQLFeatureNotSupportedException;-import java.time.Instant;-import java.time.ZoneId;-import java.util.HashSet;-import java.util.Optional;-import java.util.Set;-import javax.annotation.Nullable;-import javax.sql.DataSource;-import org.apache.gravitino.maintenance.scheduler.AutocommitDataSources;-import org.apache.gravitino.maintenance.scheduler.MaintenanceTaskIds;-import org.apache.gravitino.maintenance.scheduler.TableMaintenanceSchedulerPools;-import org.apache.gravitino.storage.relational.session.SqlSessions;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--/**- * Registers {@code policy-expand} tasks in {@link- * TableMaintenanceSchedulerPools#EXPAND_TASKS_TABLE} through a db-scheduler client.- *- * <p>The instance id is the policy id. A blank {@code timeTrigger}, or a disabled policy, removes- * the row. Handlers that fan the row out into cron jobs are out of scope here.- *- * <p>{@code timeTrigger} is a six-field Quartz cron. This class decides whether the expression has- * a next fire time; policy content does not parse cron itself.- *- * <p>{@link #joiningCurrentTransaction()} writes through the open MyBatis session. The client must- * not commit or close that connection, so the policy transaction and the expand row commit- * together.- */-public final class PolicyExpandRegistrar {-- private static final Logger LOG = LoggerFactory.getLogger(PolicyExpandRegistrar.class);-- /** Attempts while a pick still owns the expand row. */- private static final int EXECUTING_ATTEMPTS = 10;-- /** Pause between attempts, so a short pick can finish inside the policy transaction. */- private static final long EXECUTING_WAIT_MS = 50L;-- private final DataSource dataSource;-- private PolicyExpandRegistrar(DataSource dataSource) {- this.dataSource = dataSource;- }-- /**- * Opens a client that writes on the current thread's open SQL session.- *- * <p>The db-scheduler client is created on each call, because building it borrows a connection.- * That connection is the open session, so this registrar must be used inside a policy- * transaction.- *- * @return registrar that inserts, moves, and deletes expand rows in the caller's transaction- */- public static PolicyExpandRegistrar joiningCurrentTransaction() {- return new PolicyExpandRegistrar(new SessionDataSource());- }-- /**- * Opens a client against the entity-store pool with JDBC autocommit forced on.- *- * <p>Used for post-commit reads and test-only writes such as {@link #scheduleAt}. The- * entity-store pool often disables autocommit; without this wrap, SchedulerClient mutations would- * not commit and the expand pool would never observe them.- *- * @param dataSource relational JDBC pool shared with the entity store- * @return registrar that can read (and test-write) expand rows after the policy transaction- * commits- */- public static PolicyExpandRegistrar forReads(DataSource dataSource) {- return new PolicyExpandRegistrar(AutocommitDataSources.wrap(dataSource));- }-- private SchedulerClient client() {- return SchedulerClient.Builder.create(- dataSource, TableMaintenanceSchedulerPools.policyExpandTask())- .tableName(TableMaintenanceSchedulerPools.EXPAND_TASKS_TABLE)- .build();- }-- /**- * Inserts or moves the expand row to the next cron fire time, or removes it when the policy- * should not run.- *- * @param policyId persisted policy id, used as the db-scheduler task instance- * @param enabled whether the policy is enabled- * @param timeTrigger cron expression, or {@code null} when the policy has no time trigger- */- public void sync(long policyId, boolean enabled, @Nullable String timeTrigger) {- TaskInstanceId instanceId = instanceId(policyId);- if (!enabled || timeTrigger == null || timeTrigger.isBlank()) {- cancelIfPresent(instanceId);- return;- }- scheduleAt(policyId, nextExecution(timeTrigger));- }-- /**- * Inserts or moves the expand row to an explicit due time.- *- * @param policyId persisted policy id- * @param due execution time to store- */- @VisibleForTesting- public void scheduleAt(long policyId, Instant due) {- runDespiteExecution(() -> scheduleOnce(policyId, due));- }-- /**- * Deletes the expand row for a dropped policy.- *- * @param policyId persisted policy id- */- public void remove(long policyId) {- cancelIfPresent(instanceId(policyId));- }-- /**- * @param policyId persisted policy id- * @return next execution time of the expand row, or empty when the row is absent- */- @VisibleForTesting- public Optional<Instant> scheduledExecutionTime(long policyId) {- return client()- .getScheduledExecution(instanceId(policyId))- .map(execution -> execution.getExecutionTime());- }-- /**- * @return policy ids that currently have a {@code policy-expand} row- */- Set<Long> scheduledPolicyIds() {- Set<Long> ids = new HashSet<>();- client()- .fetchScheduledExecutionsForTask(- TableMaintenanceSchedulerPools.POLICY_EXPAND,- Void.class,- execution -> {- MaintenanceTaskIds.parseExpandPolicy(execution.getTaskInstance().getId())- .ifPresent(ids::add);- });- return ids;- }-- /**- * Next fire time for a Quartz cron, strictly after now.- *- * @param timeTrigger six-field Quartz cron expression- * @return next execution instant in the system default zone- */- static Instant nextExecution(String timeTrigger) {- CronSchedule schedule = new CronSchedule(timeTrigger, ZoneId.systemDefault(), CronStyle.QUARTZ);- Instant next = schedule.getNextExecutionTime(ExecutionComplete.simulatedSuccess(Instant.now()));- if (next == null || Schedule.NEVER.equals(next)) {- throw new IllegalArgumentException("timeTrigger has no next execution: " + timeTrigger);- }- return next;- }-- private static TaskInstanceId instanceId(long policyId) {- return TaskInstanceId.of(- TableMaintenanceSchedulerPools.POLICY_EXPAND, MaintenanceTaskIds.forExpandPolicy(policyId));- }-- private void scheduleOnce(long policyId, Instant due) {- TaskInstanceId instanceId = instanceId(policyId);- boolean scheduled =- client()- .schedule(- new TaskInstance<>(- TableMaintenanceSchedulerPools.POLICY_EXPAND, instanceId.getId()),- due,- SchedulerClient.ScheduleOptions.WHEN_EXISTS_RESCHEDULE);- if (!scheduled) {- throw new IllegalStateException(- "Failed to schedule policy-expand instance " + instanceId.getId() + " at " + due);- }- }-- private void cancelIfPresent(TaskInstanceId instanceId) {- runDespiteExecution(- () -> {- SchedulerClient client = client();- if (client.getScheduledExecution(instanceId).isPresent()) {- client.cancel(instanceId);- }- });- }-- /**- * Retries while db-scheduler reports the expand row as picked.- *- * <p>A pick rejects both reschedule and cancel. Failing the attempt here would roll the policy- * transaction back. After the retry window the in-flight execution applies the committed policy- * from {@link PolicyExpandLifecycleHook#completePick}.- *- * @param action one scheduler write- */- private static void runDespiteExecution(Runnable action) {- for (int attempt = 1; ; attempt++) {- try {- action.run();- return;- } catch (TaskInstanceCurrentlyExecutingException e) {- if (attempt >= EXECUTING_ATTEMPTS) {- LOG.warn(- "policy-expand row is still executing; leaving the in-flight pick to apply the policy",- e);- return;- }- try {- Thread.sleep(EXECUTING_WAIT_MS);- } catch (InterruptedException interrupted) {- Thread.currentThread().interrupt();- e.addSuppressed(interrupted);- throw e;- }- }- }- }-- /**- * Hands db-scheduler the connection of the open SQL session. {@code close}, {@code commit}, and- * {@code rollback} are ignored so the session owner commits the expand row with the policy.- */- private static final class SessionDataSource implements DataSource {-- @Override- public Connection getConnection() throws SQLException {- return nonClosing(SqlSessions.currentConnection());- }-- @Override- public Connection getConnection(String username, String password) throws SQLException {- return getConnection();- }-- @Override- public PrintWriter getLogWriter() {- return null;- }-- @Override- public void setLogWriter(PrintWriter out) {}-- @Override- public void setLoginTimeout(int seconds) {}-- @Override- public int getLoginTimeout() {- return 0;- }-- @Override- public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {- throw new SQLFeatureNotSupportedException();- }-- @Override- public <T> T unwrap(Class<T> iface) throws SQLException {- if (iface.isInstance(this)) {- return iface.cast(this);- }- throw new SQLException("Not a wrapper of " + iface.getName());- }-- @Override- public boolean isWrapperFor(Class<?> iface) {- return iface.isInstance(this);- }-- private static Connection nonClosing(Connection connection) {- InvocationHandler handler =- (proxy, method, args) -> {- String name = method.getName();- if ("close".equals(name) || "commit".equals(name) || "rollback".equals(name)) {- return null;- }- if ("setAutoCommit".equals(name)) {- return null;- }- if ("getAutoCommit".equals(name)) {- return false;- }- try {- return method.invoke(connection, args);- } catch (InvocationTargetException e) {- throw e.getCause();- }- };- return (Connection)- Proxy.newProxyInstance(- Connection.class.getClassLoader(), new Class<?>[] {Connection.class}, handler);- }- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/AutocommitDataSources.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/AutocommitDataSources.javaindex c8d12e22bb..4b9f998613 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/AutocommitDataSources.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/AutocommitDataSources.java@@ -19,22 +19,51 @@package org.apache.gravitino.maintenance.scheduler;import java.io.PrintWriter;-import java.lang.reflect.InvocationHandler;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Proxy;import java.sql.Connection;import java.sql.SQLException;import java.sql.SQLFeatureNotSupportedException;+import java.util.Objects;+import java.util.Set;+import java.util.function.Function;import javax.sql.DataSource;+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;+import org.apache.gravitino.storage.relational.session.SqlSessions;/**- * Wraps the entity-store {@link DataSource} so db-scheduler {@code SchedulerClient} calls commit- * even when the pool disables JDBC autocommit.+ * {@link DataSource} adapters for db-scheduler clients: force JDBC autocommit on pooled+ * connections, reuse the open MyBatis session so expand rows commit with the policy, or bind+ * several SchedulerClient writes to one JDBC transaction.*/public final class AutocommitDataSources {+ private static final Set<String> JOIN_SESSION_NOOPS =+ Set.of("close", "commit", "rollback", "setAutoCommit");++ /** Ignores {@code close} so db-scheduler can reuse one transactional connection. */+ private static final Set<String> BOUND_TX_NOOPS = Set.of("close", "setAutoCommit");+private AutocommitDataSources() {}+ /**+ * Resolves the relational entity-store JDBC pool from the open MyBatis environment.+ *+ * @return entity-store {@link DataSource}+ */+ public static DataSource entityStore() {+ Object dataSource =+ SqlSessionFactoryHelper.getInstance()+ .getSqlSessionFactory()+ .getConfiguration()+ .getEnvironment()+ .getDataSource();+ if (!(dataSource instanceof DataSource)) {+ throw new IllegalStateException("Entity store data source is not available");+ }+ return (DataSource) dataSource;+ }+/*** @param delegate entity-store pool* @return proxy that forces {@code autoCommit=true} on borrowed connections@@ -43,11 +72,104 @@ public final class AutocommitDataSources {return new AutocommitDataSource(delegate);}- private static final class AutocommitDataSource implements DataSource {+ /**+ * Hands db-scheduler the open MyBatis connection. {@code close}/{@code commit}/{@code rollback}+ * are ignored so the session owner commits with the caller.+ *+ * @return data source bound to {@link SqlSessions#currentConnection()}+ */+ public static DataSource joiningCurrentSession() {+ return new SimpleDataSource() {+ @Override+ public Connection getConnection() throws SQLException {+ return proxyConnection(+ SqlSessions.currentConnection(), /*autocommit=*/ false, JOIN_SESSION_NOOPS);+ }+ };+ }++ /**+ * Runs {@code work} with a {@link DataSource} that always returns the same connection ({@code+ * autoCommit=false}). Commits when {@code work} returns; rolls back when it throws. db-scheduler+ * {@code SchedulerClient} calls on that data source share one JDBC transaction (join via a+ * transaction-aware {@link DataSource}).+ *+ * @param pool entity-store pool (not the autocommit wrap)+ * @param work receives a bound data source; return value is committed+ * @param <T> result type+ * @return result of {@code work}+ * @throws SQLException if borrowing, commit, or rollback fails+ */+ public static <T> T runInTransaction(DataSource pool, Function<DataSource, T> work)+ throws SQLException {+ Objects.requireNonNull(pool, "pool");+ Objects.requireNonNull(work, "work");+ Connection connection = pool.getConnection();+ boolean previousAutoCommit = connection.getAutoCommit();+ try {+ connection.setAutoCommit(false);+ DataSource bound =+ new SimpleDataSource() {+ @Override+ public Connection getConnection() throws SQLException {+ return proxyConnection(connection, /*autocommit=*/ false, BOUND_TX_NOOPS);+ }+ };+ try {+ T result = work.apply(bound);+ connection.commit();+ return result;+ } catch (RuntimeException e) {+ try {+ connection.rollback();+ } catch (SQLException rollbackFailure) {+ e.addSuppressed(rollbackFailure);+ }+ throw e;+ }+ } finally {+ try {+ connection.setAutoCommit(previousAutoCommit);+ } catch (SQLException ignored) {+ // best-effort restore before close+ }+ connection.close();+ }+ }++ private static Connection proxyConnection(+ Connection connection, boolean autocommit, Set<String> noops) {+ return (Connection)+ Proxy.newProxyInstance(+ Connection.class.getClassLoader(),+ new Class<?>[] {Connection.class},+ (proxy, method, args) -> {+ String name = method.getName();+ if (autocommit) {+ if ("setAutoCommit".equals(name)) {+ return null;+ }+ if ("getAutoCommit".equals(name)) {+ return true;+ }+ } else if (noops.contains(name)) {+ return null;+ } else if ("getAutoCommit".equals(name)) {+ return false;+ }+ try {+ return method.invoke(connection, args);+ } catch (InvocationTargetException e) {+ throw e.getCause();+ }+ });+ }++ private static final class AutocommitDataSource extends SimpleDataSource {private final DataSource delegate;- AutocommitDataSource(DataSource delegate) {+ private AutocommitDataSource(DataSource delegate) {this.delegate = delegate;}@@ -100,30 +222,51 @@ public final class AutocommitDataSources {}private static Connection withAutocommit(Connection connection) throws SQLException {- Connection proxy =- (Connection)- Proxy.newProxyInstance(- Connection.class.getClassLoader(),- new Class<?>[] {Connection.class},- suppressingSetAutocommit(connection));connection.setAutoCommit(true);- return proxy;+ return proxyConnection(connection, /*autocommit=*/ true, Set.of());}+ }- private static InvocationHandler suppressingSetAutocommit(Connection connection) {- return (proxy, method, args) -> {- if ("setAutoCommit".equals(method.getName())) {- return null;- }- if ("getAutoCommit".equals(method.getName())) {- return true;- }- try {- return method.invoke(connection, args);- } catch (InvocationTargetException e) {- throw e.getCause();- }- };+ /** Minimal {@link DataSource}; subclasses override connection borrowing. */+ private abstract static class SimpleDataSource implements DataSource {++ @Override+ public Connection getConnection(String username, String password) throws SQLException {+ return getConnection();+ }++ @Override+ public PrintWriter getLogWriter() throws SQLException {+ return null;+ }++ @Override+ public void setLogWriter(PrintWriter out) throws SQLException {}++ @Override+ public void setLoginTimeout(int seconds) throws SQLException {}++ @Override+ public int getLoginTimeout() throws SQLException {+ return 0;+ }++ @Override+ public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {+ throw new SQLFeatureNotSupportedException();+ }++ @Override+ public <T> T unwrap(Class<T> iface) throws SQLException {+ if (iface.isInstance(this)) {+ return iface.cast(this);+ }+ throw new SQLException("Not a wrapper of " + iface.getName());+ }++ @Override+ public boolean isWrapperFor(Class<?> iface) throws SQLException {+ return iface.isInstance(this);}}}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 5da9c2547e..ce3608beac 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@@ -31,17 +31,17 @@ 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;+import org.apache.gravitino.maintenance.scheduler.job.MaintenanceJobTemplates;/**- * Enqueue-time spec stored as JSON in db-scheduler {@code task_data} for {@code cron-job} and+ * Schedule-time spec stored as JSON in db-scheduler {@code task_data} for {@code cron-job} and* {@code commit-job} rows.** <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}.+ * routing fields plus a flat {@code parameters} map (old template placeholders). Shared {@code+ * updater_options} and {@code spark_conf} sit at the 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 {@@ -202,7 +202,7 @@ public final class MaintenanceJobSpec {* @param tableId table entity id* @param policyId policy entity id* @param maintenanceType Spark wire maintenance type- * @param actionId soft-slot action id when known; null at enqueue+ * @param actionId soft-slot action id when known; null at schedule* @param parameters flat template placeholders (old builtin jobConf keys)*/public Task(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 d6adf556ee..a7deedd4fc 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@@ -20,7 +20,6 @@ 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;@@ -30,20 +29,24 @@ import java.util.Locale;import java.util.Map;import java.util.Optional;import java.util.Set;+import java.util.TreeMap;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.annotation.Nullable;import org.apache.gravitino.Config;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;import org.apache.gravitino.json.JsonUtils;+import org.apache.gravitino.maintenance.model.TableCandidate;+import org.apache.gravitino.maintenance.optimizer.common.util.IcebergSparkConfigUtils;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.maintenance.scheduler.job.MaintenanceJobConfBuilder;+import org.apache.gravitino.maintenance.scheduler.job.MaintenanceJobTemplates;import org.apache.gravitino.meta.PolicyEntity;/**- * Builds enqueue-time {@link MaintenanceJobSpec} values for the cron path and helpers used by cron- * / commit submit to assemble the flat {@code runJob} map.+ * Builds schedule-time {@link MaintenanceJobSpec} values for the cron and commit paths, and helpers+ * used by submit to assemble the flat {@code runJob} map.*/public final class MaintenanceJobSpecFactory {@@ -52,8 +55,8 @@ public final class MaintenanceJobSpecFactory {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}.+ * Keys that belong on the shared {@code task_data} fields or are re-derived at submit — not+ * stored in per-task {@code parameters}.*/private static final Set<String> NON_PARAMETER_KEYS =ImmutableSet.of(@@ -85,52 +88,132 @@ public final class MaintenanceJobSpecFactory {}/**- * 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}.+ * Cron schedule-time spec. Each {@link TableCandidate} may carry its own policy list; every+ * (table, policy) pair becomes one {@link Task}. Shared {@code updater_options} come from the+ * first policy encountered; {@code spark_conf} max-merges across all policies.** <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.*- * @param policy effective maintenance policy- * @param tables resolved table refs (same order as enqueue)+ * @param tables table + policies units (same order as schedule)* @return spec ready for {@code task_data}*/- public MaintenanceJobSpec forCron(PolicyEntity policy, List<ResolvedTableRef> tables) {- Preconditions.checkNotNull(policy, "policy");- Preconditions.checkArgument(tables != null && !tables.isEmpty(), "tables must not be empty");- Optional<String> wire = MaintenanceJobTemplates.maintenanceType(policy.policyType());- Preconditions.checkArgument(- wire.isPresent(), "unsupported policy type %s", policy.policyType());+ public MaintenanceJobSpec forCron(List<TableCandidate> tables) {+ return build(tables);+ }++ /**+ * Commit schedule-time spec. Same shape as {@link #forCron}: typically one {@link TableCandidate}+ * whose {@code policies} are the onCommit chain. Caller filters cooldown and checks auth before+ * this.+ *+ * @param tables table + policies units+ * @return spec with one task per (table, policy)+ */+ public MaintenanceJobSpec forCommit(List<TableCandidate> tables) {+ return build(tables);+ }+ private MaintenanceJobSpec build(List<TableCandidate> tables) {+ Preconditions.checkArgument(tables != null && !tables.isEmpty(), "tables must not be empty");String catalogName = tables.get(0).catalogName();- for (ResolvedTableRef ref : tables) {+ for (TableCandidate table : tables) {Preconditions.checkArgument(- catalogName.equals(ref.catalogName()),- "cron batch tables must share catalogName; got %s and %s",+ catalogName.equals(table.catalogName()),+ "tables must share catalogName; got %s and %s",catalogName,- ref.catalogName());+ table.catalogName());}- Map<String, String> built = jobConfBuilder.build(policy, catalogName);- MaintenanceJobConfBuilder.foldPlaceholdersIntoSparkConf(built, catalogName);- EnqueueBags bags = splitEnqueueBags(built);+ String updaterOptions = null;+ Map<String, String> sparkConf = new LinkedHashMap<>();+ List<Task> tasks = new ArrayList<>();+ boolean firstPolicy = true;+ for (TableCandidate table : tables) {+ for (PolicyEntity policy : table.policies()) {+ Optional<String> wire = MaintenanceJobTemplates.maintenanceType(policy.policyType());+ Preconditions.checkArgument(+ wire.isPresent(), "unsupported policy type %s", policy.policyType());+ Map<String, String> built = jobConfBuilder.build(policy, catalogName);+ MaintenanceJobConfBuilder.foldPlaceholdersIntoSparkConf(built, catalogName);+ JobConfParts parts = splitJobConfParts(built);+ if (firstPolicy) {+ updaterOptions = parts.updaterOptions;+ if (parts.sparkConf != null && !parts.sparkConf.isBlank()) {+ sparkConf.putAll(+ IcebergSparkConfigUtils.parseFlatJsonMap(parts.sparkConf, "spark_conf"));+ }+ firstPolicy = false;+ } else {+ mergeSparkConfMaps(sparkConf, parts.sparkConf);+ }+ Map<String, String> parameters = new LinkedHashMap<>(parts.parameters);+ parameters.put("catalog_name", table.catalogName());+ parameters.put("table_identifier", table.tableIdentifier());+ tasks.add(new Task(table.tableId(), policy.id(), wire.get(), null, parameters));+ }+ }+ String sparkConfJson = sparkConf.isEmpty() ? null : writeJson(sparkConf, "spark_conf");+ return new MaintenanceJobSpec(tasks, updaterOptions, sparkConfJson);+ }- List<Task> tasks = new ArrayList<>(tables.size());- for (ResolvedTableRef ref : tables) {- 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));+ /**+ * Catalog name from a table {@link NameIdentifier} ({@code namespace.level(1)}).+ *+ * @param identifier metalake.catalog.schema…table+ * @return catalog name+ */+ public static String catalogName(NameIdentifier identifier) {+ Namespace namespace = identifier.namespace();+ Preconditions.checkArgument(+ namespace != null && namespace.length() >= 2 && identifier.name() != null,+ "identifier must be metalake.catalog.schema…table: %s",+ identifier);+ String catalogName = namespace.level(1);+ Preconditions.checkArgument(+ catalogName != null && !catalogName.isBlank(),+ "catalog name must not be blank: %s",+ identifier);+ return catalogName;+ }++ /**+ * Spark {@code schema.table} (nested schemas joined with {@code .}) from a table {@link+ * NameIdentifier}.+ *+ * @param identifier metalake.catalog.schema…table+ * @return Spark table identifier+ */+ public static String sparkTableIdentifier(NameIdentifier identifier) {+ Namespace namespace = identifier.namespace();+ Preconditions.checkArgument(+ namespace != null && namespace.length() >= 2 && identifier.name() != null,+ "identifier must be metalake.catalog.schema…table: %s",+ identifier);+ StringBuilder sparkTable = new StringBuilder();+ for (int i = 2; i < namespace.length(); i++) {+ String level = namespace.level(i);+ Preconditions.checkArgument(+ level != null && !level.isBlank(), "blank namespace on %s", identifier);+ if (sparkTable.length() > 0) {+ sparkTable.append('.');+ }+ sparkTable.append(level);}- return new MaintenanceJobSpec(tasks, bags.updaterOptions, bags.sparkConf);+ Preconditions.checkArgument(+ !identifier.name().isBlank(), "table name must not be blank: %s", identifier);+ if (sparkTable.length() > 0) {+ sparkTable.append('.');+ }+ sparkTable.append(identifier.name());+ return sparkTable.toString();}/**- * Assembles the flat {@code runJob} map for one cron task: task {@code parameters} + envelope- * bags + TMS wire keys + one-element {@code tables} JSON.+ * Assembles the flat {@code runJob} map for one cron task: task {@code parameters} + shared+ * {@code updater_options}/{@code spark_conf} + TMS wire keys + one-element {@code tables} JSON.*- * @param spec enqueue spec+ * @param spec schedule spec* @param task task to submit* @return mutable jobConf (caller resolves secrets / injects {@code action_ids})*/@@ -145,7 +228,7 @@ public final class MaintenanceJobSpecFactory {task.getTableId());Map<String, String> jobConf = new LinkedHashMap<>(task.getParameters());- putSharedBags(jobConf, spec);+ putSharedJobConfFields(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));@@ -157,7 +240,7 @@ public final class MaintenanceJobSpecFactory {/*** Assembles one chained commit {@code runJob} map from all tasks (merged parameters + shared- * bags).+ * {@code updater_options}/{@code spark_conf}).** @param spec commit-chain spec* @return mutable jobConf@@ -180,7 +263,7 @@ public final class MaintenanceJobSpecFactory {mergeTaskParameters(jobConf, later);mergePolicyRulesByType(jobConf, later);}- putSharedBags(jobConf, spec);+ putSharedJobConfFields(jobConf, spec);List<String> types = new ArrayList<>(spec.getTasks().size());List<String> policyIds = new ArrayList<>(spec.getTasks().size());@@ -197,7 +280,15 @@ public final class MaintenanceJobSpecFactory {return jobConf;}- private static void putSharedBags(Map<String, String> jobConf, MaintenanceJobSpec spec) {+ private static String writeJson(Object value, String field) {+ try {+ return JsonUtils.anyFieldMapper().writeValueAsString(value);+ } catch (JsonProcessingException e) {+ throw new IllegalStateException("Failed to serialize " + field, e);+ }+ }++ private static void putSharedJobConfFields(Map<String, String> jobConf, MaintenanceJobSpec spec) {if (spec.getUpdaterOptions() != null && !spec.getUpdaterOptions().isBlank()) {jobConf.put(MaintenanceJobTemplates.UPDATER_OPTIONS_JOB_CONF_KEY, spec.getUpdaterOptions());}@@ -207,9 +298,10 @@ public final class MaintenanceJobSpecFactory {}/**- * Splits a {@link MaintenanceJobConfBuilder#build} map into envelope bags vs per-task parameters.+ * Splits a {@link MaintenanceJobConfBuilder#build} map into per-task {@code parameters} plus+ * shared {@code updater_options} / {@code spark_conf}.*/- public static EnqueueBags splitEnqueueBags(Map<String, String> built) {+ private static JobConfParts splitJobConfParts(Map<String, String> built) {Preconditions.checkNotNull(built, "built");Map<String, String> parameters = new LinkedHashMap<>();String updaterOptions = null;@@ -235,8 +327,51 @@ public final class MaintenanceJobSpecFactory {}Preconditions.checkArgument(updaterOptions != null && !updaterOptions.isBlank(),- "updater_options is required on enqueue jobConf");- return new EnqueueBags(parameters, updaterOptions, sparkConf);+ "updater_options is required on schedule jobConf");+ return new JobConfParts(parameters, updaterOptions, sparkConf);+ }++ /**+ * Merges nested {@code spark_conf} JSON into {@code into}: max resource-shaped values, otherwise+ * first-wins {@code putIfAbsent}. Used by commit-chain build and cron snapshot-expiry merge.+ *+ * @param into mutable flat spark conf map+ * @param fromJson candidate {@code spark_conf} JSON, or null/blank+ */+ public static void mergeSparkConfMaps(Map<String, String> into, @Nullable String fromJson) {+ if (fromJson == null || fromJson.trim().isEmpty()) {+ return;+ }+ Map<String, String> later = IcebergSparkConfigUtils.parseFlatJsonMap(fromJson, "spark_conf");+ mergeResourceKeys(into, later);+ for (Map.Entry<String, String> entry : later.entrySet()) {+ into.putIfAbsent(entry.getKey(), entry.getValue());+ }+ }++ /**+ * Merges several schedule-time {@code spark_conf} JSON strings. Resource-shaped keys (memory /+ * cores / instances) take the larger magnitude; other keys are first-wins.+ *+ * @param sparkConfJsons ordered {@code spark_conf} JSON strings (earlier wins non-resource keys)+ * @return merged JSON, or null when empty+ */+ @Nullable+ public static String mergeSparkConfJson(String... sparkConfJsons) {+ Map<String, String> merged = new LinkedHashMap<>();+ if (sparkConfJsons != null) {+ for (String sparkConfJson : sparkConfJsons) {+ mergeSparkConfMaps(merged, sparkConfJson);+ }+ }+ if (merged.isEmpty()) {+ return null;+ }+ try {+ return JsonUtils.anyFieldMapper().writeValueAsString(new TreeMap<>(merged));+ } catch (JsonProcessingException e) {+ throw new IllegalStateException("Failed to serialize spark_conf", e);+ }}/**@@ -288,7 +423,7 @@ public final class MaintenanceJobSpecFactory {}/**- * Union {@link MaintenanceJobTemplates#RULES_KEY} maps so each chain type keeps its enqueue-time+ * Union {@link MaintenanceJobTemplates#RULES_KEY} maps so each chain type keeps its schedule-time* rules.*/static void mergePolicyRulesByType(Map<String, String> into, Map<String, String> from) {@@ -354,8 +489,7 @@ public final class MaintenanceJobSpecFactory {* Parses Spark-style memory strings ({@code 512m}, {@code 1g}, {@code 2048}) into bytes for max* merge.*/- @VisibleForTesting- static Optional<Long> parseMemoryBytes(String value) {+ private static Optional<Long> parseMemoryBytes(String value) {if (value == null) {return Optional.empty();}@@ -417,26 +551,17 @@ public final class MaintenanceJobSpecFactory {}}- /** Visible for tests that assert resource merge. */- @VisibleForTesting- public static Map<String, String> newLinkedMap(String... kv) {- Map<String, String> map = new LinkedHashMap<>();- for (int i = 0; i + 1 < kv.length; i += 2) {- map.put(kv[i], kv[i + 1]);- }- 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;+ /**+ * Result of splitting {@link MaintenanceJobConfBuilder#build} into per-task parameters and shared+ * jobConf fields.+ */+ private static final class JobConfParts {+ private final Map<String, String> parameters;+ private final String updaterOptions;+ @Nullable private final String sparkConf;- EnqueueBags(Map<String, String> parameters, String updaterOptions, @Nullable String sparkConf) {+ private JobConfParts(+ 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/TableMaintenanceSchedulerPools.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/MaintenanceSchedulerPools.javasimilarity index 78%rename from plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/TableMaintenanceSchedulerPools.javarename to plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/MaintenanceSchedulerPools.javaindex 0468cdc09e..bafd110b2f 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/TableMaintenanceSchedulerPools.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/MaintenanceSchedulerPools.java@@ -34,19 +34,18 @@ import java.util.function.Supplier;import javax.sql.DataSource;import org.apache.gravitino.Config;import org.apache.gravitino.json.JsonUtils;+import org.apache.gravitino.maintenance.MaintenanceActionManager;+import org.apache.gravitino.maintenance.MaintenanceJobManager;import org.apache.gravitino.maintenance.TableMaintenanceConfig;-import org.apache.gravitino.maintenance.occupancy.OccupancyGate;-import org.apache.gravitino.maintenance.scheduler.job.commit.CommitOccupancyGate;+import org.apache.gravitino.maintenance.scheduler.job.MaintenanceJobConfBuilder;import org.apache.gravitino.maintenance.scheduler.job.commit.MaintenanceCommitSubmitPipeline;import org.apache.gravitino.maintenance.scheduler.job.cron.CronJobClient;-import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceJobConfBuilder;-import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceJobSubmitter;-import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceSparkSubmitPipeline;-import org.apache.gravitino.maintenance.scheduler.job.cron.PendingCronExpandOccupancyGate;-import org.apache.gravitino.maintenance.scheduler.policy.expand.ExpandOccupancyGate;-import org.apache.gravitino.maintenance.scheduler.policy.expand.NearestPolicyTableEnumerator;-import org.apache.gravitino.maintenance.scheduler.policy.expand.PolicyExpandPipeline;+import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceCronSubmitPipeline;+import org.apache.gravitino.maintenance.scheduler.policy.NearestPolicyTableEnumerator;+import org.apache.gravitino.maintenance.scheduler.policy.expand.MaintenanceExpandSubmitPipeline;+import org.apache.gravitino.maintenance.scheduler.policy.expand.PolicyExpandPlanner;import org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService;+import org.apache.gravitino.storage.relational.service.PolicyMetaService;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -58,12 +57,14 @@ import org.slf4j.LoggerFactory;* isolation; sharing one physical table across pools is unsupported (see design §5.2).** <p>The expand pool fans a due {@code policy-expand} lease into {@code cron-job} rows with an- * enqueue-time {@link MaintenanceJobSpec}. The cron and commit pools consume that spec, claim a+ * schedule-time {@link MaintenanceJobSpec}. The cron and commit pools consume that spec, claim a* soft slot, and submit Spark.+ *+ * <p>Dependencies are injected by the composition root ({@code TableMaintenanceRESTFeature}).*/-public class TableMaintenanceSchedulerPools implements AutoCloseable {+public class MaintenanceSchedulerPools implements AutoCloseable {- private static final Logger LOG = LoggerFactory.getLogger(TableMaintenanceSchedulerPools.class);+ private static final Logger LOG = LoggerFactory.getLogger(MaintenanceSchedulerPools.class);/** Expand-pool db-scheduler table. */public static final String EXPAND_TASKS_TABLE = "scheduled_expand_tasks";@@ -87,7 +88,7 @@ public class TableMaintenanceSchedulerPools implements AutoCloseable {* Expand pipeline supplier used by {@link #policyExpandTask()}. {@link #start} installs the* relational implementation.*/- private static final AtomicReference<Supplier<PolicyExpandPipeline>> EXPAND_PIPELINE =+ private static final AtomicReference<Supplier<MaintenanceExpandSubmitPipeline>> EXPAND_PIPELINE =new AtomicReference<>(() -> {throw new IllegalStateException("policy-expand pipeline is not configured");@@ -112,39 +113,55 @@ public class TableMaintenanceSchedulerPools implements AutoCloseable {* @param dataSource relational JDBC pool shared with the entity store* @param config maintenance scheduler settings* @param gravitinoConfig server config for {@code minIntervalMs} fallbacks and jobConf overlay+ * @param jobManager TMS Spark submit+bind manager+ * @param actionManager occupancy / cooldown gate+ * @param actionMetaService soft-slot claim store used by cron/commit submit pipelines+ * @param tableEnumerator nearest-policy table scan for expand+ * @param policyMetaService policy lookup used by expand planning*/- public void start(DataSource dataSource, TableMaintenanceConfig config, Config gravitinoConfig) {+ public void start(+ DataSource dataSource,+ TableMaintenanceConfig config,+ Config gravitinoConfig,+ MaintenanceJobManager jobManager,+ MaintenanceActionManager actionManager,+ TableMaintenanceActionMetaService actionMetaService,+ NearestPolicyTableEnumerator tableEnumerator,+ PolicyMetaService policyMetaService) {Preconditions.checkState(schedulers.isEmpty(), "scheduler pools already started");Preconditions.checkNotNull(dataSource, "dataSource must not be null");Preconditions.checkNotNull(gravitinoConfig, "gravitinoConfig must not be null");+ Preconditions.checkNotNull(jobManager, "jobManager must not be null");+ Preconditions.checkNotNull(actionManager, "actionManager must not be null");+ Preconditions.checkNotNull(actionMetaService, "actionMetaService must not be null");+ Preconditions.checkNotNull(tableEnumerator, "tableEnumerator must not be null");+ Preconditions.checkNotNull(policyMetaService, "policyMetaService must not be null");- OccupancyGate occupancyGate =- new OccupancyGate(TableMaintenanceActionMetaService.getInstance(), config.claimTimeoutMs());- ExpandOccupancyGate expandGate =- new PendingCronExpandOccupancyGate(occupancyGate::shouldSkip, dataSource);- PolicyExpandPipeline pipeline =- new PolicyExpandPipeline(- new NearestPolicyTableEnumerator(),- new CronJobClient(dataSource, gravitinoConfig),- expandGate,- gravitinoConfig,- config.expandEnqueueBatchSize());+ MaintenanceExpandSubmitPipeline pipeline =+ new MaintenanceExpandSubmitPipeline(+ new PolicyExpandPlanner(+ tableEnumerator,+ new CronJobClient(dataSource, gravitinoConfig),+ actionManager,+ gravitinoConfig,+ config.expandScheduleBatchSize(),+ policyMetaService));EXPAND_PIPELINE.set(() -> pipeline);- MaintenanceSparkSubmitPipeline cronSubmit =- new MaintenanceSparkSubmitPipeline(- occupancyGate::isInFlight,- TableMaintenanceActionMetaService.getInstance(),- MaintenanceJobSubmitter.fromEnv(),+ MaintenanceCronSubmitPipeline cronSubmit =+ new MaintenanceCronSubmitPipeline(+ actionManager,+ actionMetaService,+ jobManager,new MaintenanceJobConfBuilder(gravitinoConfig),config.claimTimeoutMs());CRON_SUBMIT.set(cronSubmit::submit);MaintenanceCommitSubmitPipeline commitSubmit =new MaintenanceCommitSubmitPipeline(- CommitOccupancyGate.of(occupancyGate),- TableMaintenanceActionMetaService.getInstance(),- MaintenanceJobSubmitter.fromEnv(),+ actionManager,+ actionMetaService,+ jobManager,new MaintenanceJobConfBuilder(gravitinoConfig),config.claimTimeoutMs());COMMIT_SUBMIT.set(commitSubmit::submit);@@ -242,7 +259,7 @@ public class TableMaintenanceSchedulerPools implements AutoCloseable {}/**- * Cron-pool task definition. Consumes the enqueue-time spec, claims a soft slot, submits Spark,+ * Cron-pool task definition. Consumes the schedule-time spec, claims a soft slot, submits Spark,* then removes the one-shot row so a later expand pick can schedule again.** @return the {@code cron-job} task@@ -264,7 +281,7 @@ public class TableMaintenanceSchedulerPools implements AutoCloseable {}/**- * Commit-pool task definition. Consumes the enqueue-time chain spec, claims a soft slot, submits+ * Commit-pool task definition. Consumes the schedule-time chain spec, claims a soft slot, submits* Spark, then removes the one-shot row.** @return the {@code commit-job} taskdiff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/MaintenanceAuthConsistency.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/MaintenanceAuthConsistency.javanew file mode 100644index 0000000000..f5bb4b4198--- /dev/null+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/MaintenanceAuthConsistency.java@@ -0,0 +1,199 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.maintenance.scheduler.job;++import com.google.common.base.Preconditions;+import java.util.ArrayList;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.Objects;+import java.util.Set;+import java.util.TreeMap;+import java.util.TreeSet;+import javax.annotation.Nullable;+import org.apache.gravitino.Config;+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.meta.PolicyEntity;+import org.apache.gravitino.policy.ExecutablePolicyContent;+import org.apache.gravitino.policy.PolicyContent;+import org.apache.gravitino.policy.PolicyExecutionSpec;++/**+ * Fail-closed checks that merged maintenance work agrees on effective Gravitino / IRC auth after+ * cluster overlay.+ *+ * <p>Used by commit-chain schedule (one Spark job, many policies) and snapshot-expiry merge (shared+ * {@code updater_options} / {@code spark_conf} on the survivor row). Cluster-static {@code+ * gravitinoAuth} / {@code ircAuth} normally make every policy identical; when overlays are empty,+ * disagreeing policy auth must not be merged silently.+ */+public final class MaintenanceAuthConsistency {++ private MaintenanceAuthConsistency() {}++ /**+ * @param policies commit-chain (or other) policy members+ * @param gravitinoConfig server config used for auth overlay+ * @throws IllegalArgumentException when effective auth options disagree+ */+ public static void requireSameAuth(List<PolicyEntity> policies, Config gravitinoConfig) {+ Preconditions.checkNotNull(policies, "policies");+ Preconditions.checkNotNull(gravitinoConfig, "gravitinoConfig");+ if (policies.size() <= 1) {+ return;+ }++ Set<String> clusterIrcKeys = MaintenanceAuthConfigs.loadIrcAuth(gravitinoConfig).keySet();+ Map<String, String> expectedGravitino = null;+ Map<String, String> expectedIrc = null;+ long expectedId = -1L;++ for (PolicyEntity policy : policies) {+ PolicyContent content = policy.content();+ PolicyExecutionSpec spec =+ content instanceof ExecutablePolicyContent+ ? ((ExecutablePolicyContent) content).executionSpec()+ : PolicyExecutionSpec.empty();+ Map<String, String> gravitinoAuth =+ gravitinoAuthKeys(+ MaintenanceAuthConfigs.overlayUpdaterOptions(gravitinoConfig, spec.updaterOptions()));+ Map<String, String> ircAuth =+ ircAuthKeys(+ MaintenanceAuthConfigs.overlayJobOptions(gravitinoConfig, spec.jobOptions()),+ clusterIrcKeys);++ if (expectedGravitino == null) {+ expectedGravitino = gravitinoAuth;+ expectedIrc = ircAuth;+ expectedId = policy.id();+ continue;+ }+ if (!expectedGravitino.equals(gravitinoAuth)) {+ throw new IllegalArgumentException(+ differingKeysMessage(+ "gravitinoAuth", expectedId, policy.id(), expectedGravitino, gravitinoAuth));+ }+ if (!Objects.equals(expectedIrc, ircAuth)) {+ throw new IllegalArgumentException(+ differingKeysMessage("ircAuth", expectedId, policy.id(), expectedIrc, ircAuth));+ }+ }+ }++ /**+ * Compares schedule snapshots. Spec maps are already cluster-overlaid at build time.+ *+ * @param gravitinoConfig server config (for cluster IRC key set)+ * @param left schedule snapshot+ * @param right schedule snapshot+ * @return true when both snapshots agree on effective gravitino/IRC auth+ */+ public static boolean hasSameAuth(+ Config gravitinoConfig, MaintenanceJobSpec left, MaintenanceJobSpec right) {+ Preconditions.checkNotNull(gravitinoConfig, "gravitinoConfig");+ Preconditions.checkNotNull(left, "left");+ Preconditions.checkNotNull(right, "right");+ Set<String> clusterIrcKeys = MaintenanceAuthConfigs.loadIrcAuth(gravitinoConfig).keySet();+ Map<String, String> leftUpdater =+ IcebergSparkConfigUtils.parseFlatJsonMap(+ left.getUpdaterOptions(), MaintenanceJobTemplates.UPDATER_OPTIONS_JOB_CONF_KEY);+ Map<String, String> rightUpdater =+ IcebergSparkConfigUtils.parseFlatJsonMap(+ right.getUpdaterOptions(), MaintenanceJobTemplates.UPDATER_OPTIONS_JOB_CONF_KEY);+ Map<String, String> leftSpark =+ IcebergSparkConfigUtils.parseFlatJsonMap(left.getSparkConf(), "spark_conf");+ Map<String, String> rightSpark =+ IcebergSparkConfigUtils.parseFlatJsonMap(right.getSparkConf(), "spark_conf");+ return gravitinoAuthKeys(leftUpdater).equals(gravitinoAuthKeys(rightUpdater))+ && ircAuthKeys(leftSpark, clusterIrcKeys).equals(ircAuthKeys(rightSpark, clusterIrcKeys));+ }++ /**+ * Ids and differing key names only. Auth values (passwords / tokens) must not land in server+ * logs.+ */+ private static String differingKeysMessage(+ String authName,+ long expectedId,+ long actualId,+ Map<String, String> expected,+ Map<String, String> actual) {+ Set<String> names = new TreeSet<>();+ names.addAll(expected.keySet());+ names.addAll(actual.keySet());+ List<String> differing = new ArrayList<>();+ for (String key : names) {+ if (!Objects.equals(expected.get(key), actual.get(key))) {+ differing.add(key);+ }+ }+ return String.format(+ "%s mismatch: policy %s vs policy %s; differing keys=%s",+ authName, expectedId, actualId, differing);+ }++ private static Map<String, String> gravitinoAuthKeys(+ @Nullable Map<String, String> updaterOptions) {+ Map<String, String> projected = new TreeMap<>();+ if (updaterOptions == null) {+ return projected;+ }+ for (String key : MaintenanceAuthConfigs.GRAVITINO_AUTH_UPDATER_OPTION_KEYS) {+ String value = updaterOptions.get(key);+ if (value != null) {+ projected.put(key, value);+ }+ }+ return projected;+ }++ /** Keeps cluster {@code ircAuth} keys and any other key that looks like catalog auth. */+ private static Map<String, String> ircAuthKeys(+ @Nullable Map<String, String> overlaidJobOptions, Set<String> clusterIrcKeys) {+ Map<String, String> projected = new TreeMap<>();+ if (overlaidJobOptions == null) {+ return projected;+ }+ for (Map.Entry<String, String> entry : overlaidJobOptions.entrySet()) {+ String key = entry.getKey();+ if (key == null || entry.getValue() == null) {+ continue;+ }+ if (clusterIrcKeys.contains(key) || isCatalogAuthKey(key)) {+ projected.put(key, entry.getValue());+ }+ }+ return projected;+ }++ private static boolean isCatalogAuthKey(String key) {+ String lower = key.toLowerCase(Locale.ROOT);+ return lower.contains(".auth.")+ || lower.startsWith("auth.")+ || lower.startsWith("rest.auth")+ || lower.contains("oauth")+ || lower.contains("keytab")+ || lower.contains("credential")+ || lower.endsWith(".token")+ || lower.endsWith(".password");+ }+}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/MaintenanceJobConfBuilder.javasimilarity index 95%rename from plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceJobConfBuilder.javarename to plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/MaintenanceJobConfBuilder.javaindex 1cfdfcd78f..7620f74c28 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/MaintenanceJobConfBuilder.java@@ -16,7 +16,7 @@* specific language governing permissions and limitations* under the License.*/-package org.apache.gravitino.maintenance.scheduler.job.cron;+package org.apache.gravitino.maintenance.scheduler.job;import com.fasterxml.jackson.core.JsonProcessingException;import com.google.common.base.Preconditions;@@ -55,7 +55,7 @@ import org.apache.gravitino.policy.PolicyExecutionSpec;* Dot-form Spark resource keys ({@code spark.executor.memory}) become the matching underscore* placeholders ({@code spark_executor_memory}) instead of catalog properties.*- * <p>{@link #build} is for enqueue {@code task_data}: cluster {@code gravitinoAuth} / {@code+ * <p>{@link #build} is for schedule {@code task_data}: cluster {@code gravitinoAuth} / {@code* ircAuth} are stored as conf <em>keys</em> (not secret values). Call {@link #resolveForSubmit}* immediately before {@code runJob} to expand those keys from the live {@code gravitino.conf}.*/@@ -126,12 +126,12 @@ public final class MaintenanceJobConfBuilder {}/**- * Enqueue-time jobConf for db-scheduler {@code task_data}. Cluster auth overlays store conf keys+ * Schedule-time jobConf for db-scheduler {@code task_data}. Cluster auth overlays store conf keys* (for example {@code gravitino.maintenance.gravitinoAuth.uri}), not secret values.** @param policy effective maintenance policy* @param catalogName Spark catalog alias for IRC property scoping- * @return mutable jobConf (split into envelope bags / task {@code parameters} by the factory)+ * @return mutable jobConf (split into shared fields / task {@code parameters} by the factory)*/public Map<String, String> build(PolicyEntity policy, String catalogName) {PolicyContent content = policy.content();@@ -196,7 +196,8 @@ public final class MaintenanceJobConfBuilder {/*** 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.+ * from nested {@code spark_conf}. Used when schedule {@code task_data} stores only the nested+ * {@code spark_conf} JSON.** @param jobConf mutable runJob map that already contains {@code spark_conf}* @param catalogName Spark catalog alias for IRC property scoping@@ -215,7 +216,7 @@ public final class MaintenanceJobConfBuilder {/*** 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+ * nested {@code spark_conf} so schedule {@code task_data} can keep only that JSON at the top* level.** @param jobConf mutable map from {@link #build}@@ -258,15 +259,15 @@ public final class MaintenanceJobConfBuilder {}/**- * Expands {@code gravitino.maintenance.*} conf-key references in an enqueue snapshot into live+ * Expands {@code gravitino.maintenance.*} conf-key references in a schedule snapshot into live* values from {@code gravitino.conf}. Call immediately before {@code runJob}.*- * @param enqueueJobConf jobConf from {@link #build} / {@code task_data}+ * @param scheduleJobConf jobConf from {@link #build} / {@code task_data}* @return new map with secrets and URIs resolved*/- public Map<String, String> resolveForSubmit(Map<String, String> enqueueJobConf) {+ public Map<String, String> resolveForSubmit(Map<String, String> scheduleJobConf) {Map<String, String> resolved = new LinkedHashMap<>();- for (Map.Entry<String, String> entry : enqueueJobConf.entrySet()) {+ for (Map.Entry<String, String> entry : scheduleJobConf.entrySet()) {String key = entry.getKey();String value = entry.getValue();if (key == null || value == null) {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/MaintenanceJobTemplates.javasimilarity index 88%rename from plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceJobTemplates.javarename to plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/MaintenanceJobTemplates.javaindex 94d51780eb..1c44f9cabb 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/MaintenanceJobTemplates.java@@ -16,17 +16,18 @@* specific language governing permissions and limitations* under the License.*/-package org.apache.gravitino.maintenance.scheduler.job.cron;+package org.apache.gravitino.maintenance.scheduler.job;import java.util.Optional;import org.apache.gravitino.job.JobTemplateProvider;import org.apache.gravitino.policy.Policy;/**- * Maps maintenance {@link Policy.BuiltInType} to the cron Spark job template and procedure kind.+ * Shared TMS job template name, jobConf keys, and {@link Policy.BuiltInType} → wire-type mapping+ * for cron and commit submits.*- * <p>Cron always submits {@link #ICEBERG_MAINTENANCE_TEMPLATE}; standalone {@code- * builtin-iceberg-*} templates remain for CLI / optimizer.+ * <p>TMS always submits {@link #ICEBERG_MAINTENANCE_TEMPLATE}; standalone {@code builtin-iceberg-*}+ * templates remain for CLI / optimizer.*/public final class MaintenanceJobTemplates {@@ -59,7 +60,7 @@ public final class MaintenanceJobTemplates {public static final String UPDATER_OPTIONS_JOB_CONF_KEY = "updater_options";/**- * JobConf key for enqueue-time policy {@code rules()}, JSON map of wire maintenance type → rules+ * JobConf key for schedule-time policy {@code rules()}, JSON map of wire maintenance type → rules* object. Consumed in-Spark for trigger-expr recommend (no Gravitino round-trip).*/public static final String RULES_KEY = "rules";diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CollectedCommitChain.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CollectedCommitChain.javadeleted file mode 100644index b37cf9717f..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CollectedCommitChain.java+++ /dev/null@@ -1,56 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.job.commit;--import com.google.common.base.Preconditions;-import java.util.List;-import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceTableRefs.ResolvedTableRef;--/**- * Result of {@link CommitChainCollector#collect(long)}: ordered onCommit members plus the resolved- * Spark table ref used to build the enqueue-time spec (single table-metadata lookup).- */-public final class CollectedCommitChain {-- private final List<CommitChainMember> members;- private final ResolvedTableRef tableRef;-- /**- * @param members ordered chain members (may be empty)- * @param tableRef resolved Spark table ref for the table id- */- public CollectedCommitChain(List<CommitChainMember> members, ResolvedTableRef tableRef) {- this.members = List.copyOf(Preconditions.checkNotNull(members, "members"));- this.tableRef = Preconditions.checkNotNull(tableRef, "tableRef");- }-- /**- * @return ordered onCommit members- */- public List<CommitChainMember> members() {- return members;- }-- /**- * @return resolved Spark table ref- */- public ResolvedTableRef tableRef() {- return tableRef;- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitAuthConsistency.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitAuthConsistency.javadeleted file mode 100644index 270a474148..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitAuthConsistency.java+++ /dev/null@@ -1,179 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.job.commit;--import com.google.common.base.Preconditions;-import java.util.ArrayList;-import java.util.List;-import java.util.Locale;-import java.util.Map;-import java.util.Objects;-import java.util.Set;-import java.util.TreeMap;-import java.util.TreeSet;-import javax.annotation.Nullable;-import org.apache.gravitino.Config;-import org.apache.gravitino.maintenance.policy.MaintenanceAuthConfigs;-import org.apache.gravitino.meta.PolicyEntity;-import org.apache.gravitino.policy.ExecutablePolicyContent;-import org.apache.gravitino.policy.PolicyContent;-import org.apache.gravitino.policy.PolicyExecutionSpec;--/**- * Fail-closed checks that commit-chain members agree on effective Gravitino / IRC auth after- * cluster overlay.- *- * <p>Cluster-static {@code gravitinoAuth} / {@code ircAuth} normally make every policy identical.- * When conf leaves those bags empty, policies may carry different auth-shaped options; a single- * chained Spark Job cannot pick one identity silently.- */-final class CommitAuthConsistency {-- private CommitAuthConsistency() {}-- /**- * @param chain filtered commit-chain members (same table)- * @param gravitinoConfig server config used for auth overlay- * @throws IllegalArgumentException when effective auth bags disagree- */- static void requireConsistent(List<CommitChainMember> chain, Config gravitinoConfig) {- Preconditions.checkNotNull(chain);- Preconditions.checkNotNull(gravitinoConfig);- if (chain.size() <= 1) {- return;- }-- Set<String> clusterIrcKeys = MaintenanceAuthConfigs.loadIrcAuth(gravitinoConfig).keySet();- Map<String, String> expectedGravitino = null;- Map<String, String> expectedIrc = null;- long expectedPolicyId = -1L;-- for (CommitChainMember member : chain) {- PolicyEntity policy = member.policy();- PolicyExecutionSpec spec = executionSpec(policy.content());- Map<String, String> gravitinoAuth =- projectGravitinoAuth(- MaintenanceAuthConfigs.overlayUpdaterOptions(gravitinoConfig, spec.updaterOptions()));- Map<String, String> ircAuth =- projectIrcAuth(- MaintenanceAuthConfigs.overlayJobOptions(gravitinoConfig, spec.jobOptions()),- clusterIrcKeys);-- if (expectedGravitino == null) {- expectedGravitino = gravitinoAuth;- expectedIrc = ircAuth;- expectedPolicyId = policy.id();- continue;- }- if (!expectedGravitino.equals(gravitinoAuth)) {- throw new IllegalArgumentException(- mismatchMessage(- "gravitinoAuth", expectedPolicyId, policy.id(), expectedGravitino, gravitinoAuth));- }- if (!Objects.equals(expectedIrc, ircAuth)) {- throw new IllegalArgumentException(- mismatchMessage("ircAuth", expectedPolicyId, policy.id(), expectedIrc, ircAuth));- }- }- }-- /**- * Builds a mismatch message with policy ids and differing key names only — never auth values- * (passwords / tokens must not land in server logs).- */- static String mismatchMessage(- String bagName,- long expectedPolicyId,- long actualPolicyId,- Map<String, String> expected,- Map<String, String> actual) {- return String.format(- "commit-chain %s mismatch: policy %s vs policy %s; differing keys=%s",- bagName, expectedPolicyId, actualPolicyId, differingKeys(expected, actual));- }-- /** Key names that are missing, extra, or present with unequal values. */- static List<String> differingKeys(Map<String, String> left, Map<String, String> right) {- Set<String> names = new TreeSet<>();- names.addAll(left.keySet());- names.addAll(right.keySet());- List<String> differing = new ArrayList<>();- for (String key : names) {- if (!Objects.equals(left.get(key), right.get(key))) {- differing.add(key);- }- }- return differing;- }-- static Map<String, String> projectGravitinoAuth(@Nullable Map<String, String> updaterOptions) {- Map<String, String> projected = new TreeMap<>();- if (updaterOptions == null) {- return projected;- }- for (String key : MaintenanceAuthConfigs.GRAVITINO_AUTH_UPDATER_OPTION_KEYS) {- String value = updaterOptions.get(key);- if (value != null) {- projected.put(key, value);- }- }- return projected;- }-- /**- * Projects IRC auth-shaped keys: every cluster {@code ircAuth} key present after overlay, plus- * any remaining jobOption key that looks like catalog auth (so policy-only auth still conflicts).- */- static Map<String, String> projectIrcAuth(- @Nullable Map<String, String> overlaidJobOptions, Set<String> clusterIrcKeys) {- Map<String, String> projected = new TreeMap<>();- if (overlaidJobOptions == null) {- return projected;- }- for (Map.Entry<String, String> entry : overlaidJobOptions.entrySet()) {- String key = entry.getKey();- if (key == null || entry.getValue() == null) {- continue;- }- if (clusterIrcKeys.contains(key) || isIrcAuthShaped(key)) {- projected.put(key, entry.getValue());- }- }- return projected;- }-- static boolean isIrcAuthShaped(String key) {- String lower = key.toLowerCase(Locale.ROOT);- return lower.contains(".auth.")- || lower.startsWith("auth.")- || lower.startsWith("rest.auth")- || lower.contains("oauth")- || lower.contains("keytab")- || lower.contains("credential")- || lower.endsWith(".token")- || lower.endsWith(".password");- }-- private static PolicyExecutionSpec executionSpec(@Nullable PolicyContent content) {- if (content instanceof ExecutablePolicyContent) {- return ((ExecutablePolicyContent) content).executionSpec();- }- return PolicyExecutionSpec.empty();- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitChainCollector.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitChainCollector.javadeleted file mode 100644index 62a96f17af..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitChainCollector.java+++ /dev/null@@ -1,195 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.job.commit;--import com.google.common.base.Preconditions;-import java.util.ArrayList;-import java.util.Arrays;-import java.util.List;-import java.util.Optional;-import java.util.function.Function;-import java.util.function.Supplier;-import javax.annotation.Nullable;-import org.apache.gravitino.EntityStore;-import org.apache.gravitino.GravitinoEnv;-import org.apache.gravitino.MetadataObject;-import org.apache.gravitino.MetadataObjects;-import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceJobTemplates;-import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceTableRefs;-import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceTableRefs.ResolvedTableRef;-import org.apache.gravitino.maintenance.scheduler.policy.expand.NearestMaintenancePolicyResolver;-import org.apache.gravitino.maintenance.scheduler.policy.expand.NearestMaintenancePolicyResolver.Decision;-import org.apache.gravitino.maintenance.storage.MetalakeNames;-import org.apache.gravitino.meta.PolicyEntity;-import org.apache.gravitino.policy.ExecutablePolicyContent;-import org.apache.gravitino.policy.Policy;-import org.apache.gravitino.policy.PolicyContent;-import org.apache.gravitino.storage.relational.service.PolicyMetaService;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--/**- * Builds the onCommit maintenance chain for a table: compaction → manifest-rewrite →- * snapshot-expiry (§5.2.3). Orphan cleanup is timeTrigger-only and never included.- */-public final class CommitChainCollector {-- private static final Logger LOG = LoggerFactory.getLogger(CommitChainCollector.class);-- /** Fixed commit-chain order. */- public static final List<Policy.BuiltInType> CHAIN_ORDER =- List.of(- Policy.BuiltInType.ICEBERG_COMPACTION,- Policy.BuiltInType.ICEBERG_REWRITE_MANIFESTS,- Policy.BuiltInType.ICEBERG_SNAPSHOT_EXPIRATION);-- private final Function<Long, Optional<PolicyEntity>> policyLoader;- private final Supplier<EntityStore> entityStoreSupplier;- private final Function<Long, Optional<TableContext>> tableContextResolver;-- /**- * Production collector using {@link PolicyMetaService}, {@link GravitinoEnv#entityStore()}, and- * relational table refs.- */- public CommitChainCollector() {- this(- id -> Optional.ofNullable(PolicyMetaService.getInstance().getPolicyById(id)),- () -> GravitinoEnv.getInstance().entityStore(),- CommitChainCollector::resolveTableContext);- }-- /**- * Visible for tests.- *- * @param policyLoader loads policies by id- * @param entityStoreSupplier entity store supplier- * @param tableContextResolver resolves metalake + metadata object for a table id- */- CommitChainCollector(- Function<Long, Optional<PolicyEntity>> policyLoader,- Supplier<EntityStore> entityStoreSupplier,- Function<Long, Optional<TableContext>> tableContextResolver) {- this.policyLoader = Preconditions.checkNotNull(policyLoader);- this.entityStoreSupplier = Preconditions.checkNotNull(entityStoreSupplier);- this.tableContextResolver = Preconditions.checkNotNull(tableContextResolver);- }-- /**- * Collects the onCommit chain and the Spark table ref in one metadata resolution pass.- *- * @param tableId table entity id- * @return collected chain (members may be empty) when the table resolves; empty when metadata is- * unknown- */- public Optional<CollectedCommitChain> collect(long tableId) {- Optional<TableContext> ctx = tableContextResolver.apply(tableId);- if (ctx.isEmpty()) {- LOG.info("Skipping commit chain for table {}: could not resolve table metadata", tableId);- return Optional.empty();- }- TableContext table = ctx.get();- NearestMaintenancePolicyResolver nearest =- new NearestMaintenancePolicyResolver(entityStoreSupplier.get());- List<CommitChainMember> chain = new ArrayList<>();- for (Policy.BuiltInType type : CHAIN_ORDER) {- Decision decision = nearest.resolve(table.metalake(), table.tableObject(), type);- if (decision.kind() == Decision.Kind.CONFLICT) {- // Match expand fail-closed: ambiguous same-level policies skip the whole table.- LOG.error(- "Skip commit-job enqueue for table {}: ambiguous {} policies {} on nearest level",- tableId,- type,- decision.conflictingPolicyIds());- return Optional.empty();- }- Optional<Long> winnerId = decision.winnerPolicyId();- if (winnerId.isEmpty()) {- continue;- }- Optional<PolicyEntity> loaded = policyLoader.apply(winnerId.get());- if (loaded.isEmpty()) {- continue;- }- PolicyEntity policy = loaded.get();- if (!policy.enabled() || !Boolean.TRUE.equals(commitTrigger(policy.content()))) {- continue;- }- Optional<String> wire = MaintenanceJobTemplates.maintenanceType(type);- if (wire.isEmpty()) {- continue;- }- chain.add(new CommitChainMember(type, policy, wire.get()));- }- return Optional.of(new CollectedCommitChain(chain, table.tableRef()));- }-- @Nullable- private static Boolean commitTrigger(@Nullable PolicyContent content) {- if (!(content instanceof ExecutablePolicyContent)) {- return null;- }- return ((ExecutablePolicyContent) content).executionSpec().commitTrigger();- }-- private static Optional<TableContext> resolveTableContext(long tableId) {- String metalake = MetalakeNames.forTableId(tableId);- if (metalake == null || metalake.isEmpty()) {- return Optional.empty();- }- List<ResolvedTableRef> refs = MaintenanceTableRefs.resolve(List.of(tableId));- if (refs.isEmpty()) {- return Optional.empty();- }- ResolvedTableRef ref = refs.get(0);- String[] parts = ref.tableIdentifier().split("\\.");- if (parts.length < 2) {- return Optional.empty();- }- List<String> names = new ArrayList<>();- names.add(ref.catalogName());- names.addAll(Arrays.asList(parts));- MetadataObject tableObject = MetadataObjects.of(names, MetadataObject.Type.TABLE);- return Optional.of(new TableContext(metalake, tableObject, ref));- }-- /** Metalake + metadata object + Spark ref for nearest-policy walks and spec build. */- static final class TableContext {- private final String metalake;- private final MetadataObject tableObject;- private final ResolvedTableRef tableRef;-- TableContext(String metalake, MetadataObject tableObject, ResolvedTableRef tableRef) {- this.metalake = metalake;- this.tableObject = tableObject;- this.tableRef = tableRef;- }-- String metalake() {- return metalake;- }-- MetadataObject tableObject() {- return tableObject;- }-- ResolvedTableRef tableRef() {- return tableRef;- }- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitChainMember.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitChainMember.javadeleted file mode 100644index 414ad73c3e..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitChainMember.java+++ /dev/null@@ -1,64 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.job.commit;--import com.google.common.base.Preconditions;-import org.apache.gravitino.meta.PolicyEntity;-import org.apache.gravitino.policy.Policy;--/** One onCommit maintenance type in the commit-job chain (§5.2.3). */-public final class CommitChainMember {-- private final Policy.BuiltInType policyType;- private final PolicyEntity policy;- private final String maintenanceType;-- /**- * @param policyType built-in maintenance type- * @param policy nearest enabled policy with {@code commitTrigger=true}- * @param maintenanceType Spark wire name ({@code rewrite_data_files}, …)- */- public CommitChainMember(- Policy.BuiltInType policyType, PolicyEntity policy, String maintenanceType) {- this.policyType = Preconditions.checkNotNull(policyType);- this.policy = Preconditions.checkNotNull(policy);- this.maintenanceType = Preconditions.checkNotNull(maintenanceType);- }-- /**- * @return built-in policy type- */- public Policy.BuiltInType policyType() {- return policyType;- }-- /**- * @return policy entity- */- public PolicyEntity policy() {- return policy;- }-- /**- * @return Spark {@code maintenance_types} wire value- */- public String maintenanceType() {- return maintenanceType;- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobClient.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobClient.javaindex c05c532def..496dcd161f 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobClient.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobClient.java@@ -21,194 +21,79 @@ package org.apache.gravitino.maintenance.scheduler.job.commit;import com.github.kagkarlsson.scheduler.SchedulerClient;import com.github.kagkarlsson.scheduler.serializer.JacksonSerializer;import com.github.kagkarlsson.scheduler.task.TaskInstance;-import com.github.kagkarlsson.scheduler.task.TaskInstanceId;-import com.google.common.annotations.VisibleForTesting;import com.google.common.base.Preconditions;import java.time.Instant;-import java.util.ArrayList;-import java.util.List;import java.util.Optional;-import java.util.function.Function;-import javax.annotation.Nullable;import javax.sql.DataSource;-import org.apache.gravitino.Config;+import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.json.JsonUtils;-import org.apache.gravitino.maintenance.TableMaintenanceConfig;-import org.apache.gravitino.maintenance.occupancy.OccupancyGate;-import org.apache.gravitino.maintenance.policy.MaintenanceMinIntervalConfigs;import org.apache.gravitino.maintenance.scheduler.AutocommitDataSources;import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;+import org.apache.gravitino.maintenance.scheduler.MaintenanceSchedulerPools;import org.apache.gravitino.maintenance.scheduler.MaintenanceTaskIds;-import org.apache.gravitino.maintenance.scheduler.TableMaintenanceSchedulerPools;-import org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService;-import org.apache.gravitino.policy.ExecutablePolicyContent;-import org.apache.gravitino.policy.PolicyContent;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/**- * Enqueues one-shot {@code commit-job} rows through a db-scheduler {@link SchedulerClient} on the- * entity-store DataSource (§5.2.3).+ * Submits one-shot {@code commit-job} rows to db-scheduler. Planning is done by {@link+ * CommitJobPlanner}.*- * <p>Instance id is {@code {table_id}}; bursts of commits on the same table coalesce via {@code- * scheduleIfNotExists}. Enqueue collects the onCommit chain, drops members still inside {@code- * minIntervalMs}, checks auth consistency, builds a {@link MaintenanceJobSpec}, and inserts only- * when the spec is non-empty. Coalesce leaves an existing row's {@code task_data} untouched.+ * <p>One instance is held by {@code PostCommitMaintenanceListener} for the listener lifetime.*/public class CommitJobClient {private static final Logger LOG = LoggerFactory.getLogger(CommitJobClient.class);- private final DataSource dataSource;- private final Config gravitinoConfig;- private final Function<Long, Optional<CollectedCommitChain>> chainCollector;- private final CommitOccupancyGate occupancyGate;- private final CommitJobSpecFactory specFactory;+ private final SchedulerClient scheduler;+ private final CommitJobPlanner planner;/*** @param dataSource relational JDBC pool shared with the entity store- * @param gravitinoConfig server config for auth overlay and minInterval fallbacks+ * @param planner commit-job planner wired by the composition root*/- public CommitJobClient(DataSource dataSource, Config gravitinoConfig) {- this(- dataSource,- gravitinoConfig,- new CommitChainCollector()::collect,- CommitOccupancyGate.of(- new OccupancyGate(- TableMaintenanceActionMetaService.getInstance(),- TableMaintenanceConfig.from(gravitinoConfig).claimTimeoutMs())));+ public CommitJobClient(DataSource dataSource, CommitJobPlanner planner) {+ Preconditions.checkNotNull(dataSource);+ this.planner = Preconditions.checkNotNull(planner);+ this.scheduler = schedulerClient(dataSource);}/**- * Visible for tests.+ * Plans then schedules a {@code commit-job} for the table in {@code identifier}.*- * @param dataSource JDBC pool- * @param gravitinoConfig server config- * @param chainCollector returns the collected onCommit chain for a table id- * @param occupancyGate cooldown / in-flight checks for enqueue gating+ * @param identifier {@code metalake.catalog.schema.table} from the commit event*/- @VisibleForTesting- public CommitJobClient(- DataSource dataSource,- Config gravitinoConfig,- Function<Long, Optional<CollectedCommitChain>> chainCollector,- CommitOccupancyGate occupancyGate) {- this.dataSource = Preconditions.checkNotNull(dataSource);- this.gravitinoConfig = Preconditions.checkNotNull(gravitinoConfig);- this.chainCollector = Preconditions.checkNotNull(chainCollector);- this.occupancyGate = Preconditions.checkNotNull(occupancyGate);- this.specFactory = new CommitJobSpecFactory(gravitinoConfig);- }-- /**- * Builds an enqueue-time spec (chain + jobConf) and schedules a {@code commit-job} when one is- * not already queued and the spec is non-empty.- *- * @param tableId table entity id- * @return insert / coalesce / skip outcome- */- public CommitJobEnqueueResult enqueueNow(long tableId) {- Preconditions.checkArgument(tableId > 0, "tableId must be positive");- SchedulerClient client = schedulerClient(dataSource);- String id = MaintenanceTaskIds.forCommitTable(tableId);- // Coalesce without rebuilding task_data: keep the first enqueue-time spec.- if (client- .getScheduledExecution(TaskInstanceId.of(TableMaintenanceSchedulerPools.COMMIT_JOB, id))- .isPresent()) {- return CommitJobEnqueueResult.ALREADY_QUEUED;+ public void scheduleNow(NameIdentifier identifier) {+ if (identifier == null) {+ return;}- Optional<MaintenanceJobSpec> spec = buildSpec(tableId);+ Optional<MaintenanceJobSpec> spec = planner.plan(scheduler, identifier);if (spec.isEmpty()) {- return CommitJobEnqueueResult.SKIPPED;+ return;+ }+ long tableId = spec.get().tableIds().get(0);+ String id = MaintenanceTaskIds.forCommitTable(tableId);+ try {+ if (scheduler.scheduleIfNotExists(+ new TaskInstance<>(MaintenanceSchedulerPools.COMMIT_JOB, id, spec.get()),+ Instant.now())) {+ LOG.info("Scheduled commit-job for table {} ({})", tableId, identifier);+ } else {+ LOG.debug("commit-job already scheduled for table {} ({})", tableId, identifier);+ }+ } catch (RuntimeException e) {+ LOG.warn("Failed to schedule commit-job for IRC update {}: {}", identifier, e.toString());}- boolean inserted =- client.scheduleIfNotExists(- new TaskInstance<>(TableMaintenanceSchedulerPools.COMMIT_JOB, id, spec.get()),- Instant.now());- return inserted ? CommitJobEnqueueResult.INSERTED : CommitJobEnqueueResult.ALREADY_QUEUED;}/**- * Builds a db-scheduler {@link SchedulerClient} that can commit against the entity-store- * DataSource.- ** @param dataSource entity-store pool- * @return client bound to {@link TableMaintenanceSchedulerPools#COMMIT_TASKS_TABLE}+ * @return client bound to the commit-job table*/- @VisibleForTestingpublic static SchedulerClient schedulerClient(DataSource dataSource) {return SchedulerClient.Builder.create(- AutocommitDataSources.wrap(dataSource), TableMaintenanceSchedulerPools.commitJobTask())+ AutocommitDataSources.wrap(dataSource), MaintenanceSchedulerPools.commitJobTask()).serializer(new JacksonSerializer(JsonUtils.anyFieldMapper()))- .tableName(TableMaintenanceSchedulerPools.COMMIT_TASKS_TABLE)+ .tableName(MaintenanceSchedulerPools.COMMIT_TASKS_TABLE).build();}-- private Optional<MaintenanceJobSpec> buildSpec(long tableId) {- Optional<CollectedCommitChain> collected = chainCollector.apply(tableId);- if (collected.isEmpty()) {- return Optional.empty();- }- List<CommitChainMember> members = collected.get().members();- if (members.isEmpty()) {- LOG.debug("Skipping commit-job enqueue for table {}: empty onCommit chain", tableId);- return Optional.empty();- }-- long nowMs = System.currentTimeMillis();- List<CommitChainMember> chain = filterByMinInterval(tableId, members, nowMs);- if (chain.isEmpty()) {- LOG.debug(- "Skipping commit-job enqueue for table {}: all onCommit types within minIntervalMs",- tableId);- return Optional.empty();- }-- try {- CommitAuthConsistency.requireConsistent(chain, gravitinoConfig);- } catch (IllegalArgumentException e) {- LOG.error("Skipping commit-job enqueue for table {}: {}", tableId, e.getMessage());- return Optional.empty();- }-- try {- return Optional.of(specFactory.forCommit(chain, collected.get().tableRef()));- } catch (RuntimeException e) {- LOG.warn(- "Skipping commit-job enqueue for table {}: failed to build jobConf spec: {}",- tableId,- e.toString());- return Optional.empty();- }- }-- private List<CommitChainMember> filterByMinInterval(- long tableId, List<CommitChainMember> collected, long nowMs) {- List<CommitChainMember> due = new ArrayList<>();- for (CommitChainMember member : collected) {- long minIntervalMs =- MaintenanceMinIntervalConfigs.resolve(- gravitinoConfig, member.policyType(), policyMinIntervalMs(member.policy().content()));- if (occupancyGate.withinMinInterval(tableId, member.policy().id(), minIntervalMs, nowMs)) {- LOG.debug(- "Dropping type {} policy {} from commit-job enqueue for table {} (within minIntervalMs={})",- member.policyType(),- member.policy().id(),- tableId,- minIntervalMs);- continue;- }- due.add(member);- }- return due;- }-- @Nullable- private static Long policyMinIntervalMs(@Nullable PolicyContent content) {- if (!(content instanceof ExecutablePolicyContent)) {- return null;- }- return ((ExecutablePolicyContent) content).executionSpec().minIntervalMs();- }}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobEnqueueResult.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobEnqueueResult.javadeleted file mode 100644index 71ad00a569..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobEnqueueResult.java+++ /dev/null@@ -1,40 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.job.commit;--/**- * Outcome of {@link CommitJobClient#enqueueNow(long)}.- *- * <p>Distinguishes coalesce ({@link #ALREADY_QUEUED}) from enqueue gate skips ({@link #SKIPPED}) so- * callers do not log "already queued" when no spec was written.- */-public enum CommitJobEnqueueResult {-- /** A new {@code commit-job} row was inserted with a MaintenanceJobSpec. */- INSERTED,-- /** A {@code commit-job} row already exists for the table (coalesced; {@code task_data} kept). */- ALREADY_QUEUED,-- /**- * Nothing written: empty / cooled-down chain, auth failure, unresolved table, or jobConf build- * failure.- */- SKIPPED-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobPlanner.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobPlanner.javanew file mode 100644index 0000000000..94c2a5929b--- /dev/null+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobPlanner.java@@ -0,0 +1,212 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.maintenance.scheduler.job.commit;++import com.github.kagkarlsson.scheduler.SchedulerClient;+import com.github.kagkarlsson.scheduler.task.TaskInstanceId;+import com.google.common.base.Preconditions;+import java.util.ArrayList;+import java.util.List;+import java.util.Optional;+import org.apache.gravitino.Config;+import org.apache.gravitino.Entity;+import org.apache.gravitino.EntityStore;+import org.apache.gravitino.MetadataObject;+import org.apache.gravitino.NameIdentifier;+import org.apache.gravitino.Namespace;+import org.apache.gravitino.exceptions.NoSuchEntityException;+import org.apache.gravitino.maintenance.MaintenanceActionManager;+import org.apache.gravitino.maintenance.model.TableCandidate;+import org.apache.gravitino.maintenance.policy.MaintenanceMinIntervalConfigs;+import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;+import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpecFactory;+import org.apache.gravitino.maintenance.scheduler.MaintenanceSchedulerPools;+import org.apache.gravitino.maintenance.scheduler.MaintenanceTaskIds;+import org.apache.gravitino.maintenance.scheduler.job.MaintenanceAuthConsistency;+import org.apache.gravitino.maintenance.scheduler.job.MaintenanceJobTemplates;+import org.apache.gravitino.maintenance.scheduler.policy.NearestMaintenancePolicyResolver;+import org.apache.gravitino.meta.PolicyEntity;+import org.apache.gravitino.meta.TableEntity;+import org.apache.gravitino.policy.ExecutablePolicyContent;+import org.apache.gravitino.policy.Policy;+import org.apache.gravitino.policy.PolicyContent;+import org.apache.gravitino.storage.relational.service.PolicyMetaService;+import org.apache.gravitino.storage.relational.service.TableMetaService;+import org.apache.gravitino.utils.NameIdentifierUtil;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * Plans a {@code commit-job}: resolve the table, skip if already queued, collect the onCommit+ * chain, drop cool-down members, check auth, and build {@link MaintenanceJobSpec}.+ */+public class CommitJobPlanner {++ private static final Logger LOG = LoggerFactory.getLogger(CommitJobPlanner.class);++ private static final List<Policy.BuiltInType> CHAIN_ORDER =+ List.of(+ Policy.BuiltInType.ICEBERG_COMPACTION,+ Policy.BuiltInType.ICEBERG_REWRITE_MANIFESTS,+ Policy.BuiltInType.ICEBERG_SNAPSHOT_EXPIRATION);++ private final Config gravitinoConfig;+ private final MaintenanceActionManager actionManager;+ private final MaintenanceJobSpecFactory specFactory;+ private final TableMetaService tableMetaService;+ private final PolicyMetaService policyMetaService;+ private final EntityStore entityStore;++ /**+ * @param gravitinoConfig server config for auth overlay and minInterval fallbacks+ * @param actionManager occupancy / cooldown gate+ * @param tableMetaService table lookup+ * @param policyMetaService policy lookup+ * @param entityStore store used by nearest-policy resolution+ */+ public CommitJobPlanner(+ Config gravitinoConfig,+ MaintenanceActionManager actionManager,+ TableMetaService tableMetaService,+ PolicyMetaService policyMetaService,+ EntityStore entityStore) {+ this.gravitinoConfig = Preconditions.checkNotNull(gravitinoConfig);+ this.actionManager = Preconditions.checkNotNull(actionManager);+ this.specFactory = new MaintenanceJobSpecFactory(gravitinoConfig);+ this.tableMetaService = Preconditions.checkNotNull(tableMetaService);+ this.policyMetaService = Preconditions.checkNotNull(policyMetaService);+ this.entityStore = Preconditions.checkNotNull(entityStore);+ }++ /**+ * @param client commit-job scheduler client (used to see if a row already exists)+ * @param identifier {@code metalake.catalog.schema.table} from the commit event+ * @return spec to schedule, or empty when there is nothing to schedule+ */+ public Optional<MaintenanceJobSpec> plan(SchedulerClient client, NameIdentifier identifier) {+ if (identifier == null) {+ return Optional.empty();+ }+ try {+ TableEntity table = tableMetaService.getTableByIdentifier(identifier);+ long tableId = table.id();+ String instanceId = MaintenanceTaskIds.forCommitTable(tableId);+ if (client+ .getScheduledExecution(+ TaskInstanceId.of(MaintenanceSchedulerPools.COMMIT_JOB, instanceId))+ .isPresent()) {+ LOG.debug("commit-job already queued for table {} ({})", tableId, identifier);+ return Optional.empty();+ }++ Namespace namespace = identifier.namespace();+ if (namespace == null || namespace.length() < 3 || identifier.name() == null) {+ LOG.info("Skipping commit-job for table {}: incomplete identifier {}", tableId, identifier);+ return Optional.empty();+ }+ for (int i = 0; i < namespace.length(); i++) {+ if (namespace.level(i) == null || namespace.level(i).isBlank()) {+ LOG.info("Skipping commit-job for table {}: blank namespace on {}", tableId, identifier);+ return Optional.empty();+ }+ }++ MetadataObject tableObject =+ NameIdentifierUtil.toMetadataObject(identifier, Entity.EntityType.TABLE);+ String metalake = namespace.level(0);++ NearestMaintenancePolicyResolver nearest = new NearestMaintenancePolicyResolver(entityStore);+ List<PolicyEntity> chain = new ArrayList<>();+ for (Policy.BuiltInType type : CHAIN_ORDER) {+ Optional<Long> winnerId = nearest.resolveWinnerId(metalake, tableObject, type);+ if (winnerId.isEmpty()) {+ continue;+ }+ PolicyEntity policy = policyMetaService.getPolicyById(winnerId.get());+ if (policy == null || !policy.enabled()) {+ continue;+ }+ PolicyContent content = policy.content();+ Boolean commitTrigger =+ content instanceof ExecutablePolicyContent+ ? ((ExecutablePolicyContent) content).executionSpec().commitTrigger()+ : null;+ if (!Boolean.TRUE.equals(commitTrigger)) {+ continue;+ }+ if (MaintenanceJobTemplates.maintenanceType(policy.policyType()).isEmpty()) {+ continue;+ }+ chain.add(policy);+ }+ if (chain.isEmpty()) {+ LOG.debug("Skipping commit-job schedule for table {}: empty onCommit chain", tableId);+ return Optional.empty();+ }++ long nowMs = System.currentTimeMillis();+ List<PolicyEntity> due = new ArrayList<>();+ for (PolicyEntity policy : chain) {+ Long contentMinInterval = null;+ if (policy.content() instanceof ExecutablePolicyContent) {+ contentMinInterval =+ ((ExecutablePolicyContent) policy.content()).executionSpec().minIntervalMs();+ }+ long minIntervalMs =+ MaintenanceMinIntervalConfigs.resolve(+ gravitinoConfig, policy.policyType(), contentMinInterval);+ if (actionManager.isCoolingDown(tableId, policy.id(), minIntervalMs, nowMs)) {+ LOG.debug(+ "Dropping type {} policy {} from commit-job schedule for table {} (within minIntervalMs={})",+ policy.policyType(),+ policy.id(),+ tableId,+ minIntervalMs);+ continue;+ }+ due.add(policy);+ }+ if (due.isEmpty()) {+ LOG.debug(+ "Skipping commit-job schedule for table {}: all onCommit types within minIntervalMs",+ tableId);+ return Optional.empty();+ }++ MaintenanceAuthConsistency.requireSameAuth(due, gravitinoConfig);+ return Optional.of(+ specFactory.forCommit(+ List.of(+ new TableCandidate(+ tableId,+ MaintenanceJobSpecFactory.catalogName(identifier),+ MaintenanceJobSpecFactory.sparkTableIdentifier(identifier),+ due))));+ } catch (NoSuchEntityException e) {+ LOG.debug("No Gravitino table for IRC update {}: {}", identifier, e.getMessage());+ return Optional.empty();+ } catch (IllegalArgumentException e) {+ LOG.error("Skipping commit-job schedule for {}: {}", identifier, e.getMessage());+ return Optional.empty();+ } catch (RuntimeException e) {+ LOG.warn("Failed to plan commit-job for IRC update {}: {}", identifier, e.toString());+ return Optional.empty();+ }+ }+}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.javadeleted file mode 100644index 4046f2aea5..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobSpecFactory.java+++ /dev/null@@ -1,128 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.job.commit;--import com.fasterxml.jackson.core.JsonProcessingException;-import com.google.common.base.Preconditions;-import java.util.ArrayList;-import java.util.LinkedHashMap;-import java.util.List;-import java.util.Map;-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.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.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>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 final MaintenanceJobConfBuilder jobConfBuilder;-- /**- * @param gravitinoConfig server config for auth overlay and gravitino URI- */- CommitJobSpecFactory(Config gravitinoConfig) {- this.jobConfBuilder =- new MaintenanceJobConfBuilder(Preconditions.checkNotNull(gravitinoConfig));- }-- /**- * Commit-chain spec for one table. Caller must already have filtered cooldown and verified auth- * consistency.- *- * @param chain non-empty onCommit members in order- * @param ref resolved Spark table ref- * @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");-- 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"));-- 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);- }- 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} maps into {@code into}: max resource-shaped values, otherwise- * first-wins {@code putIfAbsent}.- */- static void mergeSparkConfMaps(Map<String, String> into, @Nullable String fromJson) {- if (fromJson == null || fromJson.trim().isEmpty()) {- return;- }- Map<String, String> later = IcebergSparkConfigUtils.parseFlatJsonMap(fromJson, "spark_conf");- MaintenanceJobSpecFactory.mergeResourceKeys(into, later);- for (Map.Entry<String, String> entry : later.entrySet()) {- into.putIfAbsent(entry.getKey(), entry.getValue());- }- }-- private static String writeJson(Object value, String field) {- try {- return JsonUtils.anyFieldMapper().writeValueAsString(value);- } catch (JsonProcessingException e) {- throw new IllegalStateException("Failed to serialize " + field, 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/CommitOccupancyGate.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitOccupancyGate.javadeleted file mode 100644index 38bdb04f81..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitOccupancyGate.java+++ /dev/null@@ -1,65 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.job.commit;--import org.apache.gravitino.maintenance.occupancy.OccupancyGate;--/**- * Occupancy checks for commit-job paths.- *- * <p>{@link #withinMinInterval} gates enqueue (drops cooled-down chain members before spec build).- * {@link #isInFlight} gates pick (any chain type still in-flight aborts submit).- */-public interface CommitOccupancyGate {-- /**- * @param tableId table entity id- * @param policyId policy entity id- * @return true when that policy still holds a soft slot- */- boolean isInFlight(long tableId, long policyId);-- /**- * @param tableId table entity id- * @param policyId policy entity id- * @param minIntervalMs resolved cooldown- * @param nowMs current epoch millis- * @return true when still inside {@code minIntervalMs} after the last finish- */- boolean withinMinInterval(long tableId, long policyId, long minIntervalMs, long nowMs);-- /**- * @param gate production occupancy gate- * @return adapter- */- static CommitOccupancyGate of(OccupancyGate gate) {- return new CommitOccupancyGate() {- @Override- public boolean isInFlight(long tableId, long policyId) {- return gate.isInFlight(tableId, policyId);- }-- @Override- public boolean withinMinInterval(- long tableId, long policyId, long minIntervalMs, long nowMs) {- return gate.withinMinInterval(tableId, policyId, minIntervalMs, nowMs);- }- };- }-}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 20e2a3c9e3..fc903cf00e 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@@ -24,53 +24,53 @@ import java.util.Map;import java.util.Optional;import java.util.stream.Collectors;import javax.annotation.Nullable;+import org.apache.gravitino.maintenance.MaintenanceActionManager;+import org.apache.gravitino.maintenance.MaintenanceJobManager;+import org.apache.gravitino.maintenance.model.OccupancyClaim;import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;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;-import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceJobSubmitter;-import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceJobTemplates;-import org.apache.gravitino.maintenance.storage.service.OccupancyClaim;+import org.apache.gravitino.maintenance.scheduler.job.MaintenanceJobConfBuilder;import org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/**- * Commit-pool control-plane submit (§5.2.3): consume enqueue-time {@link MaintenanceJobSpec} →- * 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.+ * Commit-pool control-plane submit (§5.2.3): consume schedule-time {@link MaintenanceJobSpec} →+ * abort if any step still occupies the soft slot → soft-slot claim for every chain policy → {@link+ * MaintenanceJobManager#submitAndBind} for one chained Spark job.** <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.+ * schedule (see {@link CommitJobPlanner}). The caller always deletes the one-shot {@code+ * commit-job} row after this method returns.*/public final class MaintenanceCommitSubmitPipeline {private static final Logger LOG = LoggerFactory.getLogger(MaintenanceCommitSubmitPipeline.class);- private final CommitOccupancyGate occupancyGate;+ private final MaintenanceActionManager actionManager;private final TableMaintenanceActionMetaService actionMetaService;- private final MaintenanceJobSubmitter jobSubmitter;+ private final MaintenanceJobManager jobManager;private final MaintenanceJobConfBuilder jobConfBuilder;private final long claimTimeoutMs;/**- * @param occupancyGate in-flight checks- * @param actionMetaService soft-slot claim / bind- * @param jobSubmitter Gravitino Job submitter- * @param jobConfBuilder resolves enqueue-time conf-key refs before {@code runJob}+ * @param actionManager occupancy checks+ * @param actionMetaService soft-slot claim+ * @param jobManager runJob + bind (and orphan cancel)+ * @param jobConfBuilder resolves schedule-time conf-key refs before submit* @param claimTimeoutMs unbound claim TTL*/public MaintenanceCommitSubmitPipeline(- CommitOccupancyGate occupancyGate,+ MaintenanceActionManager actionManager,TableMaintenanceActionMetaService actionMetaService,- MaintenanceJobSubmitter jobSubmitter,+ MaintenanceJobManager jobManager,MaintenanceJobConfBuilder jobConfBuilder,long claimTimeoutMs) {- this.occupancyGate = Preconditions.checkNotNull(occupancyGate);+ this.actionManager = Preconditions.checkNotNull(actionManager);this.actionMetaService = Preconditions.checkNotNull(actionMetaService);- this.jobSubmitter = Preconditions.checkNotNull(jobSubmitter);+ this.jobManager = Preconditions.checkNotNull(jobManager);this.jobConfBuilder = Preconditions.checkNotNull(jobConfBuilder);Preconditions.checkArgument(claimTimeoutMs > 0, "claimTimeoutMs must be positive");this.claimTimeoutMs = claimTimeoutMs;@@ -80,7 +80,7 @@ public final class MaintenanceCommitSubmitPipeline {* Runs one commit-job pick for {@code instanceId} ({@code table:{table_id}}).** @param instanceId db-scheduler commit-job instance id- * @param spec enqueue-time payload; required+ * @param spec schedule-time payload; required*/public void submit(String instanceId, @Nullable MaintenanceJobSpec spec) {Optional<Long> parsed = MaintenanceTaskIds.parseCommitTable(instanceId);@@ -106,11 +106,11 @@ public final class MaintenanceCommitSubmitPipeline {return;}- // Design §5.2.3: any remaining type in-flight → delete commit-job and stop.+ // Design §5.2.3: any remaining type still occupied → delete commit-job and stop.for (Task task : spec.getTasks()) {- if (occupancyGate.isInFlight(tableId, task.getPolicyId())) {+ if (actionManager.isOccupied(tableId, task.getPolicyId())) {LOG.info(- "Skipping commit-job submit for table {} (type {} policy {} still in-flight)",+ "Skipping commit-job submit for table {} (type {} policy {} still occupied)",tableId,task.getMaintenanceType(),task.getPolicyId());@@ -130,58 +130,25 @@ public final class MaintenanceCommitSubmitPipeline {return;}- runAndBind(spec, claims.get(), tableId);- }-- private void runAndBind(MaintenanceJobSpec spec, List<OccupancyClaim> claims, long tableId) {- String metalake = spec.metalake();Map<String, String> jobConf;try {jobConf =jobConfBuilder.resolveForSubmit(MaintenanceJobSpecFactory.jobConfForCommitChain(spec));} catch (RuntimeException e) {- actionMetaService.deleteClaims(claims);+ actionMetaService.deleteClaims(claims.get());LOG.warn("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 =- jobSubmitter.runJob(- metalake, MaintenanceJobTemplates.ICEBERG_MAINTENANCE_TEMPLATE, jobConf);- actionMetaService.bindJobIds(claims, jobId);++ Optional<Long> jobId = jobManager.submitAndBind(spec.metalake(), jobConf, claims.get());+ if (jobId.isPresent()) {LOG.info("Submitted commit-job for table {} as job {} (chain={}, policies={})",tableId,- jobId,+ jobId.get(),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);- }- actionMetaService.deleteClaims(claims);- LOG.warn(- "Failed commit-job submit for table {} policies={}: {}",- tableId,- spec.getTasks().stream().map(Task::getPolicyId).collect(Collectors.toList()),- e.toString());- }- }-- private void cancelJobQuietly(String metalake, long jobId) {- try {- jobSubmitter.cancelJob(metalake, jobId);- } catch (RuntimeException cancelError) {- LOG.warn(- "Failed to cancel orphaned commit Spark job {} under metalake {} after bind failure",- jobId,- metalake,- cancelError);+ policyIds);}}}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 6d9efdbe51..6440c9c3d3 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@@ -18,687 +18,80 @@*/package org.apache.gravitino.maintenance.scheduler.job.cron;-import com.github.kagkarlsson.scheduler.ScheduledExecution;import com.github.kagkarlsson.scheduler.SchedulerClient;import com.github.kagkarlsson.scheduler.serializer.JacksonSerializer;-import com.github.kagkarlsson.scheduler.task.TaskInstance;-import com.github.kagkarlsson.scheduler.task.TaskInstanceId;-import com.google.common.annotations.VisibleForTesting;import com.google.common.base.Preconditions;import java.time.Instant;-import java.util.ArrayList;-import java.util.Comparator;-import java.util.HashSet;-import java.util.LinkedHashMap;import java.util.List;-import java.util.Map;-import java.util.Optional;-import java.util.Set;-import java.util.function.Function;import javax.sql.DataSource;import org.apache.gravitino.Config;import org.apache.gravitino.json.JsonUtils;+import org.apache.gravitino.maintenance.model.TableCandidate;import org.apache.gravitino.maintenance.scheduler.AutocommitDataSources;-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;-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;-import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceTableRefs.ResolvedTableRef;-import org.apache.gravitino.maintenance.scheduler.policy.expand.ExpandTableCandidate;+import org.apache.gravitino.maintenance.scheduler.MaintenanceSchedulerPools;import org.apache.gravitino.meta.PolicyEntity;-import org.apache.gravitino.policy.Policy;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;/**- * Enqueues one-shot {@code cron-job} rows through a db-scheduler {@link SchedulerClient} on the- * entity-store DataSource.+ * Submits one-shot {@code cron-job} rows to db-scheduler. Schedule planning is {@link+ * CronJobPlanner}.*- * <p>Follows the usual client pattern: {@link SchedulerClient#scheduleIfNotExists} for new instance- * ids, {@link SchedulerClient#getScheduledExecutionsForTask} to inspect open rows, and {@link- * SchedulerClient#reschedule(TaskInstanceId, Instant, Object)} to replace {@code task_data} when- * filling an incomplete snapshot-expiry batch.- *- * <p>Existing instance ids are left untouched so a repeated expand pick does not reset an- * already-queued submit. Snapshot-expiry winners attached at schema/catalog are packed into {@code- * batch:{batch_id};policy:{policy_id}} rows; incomplete batches are filled before a new {@code- * batch_id} is allocated (§5.2.2).- *- * <p>Snapshot-expiry coalesce happens at expand enqueue (not cron pick): unpicked same-catalog- * {@code expire_snapshots} {@code table:} / {@code batch:} rows may merge while under capacity. A- * queued row is merged only when it is not already at capacity and the combined size would not- * exceed capacity (all-or-nothing). Policy id need not match. Picked rows are never cancelled or- * merged.- *- * <p>Enqueue builds a {@link MaintenanceJobSpec} once (policy → jobConf) into {@code task_data};- * pick consumes that spec. The entity store disables JDBC autocommit; connections are wrapped via- * {@link AutocommitDataSources} so each client call commits. {@code task_data} is JSON via {@link- * JacksonSerializer + JsonUtils.anyFieldMapper()}.+ * <p>One instance is held by the expand path for the life of the scheduler pools.*/public class CronJobClient {- private static final Logger LOG = LoggerFactory.getLogger(CronJobClient.class);-- /**- * Max tables in one snapshot-expiry {@code batch:} cron-job (merge capacity). Independent of- * {@code gravitino.maintenance.expand.enqueueBatchSize}, which only bounds how many tables one- * expand pick may hand to {@link #enqueueNow}.- */- private static final int SNAPSHOT_EXPIRY_BATCH_CAPACITY = 10;-- private final DataSource dataSource;- private final MaintenanceJobSpecFactory specFactory;- private final Function<List<Long>, List<ResolvedTableRef>> tableRefResolver;+ private final SchedulerClient scheduler;+ private final CronJobPlanner planner;/*** @param dataSource relational JDBC pool shared with the entity store* @param gravitinoConfig server config for jobConf overlay*/public CronJobClient(DataSource dataSource, Config gravitinoConfig) {- this(dataSource, gravitinoConfig, MaintenanceTableRefs::resolve);+ Preconditions.checkNotNull(dataSource);+ this.planner = new CronJobPlanner(Preconditions.checkNotNull(gravitinoConfig), dataSource);+ this.scheduler = schedulerClient(dataSource);}/**- * Visible for tests that inject table-id resolution without a JDBC catalog store.+ * Plans and submits due-now cron jobs for the given table candidates.*- * @param dataSource relational JDBC pool- * @param gravitinoConfig server config- * @param tableRefResolver resolves entity ids to catalog + schema.table+ * @param policy effective maintenance policy (expand context)+ * @param candidates schedulable tables with their policies+ * @param batchCapacity max candidates considered for non-snapshot types+ * @return number of newly inserted cron-job rows*/- @VisibleForTesting- public CronJobClient(- DataSource dataSource,- Config gravitinoConfig,- Function<List<Long>, List<ResolvedTableRef>> tableRefResolver) {- this.dataSource = Preconditions.checkNotNull(dataSource);- this.specFactory = new MaintenanceJobSpecFactory(Preconditions.checkNotNull(gravitinoConfig));- this.tableRefResolver = Preconditions.checkNotNull(tableRefResolver);+ public int scheduleNow(PolicyEntity policy, List<TableCandidate> candidates, int batchCapacity) {+ return planner.plan(scheduler, policy, candidates, batchCapacity, Instant.now());}/**- * Enqueues due-now cron jobs for the given expand candidates.- *- * @param policy effective maintenance policy (used to build the jobConf spec)- * @param candidates enqueueable tables with winner levels- * @param batchCapacity expand enqueue budget (max candidates considered for non-snapshot types).- * Snapshot-expiry merge capacity is a fixed per-batch table limit inside this client, not- * this value.- * @return number of newly inserted cron-job rows (merges into existing batches do not count)+ * @param tableId table entity id+ * @param policyId policy entity id+ * @return true when a queued cron-job already covers the table*/- public int enqueueNow(- PolicyEntity policy, List<ExpandTableCandidate> candidates, int batchCapacity) {- if (policy == null || candidates == null || candidates.isEmpty()) {- return 0;- }- if (MaintenanceJobTemplates.templateName(policy.policyType()).isEmpty()) {- LOG.warn(- "Skipping cron-job enqueue for policy {} with unsupported type {}",- policy.id(),- policy.policyType());- return 0;- }- int expandLimit = Math.max(1, batchCapacity);- SchedulerClient client = schedulerClient(dataSource);- Instant due = Instant.now();-- if (policy.policyType() == Policy.BuiltInType.ICEBERG_SNAPSHOT_EXPIRATION) {- return enqueueSnapshotExpiry(client, policy, candidates, SNAPSHOT_EXPIRY_BATCH_CAPACITY, due);- }- int scheduled = 0;- int limit = Math.min(candidates.size(), expandLimit);- for (ExpandTableCandidate candidate : candidates.subList(0, limit)) {- if (scheduleTable(client, policy, candidate.tableId(), due)) {- scheduled++;- }- }- return scheduled;+ public boolean isTableAlreadyQueued(long tableId, long policyId) {+ return planner.isTableAlreadyQueued(scheduler, tableId, policyId);}/**- * Builds a db-scheduler {@link SchedulerClient} that can commit against the entity-store- * DataSource.- ** @param dataSource entity-store pool- * @return client bound to {@link TableMaintenanceSchedulerPools#CRON_TASKS_TABLE}+ * @return client bound to the cron-job table with JDBC autocommit forced on*/public static SchedulerClient schedulerClient(DataSource dataSource) {- return SchedulerClient.Builder.create(- AutocommitDataSources.wrap(dataSource), TableMaintenanceSchedulerPools.cronJobTask())- .serializer(new JacksonSerializer(JsonUtils.anyFieldMapper()))- .tableName(TableMaintenanceSchedulerPools.CRON_TASKS_TABLE)- .build();- }-- private int enqueueSnapshotExpiry(- SchedulerClient client,- PolicyEntity policy,- List<ExpandTableCandidate> slice,- int batchCapacity,- Instant due) {- List<Long> batchable = new ArrayList<>();- List<Long> tableLevel = new ArrayList<>();- for (ExpandTableCandidate candidate : slice) {- if (isTableAlreadyQueued(client, candidate.tableId(), policy.id())) {- continue;- }- if (candidate.batchableForSnapshotExpiry()) {- batchable.add(candidate.tableId());- } else {- tableLevel.add(candidate.tableId());- }- }- int scheduled = 0;- if (!batchable.isEmpty()) {- for (Map.Entry<String, List<Long>> entry : groupByCatalog(batchable).entrySet()) {- scheduled +=- enqueueSameCatalog(- client, policy, entry.getKey(), entry.getValue(), batchCapacity, due);- }- }- for (Long tableId : tableLevel) {- scheduled += enqueueTableSnapshotExpiry(client, policy, tableId, batchCapacity, due);- }- mergeJobsIntoOpenBatches(client, batchCapacity);- return scheduled;+ return schedulerClientOn(AutocommitDataSources.wrap(dataSource));}/**- * Enqueues one table-level snapshot-expiry winner: prefer filling an incomplete same-catalog- * {@code batch:}, else coalesce with other unpicked expire rows into a new {@code batch:}, else- * schedule a lone {@code table:} row.- */- private int enqueueTableSnapshotExpiry(- SchedulerClient client, PolicyEntity policy, long tableId, int batchCapacity, Instant due) {- if (isTableAlreadyQueued(client, tableId, policy.id())) {- return 0;- }- List<ResolvedTableRef> resolved = tableRefResolver.apply(List.of(tableId));- if (resolved.isEmpty()) {- LOG.warn("Skipping unresolved table {} from snapshot-expiry table enqueue", tableId);- return 0;- }- String catalogName = resolved.get(0).catalogName();- Optional<QueuedExpireJob> incomplete =- findIncompleteExpireBatch(client, batchCapacity, catalogName);- if (incomplete.isPresent()- && mergeTablesIntoCronRow(client, incomplete.get(), List.of(tableId), batchCapacity)) {- return 0;- }-- List<QueuedExpireJob> toMerge =- selectJobsToMerge(- client, catalogName, batchCapacity - 1, batchCapacity, Set.of(), Set.of(tableId));- if (!toMerge.isEmpty()) {- List<Long> chunk = new ArrayList<>();- chunk.add(tableId);- for (QueuedExpireJob job : toMerge) {- chunk.addAll(job.spec.tableIds());- }- if (chunk.size() <= batchCapacity && scheduleBatch(client, policy, chunk, due)) {- cancelJobs(client, toMerge);- return 1;- }- }- return scheduleTable(client, policy, tableId, due) ? 1 : 0;- }-- private Map<String, List<Long>> groupByCatalog(List<Long> tableIds) {- List<ResolvedTableRef> resolved = tableRefResolver.apply(tableIds);- Map<Long, ResolvedTableRef> byId = new LinkedHashMap<>();- for (ResolvedTableRef ref : resolved) {- byId.put(ref.tableId(), ref);- }- Map<String, List<Long>> byCatalog = new LinkedHashMap<>();- for (Long tableId : tableIds) {- ResolvedTableRef ref = byId.get(tableId);- if (ref == null) {- LOG.warn("Skipping unresolved table {} from snapshot-expiry batch enqueue", tableId);- continue;- }- byCatalog.computeIfAbsent(ref.catalogName(), ignored -> new ArrayList<>()).add(tableId);- }- return byCatalog;- }-- private int enqueueSameCatalog(- SchedulerClient client,- PolicyEntity policy,- String catalogName,- List<Long> tableIds,- int batchCapacity,- Instant due) {- List<Long> remaining = new ArrayList<>(tableIds);- int newRows = 0;- while (!remaining.isEmpty()) {- Optional<QueuedExpireJob> incomplete =- findIncompleteExpireBatch(client, batchCapacity, catalogName);- if (incomplete.isPresent()) {- QueuedExpireJob open = incomplete.get();- int room = batchCapacity - open.spec.tableIds().size();- int fromRemaining = Math.min(room, remaining.size());- List<Long> chunk = new ArrayList<>(remaining.subList(0, fromRemaining));- Set<Long> excludeTables = new HashSet<>(open.spec.tableIds());- excludeTables.addAll(chunk);- List<QueuedExpireJob> toMerge =- selectJobsToMerge(- client,- catalogName,- room - chunk.size(),- batchCapacity,- Set.of(open.instanceId.getId()),- excludeTables);- for (QueuedExpireJob job : toMerge) {- chunk.addAll(job.spec.tableIds());- }- if (mergeTablesIntoCronRow(client, open, chunk, batchCapacity)) {- remaining.subList(0, fromRemaining).clear();- cancelJobs(client, toMerge);- continue;- }- }- int end = Math.min(batchCapacity, remaining.size());- List<Long> chunk = new ArrayList<>(remaining.subList(0, end));- List<QueuedExpireJob> toMerge =- selectJobsToMerge(- client,- catalogName,- batchCapacity - chunk.size(),- batchCapacity,- Set.of(),- new HashSet<>(chunk));- for (QueuedExpireJob job : toMerge) {- chunk.addAll(job.spec.tableIds());- }- if (chunk.size() <= batchCapacity && scheduleBatch(client, policy, chunk, due)) {- newRows++;- remaining.subList(0, end).clear();- cancelJobs(client, toMerge);- continue;- }- Long first = remaining.remove(0);- if (end > 1 && scheduleBatch(client, policy, List.of(first), due)) {- newRows++;- } else {- LOG.warn(- "Dropping table {} from snapshot-expiry enqueue for policy {} after failed batch build",- first,- policy.id());- }- }- return newRows;- }-- /** Fills incomplete expire {@code batch:} rows with whole unpicked same-catalog cron rows. */- private void mergeJobsIntoOpenBatches(SchedulerClient client, int batchCapacity) {- Set<String> saturated = new HashSet<>();- for (; ; ) {- Optional<QueuedExpireJob> incomplete =- listQueuedExpireJobs(client).stream()- .filter(j -> j.isBatch && !j.picked && j.spec.tableIds().size() < batchCapacity)- .filter(j -> j.catalog != null)- .filter(j -> !saturated.contains(j.instanceId.getId()))- .min(Comparator.comparingLong(j -> j.batchId));- if (incomplete.isEmpty()) {- return;- }- QueuedExpireJob open = incomplete.get();- int room = batchCapacity - open.spec.tableIds().size();- List<QueuedExpireJob> toMerge =- selectJobsToMerge(- client,- open.catalog,- room,- batchCapacity,- Set.of(open.instanceId.getId()),- new HashSet<>(open.spec.tableIds()));- if (toMerge.isEmpty()) {- saturated.add(open.instanceId.getId());- continue;- }- List<Long> extra = new ArrayList<>();- for (QueuedExpireJob job : toMerge) {- extra.addAll(job.spec.tableIds());- }- if (!mergeTablesIntoCronRow(client, open, extra, batchCapacity)) {- return;- }- cancelJobs(client, toMerge);- }- }-- /**- * Selects whole unpicked expire cron rows that fit in {@code room} without exceeding capacity.- * Skips rows already at capacity. All-or-nothing per row.- */- private static List<QueuedExpireJob> selectJobsToMerge(- SchedulerClient client,- String catalogName,- int room,- int batchCapacity,- Set<String> excludeInstanceIds,- Set<Long> excludeTableIds) {- if (room <= 0) {- return List.of();- }- List<QueuedExpireJob> candidates =- listQueuedExpireJobs(client).stream()- .filter(j -> !j.picked)- .filter(j -> catalogName.equals(j.catalog))- .filter(j -> !excludeInstanceIds.contains(j.instanceId.getId()))- .filter(j -> j.spec.tableIds().size() < batchCapacity)- .filter(j -> j.spec.tableIds().stream().noneMatch(excludeTableIds::contains))- .sorted(- Comparator.comparingInt((QueuedExpireJob j) -> j.spec.tableIds().size())- .thenComparing(j -> j.instanceId.getId()))- .toList();- List<QueuedExpireJob> taken = new ArrayList<>();- int left = room;- Set<Long> claimedTables = new HashSet<>(excludeTableIds);- for (QueuedExpireJob candidate : candidates) {- int size = candidate.spec.tableIds().size();- if (size > left) {- continue;- }- if (candidate.spec.tableIds().stream().anyMatch(claimedTables::contains)) {- continue;- }- taken.add(candidate);- claimedTables.addAll(candidate.spec.tableIds());- left -= size;- if (left == 0) {- break;- }- }- return taken;- }-- private boolean mergeTablesIntoCronRow(- SchedulerClient client, QueuedExpireJob open, List<Long> extraTableIds, int batchCapacity) {- if (extraTableIds.isEmpty()) {- return true;- }- Map<Long, Task> byTableId = new LinkedHashMap<>();- for (Task task : open.spec.getTasks()) {- byTableId.putIfAbsent(task.getTableId(), task);- }- if (byTableId.size() + extraTableIds.stream().filter(id -> !byTableId.containsKey(id)).count()- > batchCapacity) {- return false;- }- String openCatalog = open.catalog;- if (openCatalog == null || openCatalog.isEmpty()) {- LOG.warn(- "Could not merge tables into cron-job {}: open job missing catalog name",- open.instanceId.getId());- return false;- }- List<ResolvedTableRef> resolved = tableRefResolver.apply(extraTableIds);- if (resolved.size() != extraTableIds.size()) {- LOG.warn(- "Could not merge tables into cron-job {}: resolved {} of {} ids {}",- open.instanceId.getId(),- resolved.size(),- extraTableIds.size(),- extraTableIds);- return false;- }- 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())) {- LOG.warn(- "Could not merge table {} into cron-job {}: catalog {} != open job catalog {}",- ref.tableId(),- open.instanceId.getId(),- ref.catalogName(),- openCatalog);- return false;- }- 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 (byTableId.size() > batchCapacity) {- return false;- }- MaintenanceJobSpec merged =- new MaintenanceJobSpec(- new ArrayList<>(byTableId.values()),- open.spec.getUpdaterOptions(),- open.spec.getSparkConf());- try {- return client.reschedule(open.instanceId, open.executionTime, merged);- } catch (RuntimeException e) {- LOG.debug(- "Could not merge tables into cron-job {}: {}", open.instanceId.getId(), e.toString());- return false;- }- }-- private static void cancelJobs(SchedulerClient client, List<QueuedExpireJob> jobs) {- for (QueuedExpireJob job : jobs) {- Optional<ScheduledExecution<Object>> execution = client.getScheduledExecution(job.instanceId);- if (execution.isEmpty()) {- continue;- }- if (execution.get().isPicked()) {- LOG.warn(- "Skip cancel of picked cron-job {} after snapshot-expiry merge",- job.instanceId.getId());- continue;- }- try {- client.cancel(job.instanceId);- } catch (RuntimeException e) {- LOG.warn(- "Failed to cancel merged cron-job {} after snapshot-expiry merge: {}",- job.instanceId.getId(),- e.toString());- }- }- }-- private boolean scheduleTable(- SchedulerClient client, PolicyEntity policy, long tableId, Instant due) {- Optional<MaintenanceJobSpec> spec = buildSpec(policy, List.of(tableId));- if (spec.isEmpty()) {- return false;- }- String id = MaintenanceTaskIds.forCronTable(tableId, policy.id());- return client.scheduleIfNotExists(- new TaskInstance<>(TableMaintenanceSchedulerPools.CRON_JOB, id, spec.get()), due);- }-- private boolean scheduleBatch(- SchedulerClient client, PolicyEntity policy, List<Long> tableIds, Instant due) {- Optional<MaintenanceJobSpec> spec = buildSpec(policy, tableIds);- if (spec.isEmpty()) {- return false;- }- long batchId = nextBatchId(client, policy.id());- String id = MaintenanceTaskIds.forCronBatch(batchId, policy.id());- return client.scheduleIfNotExists(- new TaskInstance<>(TableMaintenanceSchedulerPools.CRON_JOB, id, spec.get()), due);- }-- private Optional<MaintenanceJobSpec> buildSpec(PolicyEntity policy, List<Long> tableIds) {- List<ResolvedTableRef> resolved = tableRefResolver.apply(tableIds);- if (resolved.size() != tableIds.size()) {- LOG.warn(- "Skipping cron-job enqueue for policy {}: resolved {} of {} table ids {}",- policy.id(),- resolved.size(),- tableIds.size(),- tableIds);- return Optional.empty();- }- try {- return Optional.of(specFactory.forCron(policy, resolved));- } catch (RuntimeException e) {- LOG.warn(- "Skipping cron-job enqueue for policy {}: failed to build jobConf / MaintenanceJobSpec: {}",- policy.id(),- e.toString());- return Optional.empty();- }- }-- private static Optional<QueuedExpireJob> findIncompleteExpireBatch(- SchedulerClient client, int batchCapacity, String catalogName) {- return listQueuedExpireJobs(client).stream()- .filter(j -> j.isBatch && !j.picked && j.spec.tableIds().size() < batchCapacity)- .filter(j -> catalogName.equals(j.catalog))- .min(Comparator.comparingLong(j -> j.batchId));- }-- private static List<QueuedExpireJob> listQueuedExpireJobs(SchedulerClient client) {- List<QueuedExpireJob> open = new ArrayList<>();- for (ScheduledExecution<MaintenanceJobSpec> execution :- client.getScheduledExecutionsForTask(- TableMaintenanceSchedulerPools.CRON_JOB, MaintenanceJobSpec.class)) {- MaintenanceJobSpec data = execution.getData();- if (data == null || !data.isValid() || !isExpireSnapshots(data)) {- continue;- }- String instanceId = execution.getTaskInstance().getId();- String catalog = data.getTasks().isEmpty() ? null : data.getTasks().get(0).catalogName();- Optional<long[]> batch = MaintenanceTaskIds.parseCronBatch(instanceId);- if (batch.isPresent()) {- // [batchId, policyId]- open.add(- new QueuedExpireJob(- TaskInstanceId.of(TableMaintenanceSchedulerPools.CRON_JOB, instanceId),- true,- batch.get()[0],- batch.get()[1],- execution.getExecutionTime(),- data,- catalog,- execution.isPicked()));- continue;- }- Optional<long[]> table = MaintenanceTaskIds.parseCronTable(instanceId);- if (table.isPresent()) {- // [tableId, policyId]- open.add(- new QueuedExpireJob(- TaskInstanceId.of(TableMaintenanceSchedulerPools.CRON_JOB, instanceId),- false,- -1L,- table.get()[1],- execution.getExecutionTime(),- data,- catalog,- execution.isPicked()));- }- }- return open;- }-- private static boolean isExpireSnapshots(MaintenanceJobSpec spec) {- String expireType =- MaintenanceJobTemplates.maintenanceType(Policy.BuiltInType.ICEBERG_SNAPSHOT_EXPIRATION)- .orElseThrow();- return spec.getTasks().stream().anyMatch(t -> expireType.equals(t.getMaintenanceType()));- }-- private static long nextBatchId(SchedulerClient client, long policyId) {- long max = -1L;- for (QueuedExpireJob job : listQueuedExpireJobs(client)) {- if (job.isBatch && job.policyId == policyId) {- max = Math.max(max, job.batchId);- }- }- return max + 1L;- }-- /**- * True when the table should not be enqueued again: a {@code table:} row already exists for this- * policy, any queued snapshot-expiry cron-job (any policy) already covers the table, or a- * non-expire {@code batch:} for this policy already includes the table.+ * Builds a cron-job client on {@code dataSource} without wrapping. Used when the caller supplies+ * a transactional or session-joined data source.+ *+ * @param dataSource already-configured JDBC data source+ * @return client bound to the cron-job table*/- static boolean isTableAlreadyQueued(SchedulerClient client, long tableId, long policyId) {- if (client- .getScheduledExecution(- TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB,- MaintenanceTaskIds.forCronTable(tableId, policyId)))- .isPresent()) {- return true;- }- for (QueuedExpireJob job : listQueuedExpireJobs(client)) {- if (job.spec.tableIds().contains(tableId)) {- return true;- }- }- for (ScheduledExecution<MaintenanceJobSpec> execution :- client.getScheduledExecutionsForTask(- TableMaintenanceSchedulerPools.CRON_JOB, MaintenanceJobSpec.class)) {- Optional<long[]> parsed =- MaintenanceTaskIds.parseCronBatch(execution.getTaskInstance().getId());- // [batchId, policyId]- if (parsed.isEmpty() || parsed.get()[1] != policyId) {- continue;- }- MaintenanceJobSpec data = execution.getData();- if (data != null- && data.isValid()- && !isExpireSnapshots(data)- && data.tableIds().contains(tableId)) {- return true;- }- }- return false;- }-- private static final class QueuedExpireJob {- private final TaskInstanceId instanceId;- private final boolean isBatch;- private final long batchId;- private final long policyId;- private final Instant executionTime;- private final MaintenanceJobSpec spec;- private final String catalog;- private final boolean picked;-- private QueuedExpireJob(- TaskInstanceId instanceId,- boolean isBatch,- long batchId,- long policyId,- Instant executionTime,- MaintenanceJobSpec spec,- String catalog,- boolean picked) {- this.instanceId = instanceId;- this.isBatch = isBatch;- this.batchId = batchId;- this.policyId = policyId;- this.executionTime = executionTime;- this.spec = spec;- this.catalog = catalog;- this.picked = picked;- }+ public static SchedulerClient schedulerClientOn(DataSource dataSource) {+ return SchedulerClient.Builder.create(dataSource, MaintenanceSchedulerPools.cronJobTask())+ .serializer(new JacksonSerializer(JsonUtils.anyFieldMapper()))+ .tableName(MaintenanceSchedulerPools.CRON_TASKS_TABLE)+ .build();}}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/CronJobPlanner.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/CronJobPlanner.javanew file mode 100644index 0000000000..e529ab9ccc--- /dev/null+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/CronJobPlanner.java@@ -0,0 +1,690 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.maintenance.scheduler.job.cron;++import com.github.kagkarlsson.scheduler.ScheduledExecution;+import com.github.kagkarlsson.scheduler.SchedulerClient;+import com.github.kagkarlsson.scheduler.task.TaskInstance;+import com.github.kagkarlsson.scheduler.task.TaskInstanceId;+import com.google.common.base.Preconditions;+import java.sql.SQLException;+import java.time.Instant;+import java.util.ArrayList;+import java.util.Comparator;+import java.util.HashSet;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.Set;+import java.util.function.Function;+import javax.annotation.Nullable;+import javax.sql.DataSource;+import org.apache.gravitino.Config;+import org.apache.gravitino.maintenance.model.TableCandidate;+import org.apache.gravitino.maintenance.scheduler.AutocommitDataSources;+import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;+import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.Task;+import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpecFactory;+import org.apache.gravitino.maintenance.scheduler.MaintenanceSchedulerPools;+import org.apache.gravitino.maintenance.scheduler.MaintenanceTaskIds;+import org.apache.gravitino.maintenance.scheduler.job.MaintenanceAuthConsistency;+import org.apache.gravitino.maintenance.scheduler.job.MaintenanceJobTemplates;+import org.apache.gravitino.meta.PolicyEntity;+import org.apache.gravitino.policy.Policy;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * Plans schedule-time {@code cron-job} work: builds specs for non-snapshot policies, and for+ * snapshot-expiry merges same-catalog rows under a fixed batch capacity (claim-first {@code cancel}+ * then {@code reschedule} of target {@code task_data} in one JDBC transaction).+ */+public class CronJobPlanner {++ private static final Logger LOG = LoggerFactory.getLogger(CronJobPlanner.class);++ /** Max tables in one snapshot-expiry {@code batch:} / merge target. */+ private static final int SNAPSHOT_EXPIRY_BATCH_CAPACITY = 10;++ private final Config gravitinoConfig;+ private final DataSource dataSource;+ private final MaintenanceJobSpecFactory specFactory;++ /**+ * @param gravitinoConfig server config for jobConf overlay and auth checks+ * @param dataSource entity-store pool used to open merge transactions+ */+ public CronJobPlanner(Config gravitinoConfig, DataSource dataSource) {+ this.gravitinoConfig = Preconditions.checkNotNull(gravitinoConfig);+ this.dataSource = Preconditions.checkNotNull(dataSource);+ this.specFactory = new MaintenanceJobSpecFactory(this.gravitinoConfig);+ }++ /**+ * Plans and writes due-now cron-job rows for the given expand candidates.+ *+ * @param client cron-job scheduler client+ * @param policy effective maintenance policy+ * @param candidates schedulable tables+ * @param expandBatchCapacity max candidates for non-snapshot types+ * @param due execution time for newly inserted rows+ * @return number of newly inserted cron-job rows (merges into existing rows do not count)+ */+ public int plan(+ SchedulerClient client,+ PolicyEntity policy,+ List<TableCandidate> candidates,+ int expandBatchCapacity,+ Instant due) {+ if (policy == null || candidates == null || candidates.isEmpty()) {+ return 0;+ }+ if (MaintenanceJobTemplates.templateName(policy.policyType()).isEmpty()) {+ LOG.warn(+ "Skipping cron-job schedule for policy {} with unsupported type {}",+ policy.id(),+ policy.policyType());+ return 0;+ }+ if (policy.policyType() != Policy.BuiltInType.ICEBERG_SNAPSHOT_EXPIRATION) {+ int scheduled = 0;+ int limit = Math.min(candidates.size(), Math.max(1, expandBatchCapacity));+ for (TableCandidate candidate : candidates.subList(0, limit)) {+ Optional<MaintenanceJobSpec> spec = buildSpec(List.of(candidate));+ if (spec.isEmpty()) {+ continue;+ }+ String id = MaintenanceTaskIds.forCronTable(candidate.tableId(), policy.id());+ if (client.scheduleIfNotExists(+ new TaskInstance<>(MaintenanceSchedulerPools.CRON_JOB, id, spec.get()), due)) {+ scheduled++;+ }+ }+ return scheduled;+ }+ int batchCapacity = SNAPSHOT_EXPIRY_BATCH_CAPACITY;+ List<TableCandidate> toSchedule = new ArrayList<>();+ for (TableCandidate candidate : candidates) {+ if (isTableAlreadyQueued(client, candidate.tableId(), policy.id())) {+ continue;+ }+ toSchedule.add(candidate);+ }+ int scheduled = 0;+ if (!toSchedule.isEmpty()) {+ Map<String, List<TableCandidate>> byCatalog = new LinkedHashMap<>();+ for (TableCandidate candidate : toSchedule) {+ byCatalog+ .computeIfAbsent(candidate.catalogName(), ignored -> new ArrayList<>())+ .add(candidate);+ }+ for (Map.Entry<String, List<TableCandidate>> entry : byCatalog.entrySet()) {+ scheduled +=+ scheduleSameCatalog(+ client, policy, entry.getKey(), entry.getValue(), batchCapacity, due);+ }+ }+ mergeOpenExpireJobs(client, batchCapacity);+ return scheduled;+ }++ private int scheduleSameCatalog(+ SchedulerClient client,+ PolicyEntity policy,+ String catalogName,+ List<TableCandidate> tables,+ int batchCapacity,+ Instant due) {+ List<TableCandidate> remaining = new ArrayList<>(tables);+ int newRows = 0;+ while (!remaining.isEmpty()) {+ Optional<QueuedExpireJob> incompleteBatch =+ findIncompleteExpireBatch(client, batchCapacity, catalogName);+ if (incompleteBatch.isPresent()) {+ QueuedExpireJob target = incompleteBatch.get();+ int remainingCapacity = batchCapacity - target.spec.tableIds().size();+ int takeCount = Math.min(remainingCapacity, remaining.size());+ List<TableCandidate> scheduleTables = new ArrayList<>(remaining.subList(0, takeCount));+ Optional<MaintenanceJobSpec> scheduleSpec = buildSpec(scheduleTables);+ if (scheduleSpec.isPresent()) {+ Set<Long> excludeTableIds = new HashSet<>(target.spec.tableIds());+ for (TableCandidate table : scheduleTables) {+ excludeTableIds.add(table.tableId());+ }+ List<QueuedExpireJob> peers =+ selectQueuedJobsToClaim(+ client,+ catalogName,+ remainingCapacity - scheduleTables.size(),+ batchCapacity,+ Set.of(target.instanceId.getId()),+ excludeTableIds);+ if (mergeInto(+ target, scheduleSpec.get().getTasks(), scheduleSpec.get(), peers, batchCapacity)) {+ remaining.subList(0, takeCount).clear();+ continue;+ }+ }+ }+ int takeCount = Math.min(batchCapacity, remaining.size());+ List<TableCandidate> scheduleTables = new ArrayList<>(remaining.subList(0, takeCount));+ Optional<MaintenanceJobSpec> scheduleSpec = buildSpec(scheduleTables);+ if (scheduleSpec.isPresent()) {+ Optional<QueuedExpireJob> batchJob =+ scheduleBatchJob(client, policy, scheduleSpec.get(), due);+ if (batchJob.isPresent()) {+ List<QueuedExpireJob> peers =+ selectQueuedJobsToClaim(+ client,+ catalogName,+ batchCapacity - batchJob.get().spec.tableIds().size(),+ batchCapacity,+ Set.of(batchJob.get().instanceId.getId()),+ new HashSet<>(batchJob.get().spec.tableIds()));+ if (!peers.isEmpty()) {+ mergeInto(batchJob.get(), List.of(), null, peers, batchCapacity);+ }+ newRows++;+ remaining.subList(0, takeCount).clear();+ continue;+ }+ }+ long droppedTableId = remaining.remove(0).tableId();+ LOG.warn(+ "Dropping table {} from snapshot-expiry schedule for policy {} after failed batch build",+ droppedTableId,+ policy.id());+ }+ return newRows;+ }++ /** Merges under-capacity expire rows (prefer {@code batch:}, then {@code table:}). */+ private void mergeOpenExpireJobs(SchedulerClient client, int batchCapacity) {+ Set<String> saturatedInstanceIds = new HashSet<>();+ for (; ; ) {+ Optional<QueuedExpireJob> target =+ findMergeTarget(client, batchCapacity, saturatedInstanceIds);+ if (target.isEmpty()) {+ return;+ }+ QueuedExpireJob mergeTarget = target.get();+ int remainingCapacity = batchCapacity - mergeTarget.spec.tableIds().size();+ List<QueuedExpireJob> peers =+ selectQueuedJobsToClaim(+ client,+ mergeTarget.catalog,+ remainingCapacity,+ batchCapacity,+ Set.of(mergeTarget.instanceId.getId()),+ new HashSet<>(mergeTarget.spec.tableIds()));+ if (peers.isEmpty()) {+ saturatedInstanceIds.add(mergeTarget.instanceId.getId());+ continue;+ }+ if (!mergeInto(mergeTarget, List.of(), null, peers, batchCapacity)) {+ saturatedInstanceIds.add(mergeTarget.instanceId.getId());+ }+ }+ }++ /** Prefers the oldest under-capacity {@code batch:}, else any under-capacity {@code table:}. */+ private static Optional<QueuedExpireJob> findMergeTarget(+ SchedulerClient client, int batchCapacity, Set<String> saturatedInstanceIds) {+ List<QueuedExpireJob> underCapacity =+ listQueuedExpireJobs(client).stream()+ .filter(job -> !job.picked && job.spec.tableIds().size() < batchCapacity)+ .filter(job -> job.catalog != null)+ .filter(job -> !saturatedInstanceIds.contains(job.instanceId.getId()))+ .toList();+ Optional<QueuedExpireJob> batchTarget =+ underCapacity.stream()+ .filter(job -> job.isBatch)+ .min(Comparator.comparingLong(job -> job.batchId));+ if (batchTarget.isPresent()) {+ return batchTarget;+ }+ return underCapacity.stream()+ .filter(job -> !job.isBatch)+ .min(Comparator.comparing(job -> job.instanceId.getId()));+ }++ /**+ * Claim-first merge into {@code target}: cancel each unpicked peer then reschedule the target's+ * {@code task_data} in one JDBC transaction. Target {@code task_instance} is unchanged. Envelope+ * {@code spark_conf} is max-merged across target, optional schedule spec, and claimed peers.+ *+ * @return true when the target was updated, or when there was nothing to merge+ */+ private boolean mergeInto(+ QueuedExpireJob target,+ List<Task> scheduleTasks,+ @Nullable MaintenanceJobSpec scheduleSpec,+ List<QueuedExpireJob> peersToClaim,+ int batchCapacity) {+ if (scheduleSpec != null+ && !MaintenanceAuthConsistency.hasSameAuth(gravitinoConfig, target.spec, scheduleSpec)) {+ LOG.debug(+ "Skipping snapshot-expiry merge into {}: schedule auth mismatch with target",+ target.instanceId.getId());+ return false;+ }++ List<QueuedExpireJob> claimable = new ArrayList<>();+ for (QueuedExpireJob peer : peersToClaim) {+ if (!MaintenanceAuthConsistency.hasSameAuth(gravitinoConfig, target.spec, peer.spec)) {+ LOG.debug(+ "Skipping claim of cron-job {} for snapshot-expiry merge: auth mismatch with target {}",+ peer.instanceId.getId(),+ target.instanceId.getId());+ continue;+ }+ claimable.add(peer);+ }++ Set<Long> plannedTableIds = new HashSet<>(target.spec.tableIds());+ for (Task task : scheduleTasks) {+ plannedTableIds.add(task.getTableId());+ }+ for (QueuedExpireJob peer : claimable) {+ plannedTableIds.addAll(peer.spec.tableIds());+ }+ if (plannedTableIds.size() > batchCapacity) {+ return false;+ }++ if (claimable.isEmpty() && scheduleTasks.isEmpty()) {+ return peersToClaim.isEmpty();+ }++ try {+ Function<DataSource, Boolean> mergeWork =+ txDs -> {+ SchedulerClient txClient = CronJobClient.schedulerClientOn(txDs);+ List<Task> claimedTasks = new ArrayList<>();+ List<String> sparkConfJsons = new ArrayList<>();+ sparkConfJsons.add(target.spec.getSparkConf());+ if (scheduleSpec != null) {+ sparkConfJsons.add(scheduleSpec.getSparkConf());+ }+ for (QueuedExpireJob peer : claimable) {+ Optional<MaintenanceJobSpec> claimedSpec = tryClaimQueuedJob(txClient, peer);+ if (claimedSpec.isEmpty()) {+ continue;+ }+ claimedTasks.addAll(claimedSpec.get().getTasks());+ sparkConfJsons.add(claimedSpec.get().getSparkConf());+ }++ List<Task> tasksToAdd = new ArrayList<>(scheduleTasks);+ tasksToAdd.addAll(claimedTasks);+ if (tasksToAdd.isEmpty()) {+ if (peersToClaim.isEmpty()) {+ return true;+ }+ throw new MergeTransactionAborted();+ }+ String mergedSparkConf =+ MaintenanceJobSpecFactory.mergeSparkConfJson(sparkConfJsons.toArray(new String[0]));+ if (!rescheduleMergedTaskData(+ txClient, target, tasksToAdd, mergedSparkConf, batchCapacity)) {+ throw new MergeTransactionAborted();+ }+ return true;+ };+ AutocommitDataSources.runInTransaction(dataSource, mergeWork);+ return true;+ } catch (MergeTransactionAborted e) {+ return false;+ } catch (SQLException e) {+ LOG.warn(+ "Snapshot-expiry merge into {} failed to open or finish JDBC transaction: {}",+ target.instanceId.getId(),+ e.toString());+ return false;+ }+ }++ /**+ * Signals intentional merge abort so {@link AutocommitDataSources#runInTransaction} rolls back.+ */+ private static final class MergeTransactionAborted extends RuntimeException {+ private static final long serialVersionUID = 1L;++ private MergeTransactionAborted() {+ super(null, null, false, false);+ }+ }++ /**+ * Cancels an unpicked queued expire row and returns its latest {@code task_data}. Empty means the+ * row was missing, already picked, or cancel failed — do not merge those tables into the target.+ */+ private static Optional<MaintenanceJobSpec> tryClaimQueuedJob(+ SchedulerClient client, QueuedExpireJob queuedJob) {+ Optional<ScheduledExecution<Object>> execution =+ client.getScheduledExecution(queuedJob.instanceId);+ if (execution.isEmpty() || execution.get().isPicked()) {+ return Optional.empty();+ }+ Object data = execution.get().getData();+ if (!(data instanceof MaintenanceJobSpec)) {+ return Optional.empty();+ }+ MaintenanceJobSpec spec = (MaintenanceJobSpec) data;+ if (!spec.isValid()) {+ return Optional.empty();+ }+ try {+ client.cancel(queuedJob.instanceId);+ } catch (RuntimeException e) {+ LOG.debug(+ "Could not claim cron-job {} for snapshot-expiry merge: {}",+ queuedJob.instanceId.getId(),+ e.toString());+ return Optional.empty();+ }+ return Optional.of(spec);+ }++ /**+ * Selects whole unpicked expire cron rows that fit in {@code remainingCapacity} without exceeding+ * {@code batchCapacity}. Skips rows already at capacity. All-or-nothing per row.+ */+ private static List<QueuedExpireJob> selectQueuedJobsToClaim(+ SchedulerClient client,+ String catalogName,+ int remainingCapacity,+ int batchCapacity,+ Set<String> excludeInstanceIds,+ Set<Long> excludeTableIds) {+ if (remainingCapacity <= 0) {+ return List.of();+ }+ List<QueuedExpireJob> candidates =+ listQueuedExpireJobs(client).stream()+ .filter(job -> !job.picked)+ .filter(job -> catalogName.equals(job.catalog))+ .filter(job -> !excludeInstanceIds.contains(job.instanceId.getId()))+ .filter(job -> job.spec.tableIds().size() < batchCapacity)+ .filter(job -> job.spec.tableIds().stream().noneMatch(excludeTableIds::contains))+ .sorted(+ Comparator.comparingInt((QueuedExpireJob job) -> job.spec.tableIds().size())+ .thenComparing(job -> job.instanceId.getId()))+ .toList();+ List<QueuedExpireJob> selected = new ArrayList<>();+ int capacityLeft = remainingCapacity;+ Set<Long> reservedTableIds = new HashSet<>(excludeTableIds);+ for (QueuedExpireJob candidate : candidates) {+ int size = candidate.spec.tableIds().size();+ if (size > capacityLeft) {+ continue;+ }+ if (candidate.spec.tableIds().stream().anyMatch(reservedTableIds::contains)) {+ continue;+ }+ selected.add(candidate);+ reservedTableIds.addAll(candidate.spec.tableIds());+ capacityLeft -= size;+ if (capacityLeft == 0) {+ break;+ }+ }+ return selected;+ }++ /**+ * Reschedules {@code target} with claimed/schedule tasks appended. Per-task {@code policyId} is+ * preserved; {@code sparkConf} is the already max-merged {@code spark_conf}.+ */+ private boolean rescheduleMergedTaskData(+ SchedulerClient client,+ QueuedExpireJob target,+ List<Task> tasksToAdd,+ @Nullable String sparkConf,+ int batchCapacity) {+ Map<Long, Task> tasksByTableId = new LinkedHashMap<>();+ for (Task task : target.spec.getTasks()) {+ tasksByTableId.putIfAbsent(task.getTableId(), task);+ }+ String targetCatalog = target.catalog;+ if (targetCatalog == null || targetCatalog.isEmpty()) {+ LOG.warn(+ "Could not merge tables into cron-job {}: target missing catalog name",+ target.instanceId.getId());+ return false;+ }+ if (target.spec.metalake() == null) {+ LOG.warn(+ "Could not merge tables into cron-job {}: missing metalake on target spec",+ target.instanceId.getId());+ return false;+ }+ boolean added = false;+ for (Task task : tasksToAdd) {+ if (tasksByTableId.containsKey(task.getTableId())) {+ continue;+ }+ String catalog = task.catalogName();+ if (catalog == null || !targetCatalog.equals(catalog)) {+ LOG.warn(+ "Could not merge table {} into cron-job {}: catalog {} != target catalog {}",+ task.getTableId(),+ target.instanceId.getId(),+ catalog,+ targetCatalog);+ return false;+ }+ tasksByTableId.put(task.getTableId(), task);+ added = true;+ }+ if (!added) {+ return true;+ }+ if (tasksByTableId.size() > batchCapacity) {+ return false;+ }+ MaintenanceJobSpec mergedSpec =+ new MaintenanceJobSpec(+ new ArrayList<>(tasksByTableId.values()), target.spec.getUpdaterOptions(), sparkConf);+ try {+ return client.reschedule(target.instanceId, target.executionTime, mergedSpec);+ } catch (RuntimeException e) {+ LOG.debug(+ "Could not reschedule cron-job {} after snapshot-expiry merge: {}",+ target.instanceId.getId(),+ e.toString());+ return false;+ }+ }++ /** Schedules a new {@code batch:} for schedule tables only; peers are claimed afterward. */+ private Optional<QueuedExpireJob> scheduleBatchJob(+ SchedulerClient client, PolicyEntity policy, MaintenanceJobSpec spec, Instant due) {+ if (spec.getTasks() == null || spec.getTasks().isEmpty()) {+ return Optional.empty();+ }+ long maxBatchId = -1L;+ for (QueuedExpireJob job : listQueuedExpireJobs(client)) {+ if (job.isBatch && job.policyId == policy.id()) {+ maxBatchId = Math.max(maxBatchId, job.batchId);+ }+ }+ long batchId = maxBatchId + 1L;+ String id = MaintenanceTaskIds.forCronBatch(batchId, policy.id());+ boolean created =+ client.scheduleIfNotExists(+ new TaskInstance<>(MaintenanceSchedulerPools.CRON_JOB, id, spec), due);+ if (!created) {+ return Optional.empty();+ }+ return listQueuedExpireJobs(client).stream()+ .filter(job -> job.instanceId.getId().equals(id))+ .findFirst();+ }++ private Optional<MaintenanceJobSpec> buildSpec(List<TableCandidate> tables) {+ try {+ return Optional.of(specFactory.forCron(tables));+ } catch (RuntimeException e) {+ long policyId =+ tables.isEmpty() || tables.get(0).policies().isEmpty()+ ? -1L+ : tables.get(0).policies().get(0).id();+ LOG.warn(+ "Skipping cron-job schedule for policy {}: failed to build jobConf / MaintenanceJobSpec: {}",+ policyId,+ e.toString());+ return Optional.empty();+ }+ }++ private static Optional<QueuedExpireJob> findIncompleteExpireBatch(+ SchedulerClient client, int batchCapacity, String catalogName) {+ return listQueuedExpireJobs(client).stream()+ .filter(j -> j.isBatch && !j.picked && j.spec.tableIds().size() < batchCapacity)+ .filter(j -> catalogName.equals(j.catalog))+ .min(Comparator.comparingLong(j -> j.batchId));+ }++ private static List<QueuedExpireJob> listQueuedExpireJobs(SchedulerClient client) {+ List<QueuedExpireJob> open = new ArrayList<>();+ for (ScheduledExecution<MaintenanceJobSpec> execution :+ client.getScheduledExecutionsForTask(+ MaintenanceSchedulerPools.CRON_JOB, MaintenanceJobSpec.class)) {+ MaintenanceJobSpec data = execution.getData();+ if (data == null || !data.isValid() || !isExpireSnapshots(data)) {+ continue;+ }+ String instanceId = execution.getTaskInstance().getId();+ String catalog = data.getTasks().isEmpty() ? null : data.getTasks().get(0).catalogName();+ Optional<long[]> batch = MaintenanceTaskIds.parseCronBatch(instanceId);+ if (batch.isPresent()) {+ // [batchId, policyId]+ open.add(+ new QueuedExpireJob(+ TaskInstanceId.of(MaintenanceSchedulerPools.CRON_JOB, instanceId),+ true,+ batch.get()[0],+ batch.get()[1],+ execution.getExecutionTime(),+ data,+ catalog,+ execution.isPicked()));+ continue;+ }+ Optional<long[]> table = MaintenanceTaskIds.parseCronTable(instanceId);+ if (table.isPresent()) {+ // [tableId, policyId]+ open.add(+ new QueuedExpireJob(+ TaskInstanceId.of(MaintenanceSchedulerPools.CRON_JOB, instanceId),+ false,+ -1L,+ table.get()[1],+ execution.getExecutionTime(),+ data,+ catalog,+ execution.isPicked()));+ }+ }+ return open;+ }++ private static boolean isExpireSnapshots(MaintenanceJobSpec spec) {+ String expireType =+ MaintenanceJobTemplates.maintenanceType(Policy.BuiltInType.ICEBERG_SNAPSHOT_EXPIRATION)+ .orElseThrow();+ return spec.getTasks().stream().anyMatch(t -> expireType.equals(t.getMaintenanceType()));+ }++ /**+ * True when the table should not be scheduled again: a {@code table:} row already exists for this+ * policy, any queued snapshot-expiry cron-job (any policy) already covers the table, or a+ * non-expire {@code batch:} for this policy already includes the table.+ *+ * @param client cron-job scheduler client+ * @param tableId table entity id+ * @param policyId policy entity id+ * @return true when a queued cron-job already covers the table+ */+ public boolean isTableAlreadyQueued(SchedulerClient client, long tableId, long policyId) {+ if (client+ .getScheduledExecution(+ TaskInstanceId.of(+ MaintenanceSchedulerPools.CRON_JOB,+ MaintenanceTaskIds.forCronTable(tableId, policyId)))+ .isPresent()) {+ return true;+ }+ for (QueuedExpireJob job : listQueuedExpireJobs(client)) {+ if (job.spec.tableIds().contains(tableId)) {+ return true;+ }+ }+ for (ScheduledExecution<MaintenanceJobSpec> execution :+ client.getScheduledExecutionsForTask(+ MaintenanceSchedulerPools.CRON_JOB, MaintenanceJobSpec.class)) {+ Optional<long[]> parsed =+ MaintenanceTaskIds.parseCronBatch(execution.getTaskInstance().getId());+ // [batchId, policyId]+ if (parsed.isEmpty() || parsed.get()[1] != policyId) {+ continue;+ }+ MaintenanceJobSpec data = execution.getData();+ if (data != null+ && data.isValid()+ && !isExpireSnapshots(data)+ && data.tableIds().contains(tableId)) {+ return true;+ }+ }+ return false;+ }++ private static final class QueuedExpireJob {+ private final TaskInstanceId instanceId;+ private final boolean isBatch;+ private final long batchId;+ private final long policyId;+ private final Instant executionTime;+ private final MaintenanceJobSpec spec;+ private final String catalog;+ private final boolean picked;++ private QueuedExpireJob(+ TaskInstanceId instanceId,+ boolean isBatch,+ long batchId,+ long policyId,+ Instant executionTime,+ MaintenanceJobSpec spec,+ String catalog,+ boolean picked) {+ this.instanceId = instanceId;+ this.isBatch = isBatch;+ this.batchId = batchId;+ this.policyId = policyId;+ this.executionTime = executionTime;+ this.spec = spec;+ this.catalog = catalog;+ this.picked = picked;+ }+ }+}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/CronSubmitGate.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/CronSubmitGate.javadeleted file mode 100644index e2b42a7d75..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/CronSubmitGate.java+++ /dev/null@@ -1,34 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.job.cron;--/**- * In-flight check for cron-job pick. {@code minIntervalMs} was already applied at expand enqueue;- * pick only blocks on a live soft slot.- */-@FunctionalInterface-public interface CronSubmitGate {-- /**- * @param tableId table entity id- * @param policyId policy entity id- * @return true when that policy still holds a soft slot for the table- */- boolean isInFlight(long tableId, long policyId);-}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/MaintenanceCronSubmitPipeline.javasimilarity index 52%rename from plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceSparkSubmitPipeline.javarename to plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceCronSubmitPipeline.javaindex 8eda6f5b31..a54046b8c4 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/MaintenanceCronSubmitPipeline.java@@ -19,55 +19,61 @@package org.apache.gravitino.maintenance.scheduler.job.cron;import com.google.common.base.Preconditions;+import java.util.List;import java.util.Map;import java.util.Optional;import javax.annotation.Nullable;+import org.apache.gravitino.maintenance.MaintenanceActionManager;+import org.apache.gravitino.maintenance.MaintenanceJobManager;+import org.apache.gravitino.maintenance.model.OccupancyClaim;import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;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;+import org.apache.gravitino.maintenance.scheduler.job.MaintenanceJobConfBuilder;import org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/**- * Cron-pool control-plane submit (§5.2.2): consume enqueue-time {@link MaintenanceJobSpec} →- * in-flight gate → soft-slot claim → {@code runJob} → bind job id.+ * Cron-pool control-plane submit (§5.2.2): consume schedule-time {@link MaintenanceJobSpec} →+ * occupancy gate → soft-slot claim → {@link MaintenanceJobManager#submitAndBind}.** <p>Single-table {@code table:...} and snapshot-expiry {@code batch:...} rows share the same spec- * 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).+ * shape; each {@link Task} becomes one Spark job. After merge, a {@code table:} instance may still+ * hold multiple tasks (members live in {@code task_data}); occupancy uses each task's own {@code+ * policyId}. If any task is occupied, 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+ * <p>Does not sample metrics or evaluate trigger-expr (both run inside Spark from schedule-time* {@code rules} in task parameters).*/-public final class MaintenanceSparkSubmitPipeline {+public final class MaintenanceCronSubmitPipeline {- private static final Logger LOG = LoggerFactory.getLogger(MaintenanceSparkSubmitPipeline.class);+ private static final Logger LOG = LoggerFactory.getLogger(MaintenanceCronSubmitPipeline.class);- private final CronSubmitGate occupancyGate;+ private final MaintenanceActionManager actionManager;private final TableMaintenanceActionMetaService actionMetaService;- private final MaintenanceJobSubmitter jobSubmitter;+ private final MaintenanceJobManager jobManager;private final MaintenanceJobConfBuilder jobConfBuilder;private final long claimTimeoutMs;/**- * @param occupancyGate in-flight gate (minInterval already applied at enqueue)- * @param actionMetaService soft-slot claim / bind- * @param jobSubmitter Gravitino Job submitter- * @param jobConfBuilder resolves enqueue-time conf-key refs before {@code runJob}+ * @param actionManager occupancy checks (minInterval already applied at schedule)+ * @param actionMetaService soft-slot claim+ * @param jobManager runJob + bind (and orphan cancel)+ * @param jobConfBuilder resolves schedule-time conf-key refs before submit* @param claimTimeoutMs unbound claim TTL*/- public MaintenanceSparkSubmitPipeline(- CronSubmitGate occupancyGate,+ public MaintenanceCronSubmitPipeline(+ MaintenanceActionManager actionManager,TableMaintenanceActionMetaService actionMetaService,- MaintenanceJobSubmitter jobSubmitter,+ MaintenanceJobManager jobManager,MaintenanceJobConfBuilder jobConfBuilder,long claimTimeoutMs) {- this.occupancyGate = Preconditions.checkNotNull(occupancyGate);+ this.actionManager = Preconditions.checkNotNull(actionManager);this.actionMetaService = Preconditions.checkNotNull(actionMetaService);- this.jobSubmitter = Preconditions.checkNotNull(jobSubmitter);+ this.jobManager = Preconditions.checkNotNull(jobManager);this.jobConfBuilder = Preconditions.checkNotNull(jobConfBuilder);Preconditions.checkArgument(claimTimeoutMs > 0, "claimTimeoutMs must be positive");this.claimTimeoutMs = claimTimeoutMs;@@ -77,7 +83,7 @@ public final class MaintenanceSparkSubmitPipeline {* Runs one cron-job pick for {@code instanceId}.** @param instanceId db-scheduler cron-job instance id- * @param spec enqueue-time payload; required+ * @param spec schedule-time payload; required*/public void submit(String instanceId, @Nullable MaintenanceJobSpec spec) {if (spec == null || !spec.isValid()) {@@ -85,55 +91,47 @@ public final class MaintenanceSparkSubmitPipeline {return;}- Optional<long[]> tableIds = MaintenanceTaskIds.parseCronTable(instanceId);- Optional<long[]> batchIds = MaintenanceTaskIds.parseCronBatch(instanceId);- if (tableIds.isEmpty() && batchIds.isEmpty()) {+ Optional<long[]> tableInstance = MaintenanceTaskIds.parseCronTable(instanceId);+ Optional<long[]> batchInstance = MaintenanceTaskIds.parseCronBatch(instanceId);+ if (tableInstance.isEmpty() && batchInstance.isEmpty()) {LOG.warn("Skipping cron-job submit for unparseable instance id {}", instanceId);return;}- long policyId = spec.getTasks().get(0).getPolicyId();- // parseCron* returns [leftId, policyId]- long expectedPolicyId = tableIds.isPresent() ? tableIds.get()[1] : batchIds.get()[1];- if (policyId != expectedPolicyId) {- LOG.warn(- "Skipping cron-job submit for {}: spec policyId {} != instance policyId {}",- instanceId,- policyId,- expectedPolicyId);- return;- }- for (Task task : spec.getTasks()) {- if (task.getPolicyId() != policyId) {+ // Instance id is row identity; member tables live in task_data (a table: row may hold peers+ // after merge). Soft slot stays per task.policyId.+ if (tableInstance.isPresent()) {+ long instanceTableId = tableInstance.get()[0];+ long instancePolicyId = tableInstance.get()[1];+ Optional<Task> instanceTask =+ spec.getTasks().stream().filter(t -> t.getTableId() == instanceTableId).findFirst();+ if (instanceTask.isEmpty()) {LOG.warn(- "Skipping cron-job submit for {}: mixed policyIds in tasks ({} vs {})",+ "Skipping cron-job submit for {}: instance tableId {} missing from spec tables {}",instanceId,- policyId,- task.getPolicyId());+ instanceTableId,+ spec.tableIds());return;}- }- if (tableIds.isPresent()) {- long expectedTableId = tableIds.get()[0];- if (spec.getTasks().size() != 1 || spec.getTasks().get(0).getTableId() != expectedTableId) {+ if (instanceTask.get().getPolicyId() != instancePolicyId) {LOG.warn(- "Skipping cron-job submit for {}: spec tables {} do not match instance tableId {}",+ "Skipping cron-job submit for {}: instance task policyId {} != instance policyId {}",instanceId,- spec.tableIds(),- expectedTableId);+ instanceTask.get().getPolicyId(),+ instancePolicyId);return;}}- // 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.+ // minInterval was gated at expand schedule; pick only blocks on occupied soft slots. Any+ // occupied member aborts the whole pick so a batch row is not partially submitted then deleted.for (Task task : spec.getTasks()) {- if (occupancyGate.isInFlight(task.getTableId(), policyId)) {+ if (actionManager.isOccupied(task.getTableId(), task.getPolicyId())) {LOG.info(- "Skipping cron-job {} entirely (table {} in-flight for policy {})",+ "Skipping cron-job {} entirely (table {} occupied for policy {})",instanceId,task.getTableId(),- policyId);+ task.getPolicyId());return;}}@@ -167,48 +165,19 @@ public final class MaintenanceSparkSubmitPipeline {e.toString());return;}- runAndBind(spec.metalake(), jobConf, claim.get(), task.getTableId(), policyId);- }- private void runAndBind(- String metalake,- Map<String, String> jobConf,- OccupancyClaim claim,- long tableId,- long policyId) {- jobConf.put(MaintenanceJobTemplates.ACTION_IDS_KEY, Long.toString(claim.actionId()));- Long jobId = null;- try {- jobId =- jobSubmitter.runJob(- metalake, MaintenanceJobTemplates.ICEBERG_MAINTENANCE_TEMPLATE, jobConf);- actionMetaService.bindJobId(claim, jobId);- LOG.info("Submitted cron-job for table {} policy {} as job {}", tableId, policyId, jobId);- } catch (RuntimeException e) {- if (jobId != null) {- cancelJobQuietly(metalake, jobId);- }- releaseClaimQuietly(claim);- LOG.warn(- "Failed cron-job submit for table {} policy {}: {}", tableId, policyId, e.toString());- }- }-- private void cancelJobQuietly(String metalake, long jobId) {- try {- jobSubmitter.cancelJob(metalake, jobId);- } catch (RuntimeException cancelError) {- LOG.warn(- "Failed to cancel orphaned cron Spark job {} under metalake {} after bind failure",- jobId,- metalake,- cancelError);+ Optional<Long> jobId = jobManager.submitAndBind(spec.metalake(), jobConf, List.of(claim.get()));+ if (jobId.isPresent()) {+ LOG.info(+ "Submitted cron-job for table {} policy {} as job {}",+ task.getTableId(),+ policyId,+ jobId.get());}}private void releaseClaimQuietly(OccupancyClaim claim) {try {- // Fence on (id, created_at) + unbound so a concurrent reclaim's live claim is not deleted.if (!actionMetaService.deleteUnboundClaim(claim)) {LOG.debug("Occupancy claim {} created_at={} was not released (reclaimed or already bound)",@@ -217,7 +186,7 @@ public final class MaintenanceSparkSubmitPipeline {}} catch (RuntimeException releaseError) {LOG.warn(- "Failed to release occupancy claim {} after submit failure",+ "Failed to release occupancy claim {} after conf resolve failure",claim.actionId(),releaseError);}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceJobSubmitter.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceJobSubmitter.javadeleted file mode 100644index 4b87316f62..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceJobSubmitter.java+++ /dev/null@@ -1,73 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.job.cron;--import java.util.Map;-import org.apache.gravitino.GravitinoEnv;-import org.apache.gravitino.job.JobHandle;-import org.apache.gravitino.meta.JobEntity;--/**- * Submits a Gravitino Job for a cron-job callback (§5.2.2).- *- * <p>Production wiring uses {@link GravitinoEnv#jobOperationDispatcher()}; tests inject a fake.- */-public interface MaintenanceJobSubmitter {-- /**- * Runs a job template and returns the persisted job-run id for occupancy bind.- *- * @param metalake metalake name- * @param jobTemplateName built-in or registered job template name- * @param jobConf runtime job configuration (policy jobOptions + auth overlay)- * @return {@link JobEntity#id()}- */- long runJob(String metalake, String jobTemplateName, Map<String, String> jobConf);-- /**- * Best-effort cancel after a successful {@link #runJob} when occupancy bind fails.- *- * @param metalake metalake name- * @param jobId numeric Gravitino job run id- */- void cancelJob(String metalake, long jobId);-- /**- * @return submitter that delegates to {@link GravitinoEnv#jobOperationDispatcher()}- */- static MaintenanceJobSubmitter fromEnv() {- return new MaintenanceJobSubmitter() {- @Override- public long runJob(String metalake, String jobTemplateName, Map<String, String> jobConf) {- JobEntity job =- GravitinoEnv.getInstance()- .jobOperationDispatcher()- .runJob(metalake, jobTemplateName, jobConf);- return job.id();- }-- @Override- public void cancelJob(String metalake, long jobId) {- GravitinoEnv.getInstance()- .jobOperationDispatcher()- .cancelJob(metalake, JobHandle.JOB_ID_PREFIX + jobId);- }- };- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceTableRefs.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceTableRefs.javadeleted file mode 100644index 6b855c50b1..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceTableRefs.java+++ /dev/null@@ -1,169 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.job.cron;--import java.util.ArrayList;-import java.util.LinkedHashMap;-import java.util.List;-import java.util.Map;-import java.util.Objects;-import javax.annotation.Nullable;-import org.apache.gravitino.storage.relational.mapper.CatalogMetaMapper;-import org.apache.gravitino.storage.relational.mapper.SchemaMetaMapper;-import org.apache.gravitino.storage.relational.mapper.TableMetaMapper;-import org.apache.gravitino.storage.relational.po.CatalogPO;-import org.apache.gravitino.storage.relational.po.SchemaPO;-import org.apache.gravitino.storage.relational.po.TablePO;-import org.apache.gravitino.storage.relational.utils.SessionUtils;--/** Resolves table entity ids to catalog + {@code schema.table} identifiers for Spark jobConf. */-public final class MaintenanceTableRefs {-- private MaintenanceTableRefs() {}-- /**- * @param tableIds table entity ids (order preserved for known ids)- * @return resolved refs; unknown / incomplete rows are omitted- */- public static List<ResolvedTableRef> resolve(List<Long> tableIds) {- if (tableIds == null || tableIds.isEmpty()) {- return List.of();- }- List<TablePO> tables =- SessionUtils.getWithoutCommit(- TableMetaMapper.class, mapper -> mapper.listTablePOsByTableIds(tableIds));- if (tables == null || tables.isEmpty()) {- return List.of();- }- Map<Long, TablePO> byId = new LinkedHashMap<>();- for (TablePO table : tables) {- if (table != null && table.getTableId() != null) {- byId.put(table.getTableId(), table);- }- }-- Map<Long, String> catalogNames = new LinkedHashMap<>();- Map<Long, String> schemaNames = new LinkedHashMap<>();- List<ResolvedTableRef> resolved = new ArrayList<>();- for (Long tableId : tableIds) {- TablePO table = byId.get(tableId);- if (table == null || table.getTableName() == null) {- continue;- }- String catalogName = catalogName(table.getCatalogId(), catalogNames);- String schemaName = schemaName(table.getSchemaId(), schemaNames);- if (catalogName == null || schemaName == null) {- continue;- }- resolved.add(- new ResolvedTableRef(tableId, catalogName, schemaName + "." + table.getTableName()));- }- return resolved;- }-- @Nullable- private static String catalogName(Long catalogId, Map<Long, String> cache) {- if (catalogId == null) {- return null;- }- if (cache.containsKey(catalogId)) {- return cache.get(catalogId);- }- CatalogPO catalog =- SessionUtils.getWithoutCommit(- CatalogMetaMapper.class, mapper -> mapper.selectCatalogMetaById(catalogId));- String name = catalog == null ? null : catalog.getCatalogName();- cache.put(catalogId, name);- return name;- }-- @Nullable- private static String schemaName(Long schemaId, Map<Long, String> cache) {- if (schemaId == null) {- return null;- }- if (cache.containsKey(schemaId)) {- return cache.get(schemaId);- }- SchemaPO schema =- SessionUtils.getWithoutCommit(- SchemaMetaMapper.class, mapper -> mapper.selectSchemaMetaById(schemaId));- String name = schema == null ? null : schema.getSchemaName();- cache.put(schemaId, name);- return name;- }-- /** One table ready for Spark expire-snapshots jobConf. */- public static final class ResolvedTableRef {- private final long tableId;- private final String catalogName;- private final String tableIdentifier;-- /**- * @param tableId table entity id- * @param catalogName catalog name- * @param tableIdentifier {@code schema.table} Spark identifier- */- public ResolvedTableRef(long tableId, String catalogName, String tableIdentifier) {- this.tableId = tableId;- this.catalogName = catalogName;- this.tableIdentifier = tableIdentifier;- }-- /**- * @return table entity id- */- public long tableId() {- return tableId;- }-- /**- * @return catalog name- */- public String catalogName() {- return catalogName;- }-- /**- * @return {@code schema.table} (or nested-namespace) Spark identifier- */- public String tableIdentifier() {- return tableIdentifier;- }-- @Override- public boolean equals(Object o) {- if (this == o) {- return true;- }- if (!(o instanceof ResolvedTableRef)) {- return false;- }- ResolvedTableRef that = (ResolvedTableRef) o;- return tableId == that.tableId- && Objects.equals(catalogName, that.catalogName)- && Objects.equals(tableIdentifier, that.tableIdentifier);- }-- @Override- public int hashCode() {- return Objects.hash(tableId, catalogName, tableIdentifier);- }- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/PendingCronExpandOccupancyGate.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/PendingCronExpandOccupancyGate.javadeleted file mode 100644index 27923359c5..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/PendingCronExpandOccupancyGate.java+++ /dev/null@@ -1,51 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.job.cron;--import com.google.common.base.Preconditions;-import javax.sql.DataSource;-import org.apache.gravitino.maintenance.scheduler.policy.expand.ExpandOccupancyGate;--/**- * Decorates an {@link ExpandOccupancyGate} so tables already covered by a queued {@code cron-job}- * row are skipped and do not consume the expand batch budget.- */-public final class PendingCronExpandOccupancyGate implements ExpandOccupancyGate {-- private final ExpandOccupancyGate delegate;- private final DataSource dataSource;-- /**- * @param delegate in-flight / minInterval gate- * @param dataSource entity-store JDBC pool used by the cron scheduler table- */- public PendingCronExpandOccupancyGate(ExpandOccupancyGate delegate, DataSource dataSource) {- this.delegate = Preconditions.checkNotNull(delegate, "delegate");- this.dataSource = Preconditions.checkNotNull(dataSource, "dataSource");- }-- @Override- public boolean shouldSkip(long tableId, long policyId, long minIntervalMs, long nowMs) {- if (delegate.shouldSkip(tableId, policyId, minIntervalMs, nowMs)) {- return true;- }- return CronJobClient.isTableAlreadyQueued(- CronJobClient.schedulerClient(dataSource), tableId, policyId);- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/NearestMaintenancePolicyResolver.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/NearestMaintenancePolicyResolver.javanew file mode 100644index 0000000000..4076715dc6--- /dev/null+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/NearestMaintenancePolicyResolver.java@@ -0,0 +1,94 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.maintenance.scheduler.policy;++import java.util.ArrayList;+import java.util.List;+import java.util.Optional;+import java.util.TreeSet;+import org.apache.gravitino.EntityStore;+import org.apache.gravitino.MetadataObject;+import org.apache.gravitino.policy.ObjectPolicyResolver;+import org.apache.gravitino.policy.ObjectPolicyResolver.Match;+import org.apache.gravitino.policy.Policy;+import org.apache.gravitino.utils.MetadataObjectUtil;++/**+ * Picks the nearest maintenance policy of a given {@link Policy.BuiltInType} for a table.+ *+ * <p>Matching and effective-tag inheritance come from {@link ObjectPolicyResolver}. This class only+ * applies maintenance-specific nearest-level and same-level conflict rules over the returned+ * metadata-object sources.+ */+public class NearestMaintenancePolicyResolver {++ private final ObjectPolicyResolver objectPolicyResolver;++ /**+ * @param entityStore relational entity store+ */+ public NearestMaintenancePolicyResolver(EntityStore entityStore) {+ this(new ObjectPolicyResolver(entityStore));+ }++ /**+ * @param objectPolicyResolver shared object-policy resolver+ */+ NearestMaintenancePolicyResolver(ObjectPolicyResolver objectPolicyResolver) {+ this.objectPolicyResolver = objectPolicyResolver;+ }++ /**+ * Resolves the unique nearest winner policy id for {@code policyType}.+ *+ * @param metalake metalake name+ * @param table table metadata object+ * @param policyType maintenance built-in type+ * @return winner policy id, or empty when none match+ * @throws IllegalArgumentException when two or more same-type policies share the nearest level+ */+ public Optional<Long> resolveWinnerId(+ String metalake, MetadataObject table, Policy.BuiltInType policyType) {+ Match[] matches = objectPolicyResolver.resolveMatches(metalake, table);+ List<MetadataObject> chain = new ArrayList<>();+ chain.add(table);+ chain.addAll(MetadataObjectUtil.getParentMetadataObjects(table));+ for (MetadataObject level : chain) {+ TreeSet<Long> atLevel = new TreeSet<>();+ for (Match match : matches) {+ if (match.policy().policyType() != policyType) {+ continue;+ }+ if (match.sources().contains(level)) {+ atLevel.add(match.policy().id());+ }+ }+ if (atLevel.isEmpty()) {+ continue;+ }+ if (atLevel.size() > 1) {+ throw new IllegalArgumentException(+ String.format(+ "ambiguous %s policies %s on nearest level %s", policyType, atLevel, level));+ }+ return Optional.of(atLevel.first());+ }+ return Optional.empty();+ }+}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/NearestPolicyTableEnumerator.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/NearestPolicyTableEnumerator.javasimilarity index 80%rename from plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/NearestPolicyTableEnumerator.javarename to plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/NearestPolicyTableEnumerator.javaindex 938e54767b..a619916cd2 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/NearestPolicyTableEnumerator.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/NearestPolicyTableEnumerator.java@@ -16,8 +16,9 @@* specific language governing permissions and limitations* under the License.*/-package org.apache.gravitino.maintenance.scheduler.policy.expand;+package org.apache.gravitino.maintenance.scheduler.policy;+import com.google.common.base.Preconditions;import java.io.IOException;import java.io.UncheckedIOException;import java.util.ArrayList;@@ -27,11 +28,11 @@ import java.util.LinkedHashMap;import java.util.LinkedHashSet;import java.util.List;import java.util.Map;+import java.util.Optional;import java.util.Set;import java.util.function.Supplier;import javax.annotation.Nullable;import org.apache.gravitino.Entity;-import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.MetadataObject;import org.apache.gravitino.MetadataObjects;import org.apache.gravitino.NameIdentifier;@@ -43,6 +44,9 @@ import org.apache.gravitino.catalog.TableDispatcher;import org.apache.gravitino.exceptions.NoSuchCatalogException;import org.apache.gravitino.exceptions.NoSuchSchemaException;import org.apache.gravitino.exceptions.NoSuchTableException;+import org.apache.gravitino.maintenance.MaintenanceActionManager;+import org.apache.gravitino.maintenance.model.TableCandidate;+import org.apache.gravitino.maintenance.scheduler.job.cron.CronJobClient;import org.apache.gravitino.meta.GenericEntity;import org.apache.gravitino.meta.PolicyEntity;import org.apache.gravitino.meta.SchemaEntity;@@ -65,14 +69,33 @@ import org.slf4j.LoggerFactory;** <p>Flow: {@code policy → tags → tagged objects}. Catalog/schema tags expand to tables (including* hierarchical child schemas). A table is kept only when {@link NearestMaintenancePolicyResolver}- * picks this policy and {@link ExpandOccupancyGate} allows enqueue. Stops after {@code limit}- * accepted tables (skipped cooldown / in-flight tables do not count).+ * picks this policy and {@link ShouldSkipTable} allows schedule. Stops after {@code limit} accepted+ * tables (skipped cooldown / in-flight tables do not count).** <p>Catalog/schema expansion prefers live {@code listSchemas}/{@code listTables}, then imports* only missing entities with {@code loadSchema}/{@code loadTable}. On list failure, falls back to* the relational store. A direct table tag uses the stored table id as-is.*/-public final class NearestPolicyTableEnumerator implements PolicyTableEnumerator {+public final class NearestPolicyTableEnumerator {++ /**+ * Skip check used while scanning for schedulable tables.+ *+ * <p>Production expand skips when the action cannot start or a pending {@code cron-job} already+ * covers the table.+ */+ @FunctionalInterface+ interface ShouldSkipTable {++ /**+ * @param tableId table entity id+ * @param policyId policy entity id+ * @param minIntervalMs resolved cooldown for the policy type+ * @param nowMs current epoch millis+ * @return true when expand must not schedule a cron-job for this pair+ */+ boolean shouldSkip(long tableId, long policyId, long minIntervalMs, long nowMs);+ }private static final Logger LOG = LoggerFactory.getLogger(NearestPolicyTableEnumerator.class);@@ -84,24 +107,6 @@ public final class NearestPolicyTableEnumerator implements PolicyTableEnumerator@Nullable private final SchemaDispatcher schemaDispatcher;@Nullable private final TableDispatcher tableDispatcher;- /**- * Production wiring via relational singletons and {@link GravitinoEnv}.- *- * <p>Resolves {@link GravitinoEnv#entityStore()} lazily so scheduler pool startup can construct- * this enumerator before the env is fully initialized (unit tests). Dispatchers may be null until- * env init; expand then falls back to relational meta listing.- */- public NearestPolicyTableEnumerator() {- this(- PolicyTagRelService.getInstance(),- TagMetaService.getInstance(),- SchemaMetaService.getInstance(),- TableMetaService.getInstance(),- () -> new NearestMaintenancePolicyResolver(GravitinoEnv.getInstance().entityStore()),- GravitinoEnv.getInstance().internalSchemaDispatcher(),- GravitinoEnv.getInstance().internalTableDispatcher());- }-/*** Meta-only constructor for unit tests (no catalog list/import).*@@ -153,9 +158,45 @@ public final class NearestPolicyTableEnumerator implements PolicyTableEnumeratorthis.tableDispatcher = tableDispatcher;}- @Override- public List<ExpandTableCandidate> listTableIds(- PolicyEntity policy, int limit, ExpandOccupancyGate occupancyGate, long minIntervalMs) {+ /**+ * Lists up to {@code limit} tables that are nearest-policy winners and can start (not occupied /+ * cooling) and are not already covered by a queued cron-job.+ *+ * @param policy loaded policy+ * @param limit maximum schedulable candidates to return+ * @param minIntervalMs resolved cooldown for {@link MaintenanceActionManager#canStart}+ * @param actionManager occupancy / cooldown checks+ * @param cronJobClient pending cron-job coverage+ * @return distinct schedulable candidates, size at most {@code limit}+ */+ public List<TableCandidate> listTableIds(+ PolicyEntity policy,+ int limit,+ long minIntervalMs,+ MaintenanceActionManager actionManager,+ CronJobClient cronJobClient) {+ Preconditions.checkNotNull(actionManager);+ Preconditions.checkNotNull(cronJobClient);+ return listTableIds(+ policy,+ limit,+ (tableId, policyId, intervalMs, nowMs) ->+ !actionManager.canStart(tableId, policyId, intervalMs, nowMs)+ || cronJobClient.isTableAlreadyQueued(tableId, policyId),+ minIntervalMs);+ }++ /**+ * Lists up to {@code limit} tables that are nearest-policy winners and are not skipped.+ *+ * @param policy loaded policy+ * @param limit maximum schedulable candidates to return+ * @param shouldSkip skip occupied / cooling / already-queued tables while scanning+ * @param minIntervalMs resolved cooldown for {@link ShouldSkipTable#shouldSkip}+ * @return distinct schedulable candidates, size at most {@code limit}+ */+ List<TableCandidate> listTableIds(+ PolicyEntity policy, int limit, ShouldSkipTable shouldSkip, long minIntervalMs) {if (limit <= 0) {return List.of();}@@ -168,10 +209,9 @@ public final class NearestPolicyTableEnumerator implements PolicyTableEnumeratorScanState scan =new ScanState(metalake,- policy.id(),- policy.policyType(),+ policy,nearestResolverSupplier.get(),- occupancyGate,+ shouldSkip,minIntervalMs,System.currentTimeMillis(),new LinkedHashSet<>(),@@ -222,7 +262,7 @@ public final class NearestPolicyTableEnumerator implements PolicyTableEnumeratorswitch (objectType) {case TABLE:if (taggedObject.id() != null) {- tryEnqueueTable(taggedObject.id(), metadataObject, scan);+ tryScheduleTable(taggedObject.id(), metadataObject, scan);}break;case SCHEMA:@@ -353,7 +393,7 @@ public final class NearestPolicyTableEnumerator implements PolicyTableEnumeratorif (!importTableIfMissing(tableIdent, storedTables)) {continue;}- tryEnqueueTable(+ tryScheduleTable(storedTables.get(tableIdent.name()).id(),NameIdentifierUtil.toMetadataObject(tableIdent, Entity.EntityType.TABLE),scan);@@ -380,7 +420,7 @@ public final class NearestPolicyTableEnumerator implements PolicyTableEnumeratorif (scan.batchFull()) {return;}- tryEnqueueTable(+ tryScheduleTable(table.id(),NameIdentifierUtil.toMetadataObject(table.nameIdentifier(), Entity.EntityType.TABLE),scan);@@ -487,72 +527,77 @@ public final class NearestPolicyTableEnumerator implements PolicyTableEnumerator/*** Accepts {@code tableId} into the batch when this policy is the nearest winner and occupancy- * allows enqueue.+ * allows schedule.*/- private static void tryEnqueueTable(long tableId, MetadataObject tableObject, ScanState scan) {+ private static void tryScheduleTable(long tableId, MetadataObject tableObject, ScanState scan) {if (tableId <= 0 || !scan.visitedTableIds.add(tableId)) {return;}- NearestMaintenancePolicyResolver.Decision decision =- scan.nearestResolver.resolve(scan.metalake, tableObject, scan.policyType);- if (decision.kind() == NearestMaintenancePolicyResolver.Decision.Kind.CONFLICT) {+ Policy.BuiltInType policyType = scan.policy.policyType();+ final Optional<Long> winnerId;+ try {+ winnerId = scan.nearestResolver.resolveWinnerId(scan.metalake, tableObject, policyType);+ } catch (IllegalArgumentException e) {LOG.error(- "Skip table {} for maintenance type {}: ambiguous policies {} on nearest level {} ({})",+ "Skip table {} for maintenance type {}: {}",tableObject.fullName(),- scan.policyType,- decision.conflictingPolicyIds(),- decision.conflictLevel() == null ? "?" : decision.conflictLevel().type(),- decision.conflictLevel() == null ? "?" : decision.conflictLevel().fullName());- return;- }- if (decision.winnerPolicyId().orElse(-1L) != scan.policyId) {+ policyType,+ e.getMessage());return;}- MetadataObject winnerLevel = decision.winnerLevel();- if (winnerLevel == null) {+ if (winnerId.isEmpty() || winnerId.get().longValue() != scan.policy.id()) {return;}- if (scan.occupancyGate.shouldSkip(tableId, scan.policyId, scan.minIntervalMs, scan.nowMs)) {+ if (scan.shouldSkip.shouldSkip(tableId, scan.policy.id(), scan.minIntervalMs, scan.nowMs)) {LOG.debug(- "Skip cron-job enqueue for table {} policy {} (in-flight or within minIntervalMs={})",+ "Skip cron-job schedule for table {} policy {} (in-flight or within minIntervalMs={})",tableId,- scan.policyId,+ scan.policy.id(),scan.minIntervalMs);return;}- scan.acceptedByTableId.put(tableId, new ExpandTableCandidate(tableId, winnerLevel.type()));+ String fullName = tableObject.fullName();+ int dot = fullName.indexOf('.');+ if (dot <= 0 || dot >= fullName.length() - 1) {+ LOG.warn("Skip table {} with unusable name {}", tableId, fullName);+ return;+ }+ scan.acceptedByTableId.put(+ tableId,+ new TableCandidate(+ tableId,+ fullName.substring(0, dot),+ fullName.substring(dot + 1),+ List.of(scan.policy)));}/** Mutable progress for one {@link #listTableIds} call. */private static final class ScanState {private final String metalake;- private final long policyId;- private final Policy.BuiltInType policyType;+ private final PolicyEntity policy;private final NearestMaintenancePolicyResolver nearestResolver;- private final ExpandOccupancyGate occupancyGate;+ private final ShouldSkipTable shouldSkip;private final long minIntervalMs;private final long nowMs;private final Set<Long> visitedTableIds;- private final Map<Long, ExpandTableCandidate> acceptedByTableId;+ private final Map<Long, TableCandidate> acceptedByTableId;private final int limit;private ScanState(String metalake,- long policyId,- Policy.BuiltInType policyType,+ PolicyEntity policy,NearestMaintenancePolicyResolver nearestResolver,- ExpandOccupancyGate occupancyGate,+ ShouldSkipTable shouldSkip,long minIntervalMs,long nowMs,Set<Long> visitedTableIds,- Map<Long, ExpandTableCandidate> acceptedByTableId,+ Map<Long, TableCandidate> acceptedByTableId,int limit) {this.metalake = metalake;- this.policyId = policyId;- this.policyType = policyType;+ this.policy = policy;this.nearestResolver = nearestResolver;- this.occupancyGate = occupancyGate;+ this.shouldSkip = shouldSkip;this.minIntervalMs = minIntervalMs;this.nowMs = nowMs;this.visitedTableIds = visitedTableIds;diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/ExpandOccupancyGate.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/ExpandOccupancyGate.javadeleted file mode 100644index cb58553037..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/ExpandOccupancyGate.java+++ /dev/null@@ -1,38 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.policy.expand;--/**- * Gate used by expand before inserting a {@code cron-job} row.- *- * <p>Production expand wires {@link org.apache.gravitino.maintenance.occupancy.OccupancyGate} and- * may also skip when a pending {@code cron-job} row already covers the same table/policy pair.- */-@FunctionalInterface-public interface ExpandOccupancyGate {-- /**- * @param tableId table entity id- * @param policyId policy entity id- * @param minIntervalMs resolved cooldown for the policy type- * @param nowMs current epoch millis- * @return true when expand must not enqueue a cron-job for this pair- */- boolean shouldSkip(long tableId, long policyId, long minIntervalMs, long nowMs);-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/ExpandTableCandidate.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/ExpandTableCandidate.javadeleted file mode 100644index e44a7e5f7a..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/ExpandTableCandidate.java+++ /dev/null@@ -1,88 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.policy.expand;--import com.google.common.base.Preconditions;-import java.util.Objects;-import org.apache.gravitino.MetadataObject;--/**- * One enqueueable table after nearest-policy and occupancy gating, with the metadata level where- * the winning policy was selected.- */-public final class ExpandTableCandidate {-- private final long tableId;- private final MetadataObject.Type winnerLevel;-- /**- * @param tableId table entity id- * @param winnerLevel {@link MetadataObject.Type#TABLE}, {@link MetadataObject.Type#SCHEMA}, or- * {@link MetadataObject.Type#CATALOG}- */- public ExpandTableCandidate(long tableId, MetadataObject.Type winnerLevel) {- Preconditions.checkArgument(tableId > 0, "tableId must be positive");- Preconditions.checkNotNull(winnerLevel, "winnerLevel must not be null");- this.tableId = tableId;- this.winnerLevel = winnerLevel;- }-- /**- * @return table entity id- */- public long tableId() {- return tableId;- }-- /**- * @return level where the nearest winning policy was attached- */- public MetadataObject.Type winnerLevel() {- return winnerLevel;- }-- /**- * @return true when snapshot-expiry may pack this table into a {@code batch:...} cron-job- */- public boolean batchableForSnapshotExpiry() {- return winnerLevel == MetadataObject.Type.SCHEMA || winnerLevel == MetadataObject.Type.CATALOG;- }-- @Override- public boolean equals(Object o) {- if (this == o) {- return true;- }- if (!(o instanceof ExpandTableCandidate)) {- return false;- }- ExpandTableCandidate that = (ExpandTableCandidate) o;- return tableId == that.tableId && winnerLevel == that.winnerLevel;- }-- @Override- public int hashCode() {- return Objects.hash(tableId, winnerLevel);- }-- @Override- public String toString() {- return "ExpandTableCandidate{tableId=" + tableId + ", winnerLevel=" + winnerLevel + '}';- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/MaintenanceExpandSubmitPipeline.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/MaintenanceExpandSubmitPipeline.javanew file mode 100644index 0000000000..80522f2536--- /dev/null+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/MaintenanceExpandSubmitPipeline.java@@ -0,0 +1,53 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.maintenance.scheduler.policy.expand;++import com.google.common.base.Preconditions;+import java.time.Instant;+import java.util.Optional;++/**+ * Expand-pool pick handler (§5.2.1), parallel to {@code MaintenanceCronSubmitPipeline} / {@code+ * MaintenanceCommitSubmitPipeline}: consume a due {@code policy-expand} lease and return the next+ * expand due time (or empty to delete the lease).+ *+ * <p>Planning (policy gate, table enumeration, cron-job schedule) is {@link PolicyExpandPlanner}.+ * Does not submit Spark.+ */+public final class MaintenanceExpandSubmitPipeline {++ private final PolicyExpandPlanner planner;++ /**+ * @param planner expand pick planner+ */+ public MaintenanceExpandSubmitPipeline(PolicyExpandPlanner planner) {+ this.planner = Preconditions.checkNotNull(planner);+ }++ /**+ * Runs one expand pick for {@code policyId}.+ *+ * @param policyId expand task instance id+ * @return next due time when the expand row should stay, or empty to delete the row+ */+ public Optional<Instant> expand(long policyId) {+ return planner.plan(policyId);+ }+}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/NearestMaintenancePolicyResolver.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/NearestMaintenancePolicyResolver.javadeleted file mode 100644index 56f53efd6e..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/NearestMaintenancePolicyResolver.java+++ /dev/null@@ -1,184 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.policy.expand;--import java.util.ArrayList;-import java.util.List;-import java.util.Optional;-import java.util.TreeSet;-import javax.annotation.Nullable;-import org.apache.gravitino.EntityStore;-import org.apache.gravitino.MetadataObject;-import org.apache.gravitino.policy.ObjectPolicyResolver;-import org.apache.gravitino.policy.ObjectPolicyResolver.Match;-import org.apache.gravitino.policy.Policy;-import org.apache.gravitino.utils.MetadataObjectUtil;--/**- * Picks the nearest maintenance policy of a given {@link Policy.BuiltInType} for a table.- *- * <p>Matching and effective-tag inheritance come from {@link ObjectPolicyResolver}. This class only- * applies maintenance-specific nearest-level and same-level conflict rules over the returned- * metadata-object sources.- */-public class NearestMaintenancePolicyResolver {-- private final ObjectPolicyResolver objectPolicyResolver;-- /**- * @param entityStore relational entity store- */- public NearestMaintenancePolicyResolver(EntityStore entityStore) {- this(new ObjectPolicyResolver(entityStore));- }-- /**- * @param objectPolicyResolver shared object-policy resolver- */- NearestMaintenancePolicyResolver(ObjectPolicyResolver objectPolicyResolver) {- this.objectPolicyResolver = objectPolicyResolver;- }-- /**- * @param metalake metalake name- * @param table table metadata object- * @param policyType maintenance built-in type- * @return winner, none, or same-level conflict- */- public Decision resolve(String metalake, MetadataObject table, Policy.BuiltInType policyType) {- Match[] matches = objectPolicyResolver.resolveMatches(metalake, table);- List<MetadataObject> chain = new ArrayList<>();- chain.add(table);- chain.addAll(MetadataObjectUtil.getParentMetadataObjects(table));- for (MetadataObject level : chain) {- TreeSet<Long> atLevel = new TreeSet<>();- for (Match match : matches) {- if (match.policy().policyType() != policyType) {- continue;- }- if (match.sources().contains(level)) {- atLevel.add(match.policy().id());- }- }- if (atLevel.isEmpty()) {- continue;- }- if (atLevel.size() > 1) {- return Decision.conflict(level, new ArrayList<>(atLevel));- }- return Decision.winner(atLevel.first(), level);- }- return Decision.none();- }-- /** Result of nearest maintenance-policy resolution for one table and built-in type. */- public static final class Decision {-- /** Outcome of nearest-policy resolution. */- public enum Kind {- /** Exactly one matching policy on the nearest non-empty level. */- WINNER,- /** No matching policy on the inheritance chain. */- NONE,- /** Two or more same-type policies on the nearest non-empty level. */- CONFLICT- }-- private final Kind kind;- @Nullable private final Long winnerPolicyId;- @Nullable private final MetadataObject winnerLevel;- @Nullable private final MetadataObject conflictLevel;- private final List<Long> conflictingPolicyIds;-- private Decision(- Kind kind,- @Nullable Long winnerPolicyId,- @Nullable MetadataObject winnerLevel,- @Nullable MetadataObject conflictLevel,- List<Long> conflictingPolicyIds) {- this.kind = kind;- this.winnerPolicyId = winnerPolicyId;- this.winnerLevel = winnerLevel;- this.conflictLevel = conflictLevel;- this.conflictingPolicyIds = conflictingPolicyIds;- }-- /**- * @param policyId winning policy id- * @param level metadata level that produced the winner- * @return winner decision- */- public static Decision winner(long policyId, MetadataObject level) {- return new Decision(Kind.WINNER, policyId, level, null, List.of());- }-- /**- * @return none decision- */- public static Decision none() {- return new Decision(Kind.NONE, null, null, null, List.of());- }-- /**- * @param level metadata level that produced the conflict- * @param policyIds conflicting policy ids- * @return conflict decision- */- public static Decision conflict(MetadataObject level, List<Long> policyIds) {- return new Decision(Kind.CONFLICT, null, null, level, List.copyOf(policyIds));- }-- /**- * @return decision kind- */- public Kind kind() {- return kind;- }-- /**- * @return winning policy id when {@link Kind#WINNER}- */- public Optional<Long> winnerPolicyId() {- return Optional.ofNullable(winnerPolicyId);- }-- /**- * @return metadata level that produced the winner, or {@code null}- */- @Nullable- public MetadataObject winnerLevel() {- return winnerLevel;- }-- /**- * @return metadata level that produced the conflict, or {@code null}- */- @Nullable- public MetadataObject conflictLevel() {- return conflictLevel;- }-- /**- * @return conflicting policy ids when {@link Kind#CONFLICT}- */- public List<Long> conflictingPolicyIds() {- return conflictingPolicyIds;- }- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/PolicyExpandClient.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/PolicyExpandClient.javanew file mode 100644index 0000000000..751c4a9031--- /dev/null+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/PolicyExpandClient.java@@ -0,0 +1,292 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.maintenance.scheduler.policy.expand;++import com.github.kagkarlsson.scheduler.SchedulerClient;+import com.github.kagkarlsson.scheduler.exceptions.TaskInstanceCurrentlyExecutingException;+import com.github.kagkarlsson.scheduler.task.ExecutionComplete;+import com.github.kagkarlsson.scheduler.task.TaskInstance;+import com.github.kagkarlsson.scheduler.task.TaskInstanceId;+import com.github.kagkarlsson.scheduler.task.schedule.CronSchedule;+import com.github.kagkarlsson.scheduler.task.schedule.CronStyle;+import com.github.kagkarlsson.scheduler.task.schedule.Schedule;+import com.google.common.base.Preconditions;+import java.time.Instant;+import java.time.ZoneId;+import java.util.HashSet;+import java.util.Optional;+import java.util.Set;+import javax.sql.DataSource;+import org.apache.gravitino.maintenance.policy.MaintenancePolicyDefinitions;+import org.apache.gravitino.maintenance.scheduler.AutocommitDataSources;+import org.apache.gravitino.maintenance.scheduler.MaintenanceSchedulerPools;+import org.apache.gravitino.maintenance.scheduler.MaintenanceTaskIds;+import org.apache.gravitino.meta.PolicyEntity;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * Expand-pool counterpart of {@code CronJobClient} / {@code CommitJobClient}: writes {@code+ * policy-expand} lease rows into {@link MaintenanceSchedulerPools#EXPAND_TASKS_TABLE}.+ *+ * <p>The instance id is the policy id. {@link #sync} / {@link #align} decide from policy content+ * whether the row should exist; callers can also {@link #remove} by id. Fan-out into {@code+ * cron-job} rows is {@link PolicyExpandPlanner} on pick (via {@link+ * MaintenanceExpandSubmitPipeline}).+ *+ * <p>{@code timeTrigger} is a six-field Quartz cron. This class decides whether the expression has+ * a next fire time; policy content does not parse cron itself.+ *+ * <p>{@link #joiningCurrentTransaction()} writes through the open MyBatis session. The client must+ * not commit or close that connection, so the policy transaction and the expand row commit+ * together.+ */+public final class PolicyExpandClient {++ private static final Logger LOG = LoggerFactory.getLogger(PolicyExpandClient.class);++ /** Attempts while a pick still owns the expand row. */+ private static final int EXECUTING_ATTEMPTS = 10;++ /** Pause between attempts, so a short pick can finish inside the policy transaction. */+ private static final long EXECUTING_WAIT_MS = 50L;++ private final DataSource dataSource;++ private PolicyExpandClient(DataSource dataSource) {+ this.dataSource = dataSource;+ }++ /**+ * Opens a client that writes on the current thread's open SQL session.+ *+ * <p>The db-scheduler client is created on each call, because building it borrows a connection.+ * That connection is the open session, so this client must be used inside a policy transaction.+ *+ * @return client that inserts, moves, and deletes expand rows in the caller's transaction+ */+ public static PolicyExpandClient joiningCurrentTransaction() {+ return new PolicyExpandClient(AutocommitDataSources.joiningCurrentSession());+ }++ /**+ * Opens a client against the entity-store pool with JDBC autocommit forced on.+ *+ * <p>Used for post-commit reads and overdue writes such as {@link #scheduleAt}. The entity-store+ * pool often disables autocommit; without this wrap, SchedulerClient mutations would not commit+ * and the expand pool would never observe them.+ *+ * @param dataSource relational JDBC pool shared with the entity store+ * @return client that can read and write expand rows after the policy transaction commits+ */+ public static PolicyExpandClient forReads(DataSource dataSource) {+ return new PolicyExpandClient(AutocommitDataSources.wrap(dataSource));+ }++ private SchedulerClient client() {+ return SchedulerClient.Builder.create(dataSource, MaintenanceSchedulerPools.policyExpandTask())+ .tableName(MaintenanceSchedulerPools.EXPAND_TASKS_TABLE)+ .build();+ }++ /**+ * Aligns the expand row with a policy write (create / alter).+ *+ * <p>Enabled maintenance policies with a non-blank {@code timeTrigger} are scheduled at the next+ * fire. Disable, blank trigger, and non-maintenance content remove the row. An invalid cron+ * throws so the policy transaction rolls back.+ *+ * @param policy persisted policy+ */+ public void sync(PolicyEntity policy) {+ Preconditions.checkNotNull(policy, "policy");+ if (!MaintenancePolicyDefinitions.isMaintenance(policy.content())) {+ remove(policy.id());+ return;+ }+ String trigger = MaintenancePolicyDefinitions.timeTrigger(policy.content());+ if (!policy.enabled() || trigger == null || trigger.isBlank()) {+ remove(policy.id());+ return;+ }+ scheduleAt(policy.id(), nextExecution(trigger));+ }++ /**+ * Aligns the expand row during startup reconcile.+ *+ * <p>Same keep/remove rules as {@link #sync}, but preserves an overdue due so the expand pool can+ * catch up, skips when a future due already matches the cron, and removes the expand row (never+ * the policy) when the cron is invalid.+ *+ * @param policy persisted policy+ */+ public void align(PolicyEntity policy) {+ Preconditions.checkNotNull(policy, "policy");+ if (!MaintenancePolicyDefinitions.isMaintenance(policy.content())) {+ remove(policy.id());+ return;+ }+ String trigger = MaintenancePolicyDefinitions.timeTrigger(policy.content());+ if (!policy.enabled() || trigger == null || trigger.isBlank()) {+ remove(policy.id());+ return;+ }+ Instant expectedNext;+ try {+ expectedNext = nextExecution(trigger);+ } catch (IllegalArgumentException e) {+ remove(policy.id());+ LOG.error(+ "Cleared policy-expand task for policy id {} name {} with invalid timeTrigger; fix the policy content",+ policy.id(),+ policy.name(),+ e);+ return;+ }+ Optional<Instant> current = scheduledExecutionTime(policy.id());+ Instant now = Instant.now();+ if (current.isPresent() && current.get().isBefore(now)) {+ // Overdue: keep so db-scheduler can catch up after a restart.+ return;+ }+ if (current.isPresent() && current.get().equals(expectedNext)) {+ return;+ }+ scheduleAt(policy.id(), expectedNext);+ }++ /**+ * Inserts or moves the expand row to an explicit due time.+ *+ * @param policyId persisted policy id+ * @param due execution time to store+ */+ public void scheduleAt(long policyId, Instant due) {+ runDespiteExecution(+ () -> {+ TaskInstanceId instanceId = instanceId(policyId);+ boolean scheduled =+ client()+ .schedule(+ new TaskInstance<>(+ MaintenanceSchedulerPools.POLICY_EXPAND, instanceId.getId()),+ due,+ SchedulerClient.ScheduleOptions.WHEN_EXISTS_RESCHEDULE);+ if (!scheduled) {+ throw new IllegalStateException(+ "Failed to schedule policy-expand instance " + instanceId.getId() + " at " + due);+ }+ });+ }++ /**+ * Deletes the expand row when it is present.+ *+ * @param policyId persisted policy id+ */+ public void remove(long policyId) {+ TaskInstanceId instanceId = instanceId(policyId);+ runDespiteExecution(+ () -> {+ SchedulerClient scheduler = client();+ if (scheduler.getScheduledExecution(instanceId).isPresent()) {+ scheduler.cancel(instanceId);+ }+ });+ }++ /**+ * @param policyId persisted policy id+ * @return next execution time of the expand row, or empty when the row is absent+ */+ public Optional<Instant> scheduledExecutionTime(long policyId) {+ return client()+ .getScheduledExecution(instanceId(policyId))+ .map(execution -> execution.getExecutionTime());+ }++ /**+ * @return policy ids that currently have a {@code policy-expand} row+ */+ public Set<Long> scheduledPolicyIds() {+ Set<Long> ids = new HashSet<>();+ client()+ .fetchScheduledExecutionsForTask(+ MaintenanceSchedulerPools.POLICY_EXPAND,+ Void.class,+ execution -> {+ MaintenanceTaskIds.parseExpandPolicy(execution.getTaskInstance().getId())+ .ifPresent(ids::add);+ });+ return ids;+ }++ /**+ * Next fire time for a Quartz cron, strictly after now.+ *+ * @param timeTrigger six-field Quartz cron expression+ * @return next execution instant in the system default zone+ */+ public static Instant nextExecution(String timeTrigger) {+ CronSchedule schedule = new CronSchedule(timeTrigger, ZoneId.systemDefault(), CronStyle.QUARTZ);+ Instant next = schedule.getNextExecutionTime(ExecutionComplete.simulatedSuccess(Instant.now()));+ if (next == null || Schedule.NEVER.equals(next)) {+ throw new IllegalArgumentException("timeTrigger has no next execution: " + timeTrigger);+ }+ return next;+ }++ private static TaskInstanceId instanceId(long policyId) {+ return TaskInstanceId.of(+ MaintenanceSchedulerPools.POLICY_EXPAND, MaintenanceTaskIds.forExpandPolicy(policyId));+ }++ /**+ * Retries while db-scheduler reports the expand row as picked.+ *+ * <p>A pick rejects both reschedule and cancel. Failing the attempt here would roll the policy+ * transaction back. After the retry window the in-flight expand pick applies the committed policy+ * on its own completion path.+ *+ * @param action one scheduler write+ */+ private static void runDespiteExecution(Runnable action) {+ for (int attempt = 1; ; attempt++) {+ try {+ action.run();+ return;+ } catch (TaskInstanceCurrentlyExecutingException e) {+ if (attempt >= EXECUTING_ATTEMPTS) {+ LOG.warn(+ "policy-expand row is still executing; leaving the in-flight pick to apply the policy",+ e);+ return;+ }+ try {+ Thread.sleep(EXECUTING_WAIT_MS);+ } catch (InterruptedException interrupted) {+ Thread.currentThread().interrupt();+ e.addSuppressed(interrupted);+ throw e;+ }+ }+ }+ }+}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/PolicyExpandCrons.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/PolicyExpandCrons.javadeleted file mode 100644index 4a6fedbfce..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/PolicyExpandCrons.java+++ /dev/null@@ -1,47 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.policy.expand;--import com.github.kagkarlsson.scheduler.task.ExecutionComplete;-import com.github.kagkarlsson.scheduler.task.schedule.CronSchedule;-import com.github.kagkarlsson.scheduler.task.schedule.CronStyle;-import com.github.kagkarlsson.scheduler.task.schedule.Schedule;-import java.time.Instant;-import java.time.ZoneId;--/** Quartz cron helpers for {@code policy-expand} next-due calculation. */-final class PolicyExpandCrons {-- private PolicyExpandCrons() {}-- /**- * Next fire time for a Quartz cron, strictly after now.- *- * @param timeTrigger six-field Quartz cron expression- * @return next execution instant in the system default zone- */- static Instant nextExecution(String timeTrigger) {- CronSchedule schedule = new CronSchedule(timeTrigger, ZoneId.systemDefault(), CronStyle.QUARTZ);- Instant next = schedule.getNextExecutionTime(ExecutionComplete.simulatedSuccess(Instant.now()));- if (next == null || Schedule.NEVER.equals(next)) {- throw new IllegalArgumentException("timeTrigger has no next execution: " + timeTrigger);- }- return next;- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/PolicyExpandPipeline.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/PolicyExpandPipeline.javadeleted file mode 100644index dfe57ac7d0..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/PolicyExpandPipeline.java+++ /dev/null@@ -1,196 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.policy.expand;--import com.google.common.base.Preconditions;-import java.time.Instant;-import java.util.List;-import java.util.Optional;-import java.util.function.Function;-import javax.annotation.Nullable;-import org.apache.gravitino.Config;-import org.apache.gravitino.maintenance.policy.MaintenanceMinIntervalConfigs;-import org.apache.gravitino.maintenance.policy.MaintenancePolicyDefinitions;-import org.apache.gravitino.maintenance.scheduler.job.cron.CronJobClient;-import org.apache.gravitino.meta.PolicyEntity;-import org.apache.gravitino.policy.ExecutablePolicyContent;-import org.apache.gravitino.policy.Policy;-import org.apache.gravitino.policy.PolicyContent;-import org.apache.gravitino.storage.relational.service.PolicyMetaService;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--/**- * Expands a due {@code policy-expand} lease into one-shot {@code cron-job} rows (§5.2.1).- *- * <p>Does not submit Spark. Returns the next expand due time, or empty when the expand row should- * be removed (missing / disabled / blank trigger / non-maintenance).- *- * <p>Enumeration fills up to {@code enqueueBatchSize} tables that pass nearest-policy and {@code- * minIntervalMs} / in-flight gating (policy content → server conf → code default).- */-public final class PolicyExpandPipeline {-- private static final Logger LOG = LoggerFactory.getLogger(PolicyExpandPipeline.class);- private static final PolicyMetaService POLICY_SERVICE = PolicyMetaService.getInstance();-- private final Function<Long, Optional<PolicyEntity>> policyLoader;- private final PolicyTableEnumerator tableEnumerator;- private final CronJobClient cronJobClient;- private final ExpandOccupancyGate occupancyGate;- private final Config config;- private final int enqueueBatchSize;-- /**- * Loads policies through {@link PolicyMetaService}.- *- * @param tableEnumerator lists attached table ids- * @param cronJobClient writes cron-job rows- * @param occupancyGate in-flight / minInterval gate- * @param config gravitino server config for per-type minInterval fallbacks- * @param enqueueBatchSize max cron-jobs per expand pick- */- public PolicyExpandPipeline(- PolicyTableEnumerator tableEnumerator,- CronJobClient cronJobClient,- ExpandOccupancyGate occupancyGate,- Config config,- int enqueueBatchSize) {- this(- PolicyExpandPipeline::loadPolicy,- tableEnumerator,- cronJobClient,- occupancyGate,- config,- enqueueBatchSize);- }-- /**- * @param policyLoader loads the policy for the expand instance id- * @param tableEnumerator lists attached table ids- * @param cronJobClient writes cron-job rows- * @param occupancyGate in-flight / minInterval gate- * @param config gravitino server config for per-type minInterval fallbacks- * @param enqueueBatchSize max cron-jobs per expand pick- */- PolicyExpandPipeline(- Function<Long, Optional<PolicyEntity>> policyLoader,- PolicyTableEnumerator tableEnumerator,- CronJobClient cronJobClient,- ExpandOccupancyGate occupancyGate,- Config config,- int enqueueBatchSize) {- this.policyLoader = Preconditions.checkNotNull(policyLoader);- this.tableEnumerator = tableEnumerator;- this.cronJobClient = cronJobClient;- this.occupancyGate = occupancyGate;- this.config = config;- this.enqueueBatchSize = enqueueBatchSize;- }-- /**- * Runs one expand pick for {@code policyId}.- *- * @param policyId expand task instance id- * @return next due time when the expand row should stay, or empty to delete the row- */- public Optional<Instant> expand(long policyId) {- Optional<PolicyEntity> loaded = policyLoader.apply(policyId);- if (loaded.isEmpty()) {- LOG.info("Removing expand row for missing policy {}", policyId);- return Optional.empty();- }- PolicyEntity policy = loaded.get();- if (!policy.enabled() || !isMaintenance(policy.content())) {- LOG.info(- "Removing expand row for policy {} (enabled={}, maintenance={})",- policyId,- policy.enabled(),- isMaintenance(policy.content()));- return Optional.empty();- }- String timeTrigger = timeTrigger(policy.content());- if (timeTrigger == null || timeTrigger.isBlank()) {- LOG.info("Removing expand row for policy {} with blank timeTrigger", policyId);- return Optional.empty();- }-- // Resolve next due before any cron-job writes so a bad crontab cannot leave orphans.- final Instant nextDue;- try {- nextDue = PolicyExpandCrons.nextExecution(timeTrigger);- } catch (RuntimeException e) {- LOG.warn(- "Removing expand row for policy {} with invalid timeTrigger {}: {}",- policyId,- timeTrigger,- e.toString());- return Optional.empty();- }-- long minIntervalMs =- MaintenanceMinIntervalConfigs.resolve(- config, policy.policyType(), policyMinIntervalMs(policy.content()));- List<ExpandTableCandidate> toEnqueue =- tableEnumerator.listTableIds(policy, enqueueBatchSize, occupancyGate, minIntervalMs);- int scheduled = cronJobClient.enqueueNow(policy, toEnqueue, enqueueBatchSize);- LOG.info(- "Expanded policy {}: scheduled {} cron-job rows for {} tables (type={}, minIntervalMs={}); next expand due {}",- policyId,- scheduled,- toEnqueue.size(),- policy.policyType(),- minIntervalMs,- nextDue);- return Optional.of(nextDue);- }-- private static Optional<PolicyEntity> loadPolicy(long policyId) {- return Optional.ofNullable(POLICY_SERVICE.getPolicyById(policyId));- }-- private static boolean isMaintenance(@Nullable PolicyContent content) {- if (content == null) {- return false;- }- for (Policy.BuiltInType type : Policy.BuiltInType.values()) {- if (MaintenancePolicyDefinitions.isMaintenance(type)- && type.contentClass().isInstance(content)) {- return true;- }- }- return false;- }-- @Nullable- private static String timeTrigger(@Nullable PolicyContent content) {- if (!(content instanceof ExecutablePolicyContent)) {- return null;- }- return ((ExecutablePolicyContent) content).executionSpec().timeTrigger();- }-- @Nullable- private static Long policyMinIntervalMs(@Nullable PolicyContent content) {- if (!(content instanceof ExecutablePolicyContent)) {- return null;- }- return ((ExecutablePolicyContent) content).executionSpec().minIntervalMs();- }-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/PolicyExpandPlanner.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/PolicyExpandPlanner.javanew file mode 100644index 0000000000..3c07b7c4fa--- /dev/null+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/PolicyExpandPlanner.java@@ -0,0 +1,139 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.maintenance.scheduler.policy.expand;++import com.google.common.base.Preconditions;+import java.time.Instant;+import java.util.List;+import java.util.Optional;+import org.apache.gravitino.Config;+import org.apache.gravitino.maintenance.MaintenanceActionManager;+import org.apache.gravitino.maintenance.model.TableCandidate;+import org.apache.gravitino.maintenance.policy.MaintenanceMinIntervalConfigs;+import org.apache.gravitino.maintenance.policy.MaintenancePolicyDefinitions;+import org.apache.gravitino.maintenance.scheduler.job.cron.CronJobClient;+import org.apache.gravitino.maintenance.scheduler.policy.NearestPolicyTableEnumerator;+import org.apache.gravitino.meta.PolicyEntity;+import org.apache.gravitino.policy.ExecutablePolicyContent;+import org.apache.gravitino.storage.relational.service.PolicyMetaService;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * Plans one {@code policy-expand} pick (§5.2.1): decide whether the lease stays, enumerate+ * nearest-policy tables, and schedule {@code cron-job} rows via {@link CronJobClient}.+ *+ * <p>Parallel to {@code CronJobPlanner} / {@code CommitJobPlanner}. Expand planning runs at pick+ * time (unlike cron/commit, which plan at schedule). Does not submit Spark.+ */+public final class PolicyExpandPlanner {++ private static final Logger LOG = LoggerFactory.getLogger(PolicyExpandPlanner.class);++ private final NearestPolicyTableEnumerator tableEnumerator;+ private final CronJobClient cronJobClient;+ private final MaintenanceActionManager actionManager;+ private final Config config;+ private final int scheduleBatchSize;+ private final PolicyMetaService policyMetaService;++ /**+ * @param tableEnumerator lists attached table ids+ * @param cronJobClient writes cron-job rows+ * @param actionManager decides whether a maintenance action can start+ * @param config gravitino server config for per-type minInterval fallbacks+ * @param scheduleBatchSize max cron-jobs per expand pick+ * @param policyMetaService policy lookup+ */+ public PolicyExpandPlanner(+ NearestPolicyTableEnumerator tableEnumerator,+ CronJobClient cronJobClient,+ MaintenanceActionManager actionManager,+ Config config,+ int scheduleBatchSize,+ PolicyMetaService policyMetaService) {+ this.tableEnumerator = Preconditions.checkNotNull(tableEnumerator);+ this.cronJobClient = Preconditions.checkNotNull(cronJobClient);+ this.actionManager = Preconditions.checkNotNull(actionManager);+ this.config = Preconditions.checkNotNull(config);+ this.scheduleBatchSize = scheduleBatchSize;+ this.policyMetaService = Preconditions.checkNotNull(policyMetaService);+ }++ /**+ * Plans one expand pick for {@code policyId}.+ *+ * @param policyId expand task instance id+ * @return next due time when the expand row should stay, or empty to delete the row+ */+ public Optional<Instant> plan(long policyId) {+ PolicyEntity policy = policyMetaService.getPolicyById(policyId);+ if (policy == null) {+ LOG.info("Removing expand row for missing policy {}", policyId);+ return Optional.empty();+ }+ if (!policy.enabled() || !MaintenancePolicyDefinitions.isMaintenance(policy.content())) {+ LOG.info(+ "Removing expand row for policy {} (enabled={}, maintenance={})",+ policyId,+ policy.enabled(),+ MaintenancePolicyDefinitions.isMaintenance(policy.content()));+ return Optional.empty();+ }+ String timeTrigger = MaintenancePolicyDefinitions.timeTrigger(policy.content());+ if (timeTrigger == null || timeTrigger.isBlank()) {+ LOG.info("Removing expand row for policy {} with blank timeTrigger", policyId);+ return Optional.empty();+ }++ // Resolve next due before any cron-job writes so a bad crontab cannot leave orphans.+ final Instant nextDue;+ try {+ nextDue = PolicyExpandClient.nextExecution(timeTrigger);+ } catch (RuntimeException e) {+ LOG.warn(+ "Removing expand row for policy {} with invalid timeTrigger {}: {}",+ policyId,+ timeTrigger,+ e.toString());+ return Optional.empty();+ }++ Long contentMinInterval = null;+ if (policy.content() instanceof ExecutablePolicyContent) {+ contentMinInterval =+ ((ExecutablePolicyContent) policy.content()).executionSpec().minIntervalMs();+ }+ long minIntervalMs =+ MaintenanceMinIntervalConfigs.resolve(config, policy.policyType(), contentMinInterval);+ List<TableCandidate> toSchedule =+ tableEnumerator.listTableIds(+ policy, scheduleBatchSize, minIntervalMs, actionManager, cronJobClient);+ int scheduled = cronJobClient.scheduleNow(policy, toSchedule, scheduleBatchSize);+ LOG.info(+ "Expanded policy {}: scheduled {} cron-job rows for {} tables (type={}, minIntervalMs={}); next expand due {}",+ policyId,+ scheduled,+ toSchedule.size(),+ policy.policyType(),+ minIntervalMs,+ nextDue);+ return Optional.of(nextDue);+ }+}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/PolicyTableEnumerator.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/PolicyTableEnumerator.javadeleted file mode 100644index 11f1f742d4..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/policy/expand/PolicyTableEnumerator.java+++ /dev/null@@ -1,47 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.policy.expand;--import java.util.List;-import org.apache.gravitino.meta.PolicyEntity;--/**- * Lists enqueueable tables that a maintenance policy should expand into cron jobs.- *- * <p>Implementations expand tag-bound catalog/schema/table attachments and keep tables for which- * the policy is the nearest winner of its {@link org.apache.gravitino.policy.Policy.BuiltInType}.- * {@code limit} is the max number of <em>enqueueable</em> tables after occupancy / cooldown gating.- * Each candidate carries the winner attachment level for snapshot-expiry batching.- */-@FunctionalInterface-public interface PolicyTableEnumerator {-- /**- * Lists up to {@code limit} tables that are nearest-policy winners and pass {@code- * occupancyGate}.- *- * @param policy loaded policy- * @param limit maximum enqueueable candidates to return- * @param occupancyGate skip in-flight / cooldown / already-queued tables while scanning- * @param minIntervalMs resolved cooldown for {@link ExpandOccupancyGate#shouldSkip}- * @return distinct enqueueable candidates, size at most {@code limit}- */- List<ExpandTableCandidate> listTableIds(- PolicyEntity policy, int limit, ExpandOccupancyGate occupancyGate, long minIntervalMs);-}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/MetalakeNames.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/MetalakeNames.javadeleted file mode 100644index c01cfa4a18..0000000000--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/storage/MetalakeNames.java+++ /dev/null@@ -1,54 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.storage;--import java.util.Collections;-import java.util.List;-import javax.annotation.Nullable;-import org.apache.gravitino.storage.relational.mapper.MetalakeMetaMapper;-import org.apache.gravitino.storage.relational.mapper.TableMetaMapper;-import org.apache.gravitino.storage.relational.po.MetalakePO;-import org.apache.gravitino.storage.relational.po.TablePO;-import org.apache.gravitino.storage.relational.utils.SessionUtils;--/** Resolves metalake names for maintenance entity ids. */-public final class MetalakeNames {-- private MetalakeNames() {}-- /**- * @param tableId table entity id- * @return metalake name owning the table, or {@code null} when the table/metalake is missing- */- @Nullable- public static String forTableId(long tableId) {- List<TablePO> tables =- SessionUtils.getWithoutCommit(- TableMetaMapper.class,- mapper -> mapper.listTablePOsByTableIds(Collections.singletonList(tableId)));- if (tables == null || tables.isEmpty()) {- return null;- }- MetalakePO metalake =- SessionUtils.getWithoutCommit(- MetalakeMetaMapper.class,- mapper -> mapper.selectMetalakeMetaById(tables.get(0).getMetalakeId()));- return metalake == null ? null : metalake.getMetalakeName();- }-}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 3c08b1bdeb..a4fdb79243 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@@ -30,7 +30,7 @@ import java.util.Locale;import java.util.Objects;import java.util.Optional;import javax.annotation.Nullable;-import org.apache.gravitino.maintenance.TableMaintenanceConfig;+import org.apache.gravitino.maintenance.model.OccupancyClaim;import org.apache.gravitino.maintenance.storage.mapper.TableMaintenanceActionMapper;import org.apache.gravitino.maintenance.storage.po.TableMaintenanceActionPO;import org.apache.gravitino.metrics.Monitored;@@ -67,8 +67,10 @@ public class TableMaintenanceActionMetaService {* 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 cancel orphaned Spark- * work when bind fails so a crash between submit and bind cannot leave dual runners.+ * runJob} that already succeeded. {@link+ * org.apache.gravitino.maintenance.MaintenanceActionManager} / 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@@ -175,36 +177,6 @@ public class TableMaintenanceActionMetaService {return claims;}- /**- * Acquires an unbound claim using {@link TableMaintenanceConfig#claimTimeoutMs()} or fails.- *- * @param tableId table entity id- * @param policyId policy entity id- * @param config maintenance config supplying the unbound claim TTL- * @return acquired claim- */- public OccupancyClaim insertInFlight(long tableId, long policyId, TableMaintenanceConfig config) {- Preconditions.checkNotNull(config, "config must not be null");- return insertInFlight(tableId, policyId, config.claimTimeoutMs());- }-- /**- * Acquires an unbound claim with the given claim timeout or fails.- *- * @param tableId table entity id- * @param policyId policy entity id- * @param claimTimeoutMs unbound claim TTL- * @return acquired claim- */- @Monitored(- metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,- baseMetricName = "insertTableMaintenanceAction")- public OccupancyClaim insertInFlight(long tableId, long policyId, long claimTimeoutMs) {- Optional<OccupancyClaim> acquired = tryAcquireInFlight(tableId, policyId, claimTimeoutMs);- Preconditions.checkState(acquired.isPresent(), "failed to acquire unbound occupancy claim");- return acquired.get();- }-/*** Binds {@code job_run_meta.job_run_id} after a successful {@code runJob}. Does not release the* soft slot ({@code finished_at} stays {@code 0} until {@link #markFinished}).@@ -220,7 +192,7 @@ public class TableMaintenanceActionMetaService {* <p>This CAS does <em>not</em> prevent duplicate Spark submissions if {@code runJob} already* ran; see {@link #tryAcquireInFlight} submit contract.*- * @param claim claim returned by {@link #tryAcquireInFlight} / {@link #insertInFlight}+ * @param claim claim returned by {@link #tryAcquireInFlight}* @param jobId Gravitino job run id*/@Monitored(@@ -247,43 +219,6 @@ public class TableMaintenanceActionMetaService {"expected to bind job_id on exactly one in-flight action, updated=%s", updated));}- /**- * Lazy-binds {@code jobId} onto the unbound in-flight claim for {@code (tableId, policyId)}.- *- * <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- * @param policyId policy entity id- * @param jobId Gravitino job run id- * @return {@code true} when a row is now bound to {@code jobId}- */- @Monitored(- metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,- baseMetricName = "bindTableMaintenanceActionJobIdIfUnbound")- public boolean bindJobIdIfUnbound(long tableId, long policyId, long jobId) {- TableMaintenanceActionPO already = getByJobIdAndTableIdAndPolicyId(jobId, tableId, policyId);- if (already != null && already.finishedAt() != null && already.finishedAt() == 0L) {- return true;- }- TableMaintenanceActionPO unbound =- SessionUtils.getWithoutCommit(- TableMaintenanceActionMapper.class,- mapper -> mapper.selectUnboundByTableAndPolicy(tableId, policyId));- if (unbound == null || unbound.actionId() == null || unbound.createdAt() == null) {- return false;- }- try {- bindJobId(new OccupancyClaim(unbound.actionId(), unbound.createdAt()), jobId);- return true;- } catch (IllegalStateException e) {- TableMaintenanceActionPO bound = getByJobIdAndTableIdAndPolicyId(jobId, tableId, policyId);- return bound != null && bound.finishedAt() != null && bound.finishedAt() == 0L;- }- }-/*** Binds the same Gravitino job run id to every claim from {@link #tryAcquireInFlightBatch} in one* transaction (commit-chain submit).@@ -401,31 +336,6 @@ public class TableMaintenanceActionMetaService {mapper -> mapper.selectByJobIdAndTableIdAndPolicyId(jobId, tableId, policyId));}- /**- * Convenience for single-table jobs. Prefer {@link #getByJobIdAndTableIdAndPolicyId}, {@link- * #getByJobIdAndTableId}, or {@link #listByJobId} when a job may cover multiple tables or- * policies.- *- * @param jobId Gravitino job run id- * @return the sole action row, or null when none- * @throws IllegalStateException when more than one table is bound to {@code jobId}- */- @Nullable- @Monitored(- metricsSource = GRAVITINO_RELATIONAL_STORE_METRIC_NAME,- baseMetricName = "getTableMaintenanceActionByJobId")- public TableMaintenanceActionPO getByJobId(long jobId) {- List<TableMaintenanceActionPO> rows = listByJobId(jobId);- if (rows.isEmpty()) {- return null;- }- Preconditions.checkState(- rows.size() == 1,- "multiple maintenance actions for job_id=%s; use getByJobIdAndTableIdAndPolicyId or listByJobId",- jobId);- return rows.get(0);- }-/*** Records the S0 metrics row id for a bound in-flight action.*@@ -550,7 +460,7 @@ public class TableMaintenanceActionMetaService {* concurrent abandon that closed this row leaves the successor soft slot intact (returns {@code* false}).*- * @param claim claim returned by {@link #tryAcquireInFlight} / {@link #insertInFlight}+ * @param claim claim returned by {@link #tryAcquireInFlight}* @return {@code true} when this claim lease was deleted*/@Monitored(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 937ec77d3d..66b593184c 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@@ -35,7 +35,7 @@ import javax.ws.rs.core.MediaType;import javax.ws.rs.core.Response;import org.apache.gravitino.Entity;import org.apache.gravitino.dto.responses.BaseResponse;-import org.apache.gravitino.maintenance.MaintenanceMetricsService;+import org.apache.gravitino.maintenance.MaintenanceMetricsManager;import org.apache.gravitino.maintenance.dto.requests.MaintenanceActionFinishRequest;import org.apache.gravitino.maintenance.dto.requests.MaintenanceActionMetricsRequest;import org.apache.gravitino.maintenance.web.TableMaintenanceRESTUtils;@@ -61,18 +61,18 @@ import org.apache.gravitino.server.authorization.annotations.AuthorizationMetada@Produces("application/vnd.gravitino.v1+json")public class TableMaintenanceActionOperations {- private final MaintenanceMetricsService metricsService;+ private final MaintenanceMetricsManager metricsManager;@Context private HttpServletRequest httpRequest;/*** Creates the resource.*- * @param metricsService metrics report domain service+ * @param metricsManager metrics report manager*/@Inject- public TableMaintenanceActionOperations(MaintenanceMetricsService metricsService) {- this.metricsService = metricsService;+ public TableMaintenanceActionOperations(MaintenanceMetricsManager metricsManager) {+ this.metricsManager = metricsManager;}/**@@ -101,7 +101,7 @@ public class TableMaintenanceActionOperations {httpRequest,() -> {requireBody(request);- metricsService.reportBeforeMetrics(metalake, actionId, finish, request);+ metricsManager.reportBeforeMetrics(metalake, actionId, finish, request);return TableMaintenanceRESTUtils.ok(new BaseResponse());},"report-before-metrics",@@ -135,7 +135,7 @@ public class TableMaintenanceActionOperations {httpRequest,() -> {requireBody(request);- metricsService.reportAfterMetrics(metalake, actionId, finish, request);+ metricsManager.reportAfterMetrics(metalake, actionId, finish, request);return TableMaintenanceRESTUtils.ok(new BaseResponse());},"report-after-metrics",@@ -165,7 +165,7 @@ public class TableMaintenanceActionOperations {httpRequest,() -> {requireBody(request);- metricsService.finishAction(metalake, actionId, request);+ metricsManager.finishAction(metalake, actionId, request);return TableMaintenanceRESTUtils.ok(new BaseResponse());},"finish",diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/web/rest/TableMaintenanceBinder.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/web/rest/TableMaintenanceBinder.javaindex 7125caadf8..b565d70b6e 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/web/rest/TableMaintenanceBinder.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/web/rest/TableMaintenanceBinder.java@@ -18,7 +18,7 @@*/package org.apache.gravitino.maintenance.web.rest;-import org.apache.gravitino.maintenance.MaintenanceMetricsService;+import org.apache.gravitino.maintenance.MaintenanceMetricsManager;import org.glassfish.hk2.utilities.binding.AbstractBinder;/** Registers table maintenance metrics REST dependencies for Jersey/HK2 injection. */@@ -26,6 +26,6 @@ public class TableMaintenanceBinder extends AbstractBinder {@Overrideprotected void configure() {- bind(MaintenanceMetricsService.create()).to(MaintenanceMetricsService.class);+ bind(MaintenanceMetricsManager.getInstance()).to(MaintenanceMetricsManager.class);}}diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/web/rest/feature/TableMaintenanceRESTFeature.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/web/rest/feature/TableMaintenanceRESTFeature.javaindex 0930ed3d61..d3c94ffd7a 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/web/rest/feature/TableMaintenanceRESTFeature.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/web/rest/feature/TableMaintenanceRESTFeature.java@@ -26,15 +26,26 @@ import javax.ws.rs.ext.Provider;import org.apache.gravitino.Config;import org.apache.gravitino.Configs;import org.apache.gravitino.GravitinoEnv;+import org.apache.gravitino.maintenance.MaintenanceActionManager;+import org.apache.gravitino.maintenance.MaintenanceJobManager;import org.apache.gravitino.maintenance.TableMaintenanceConfig;import org.apache.gravitino.maintenance.policy.PolicyExpandLifecycleHook;import org.apache.gravitino.maintenance.policy.PolicyExpandReconciler;-import org.apache.gravitino.maintenance.policy.PolicyExpandRegistrar;-import org.apache.gravitino.maintenance.scheduler.TableMaintenanceSchedulerPools;+import org.apache.gravitino.maintenance.scheduler.AutocommitDataSources;+import org.apache.gravitino.maintenance.scheduler.MaintenanceSchedulerPools;+import org.apache.gravitino.maintenance.scheduler.policy.NearestMaintenancePolicyResolver;+import org.apache.gravitino.maintenance.scheduler.policy.NearestPolicyTableEnumerator;+import org.apache.gravitino.maintenance.scheduler.policy.expand.PolicyExpandClient;+import org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService;import org.apache.gravitino.maintenance.web.rest.TableMaintenanceActionOperations;import org.apache.gravitino.maintenance.web.rest.TableMaintenanceBinder;import org.apache.gravitino.policy.hook.PolicyLifecycleHooks;-import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;+import org.apache.gravitino.storage.relational.service.MetalakeMetaService;+import org.apache.gravitino.storage.relational.service.PolicyMetaService;+import org.apache.gravitino.storage.relational.service.PolicyTagRelService;+import org.apache.gravitino.storage.relational.service.SchemaMetaService;+import org.apache.gravitino.storage.relational.service.TableMetaService;+import org.apache.gravitino.storage.relational.service.TagMetaService;import org.glassfish.jersey.server.monitoring.ApplicationEvent;import org.glassfish.jersey.server.monitoring.ApplicationEventListener;import org.glassfish.jersey.server.monitoring.RequestEvent;@@ -46,6 +57,9 @@ import org.slf4j.LoggerFactory;* Jersey feature that starts table maintenance db-scheduler pools and registers Spark action* callback REST when the extension package is enabled (§7.1 / §5.2.2).*+ * <p>This is the composition root for the TMS scheduler path: it resolves {@link GravitinoEnv} /+ * manager singletons and relational meta services, builds the table enumerator, and starts pools.+ ** <p>Registers {@link TableMaintenanceActionOperations} for sample/finish callbacks. Cron and* commit pools poll. The expand pool stays stopped, and a policy lifecycle hook writes the matching* {@code policy-expand} row on the same transaction as create, alter, enable, disable, and delete.@@ -65,7 +79,7 @@ public class TableMaintenanceRESTFeature implements Feature {/** Package name for {@link Configs#REST_API_EXTENSION_PACKAGES}. */public static final String EXTENSION_PACKAGE = TableMaintenanceRESTFeature.class.getPackageName();- private static final AtomicReference<TableMaintenanceSchedulerPools> SCHEDULER_POOLS =+ private static final AtomicReference<MaintenanceSchedulerPools> SCHEDULER_POOLS =new AtomicReference<>();private static final AtomicReference<PolicyExpandLifecycleHook> LIFECYCLE_HOOK =@@ -78,15 +92,37 @@ public class TableMaintenanceRESTFeature implements Feature {return true;}- Config config = GravitinoEnv.getInstance().config();+ GravitinoEnv env = GravitinoEnv.getInstance();+ Config config = env.config();if (!Configs.RELATIONAL_ENTITY_STORE.equals(config.get(Configs.ENTITY_STORE))) {throw new IllegalStateException("Table maintenance requires gravitino.entity.store = relational");}- DataSource dataSource = resolveEntityStoreDataSource();- TableMaintenanceSchedulerPools pools = new TableMaintenanceSchedulerPools();- pools.start(dataSource, TableMaintenanceConfig.from(config), config);+ TableMaintenanceConfig maintenanceConfig = TableMaintenanceConfig.from(config);+ PolicyMetaService policyMetaService = PolicyMetaService.getInstance();+ MetalakeMetaService metalakeMetaService = MetalakeMetaService.getInstance();+ NearestPolicyTableEnumerator tableEnumerator =+ new NearestPolicyTableEnumerator(+ PolicyTagRelService.getInstance(),+ TagMetaService.getInstance(),+ SchemaMetaService.getInstance(),+ TableMetaService.getInstance(),+ () -> new NearestMaintenancePolicyResolver(env.entityStore()),+ env.internalSchemaDispatcher(),+ env.internalTableDispatcher());++ DataSource dataSource = AutocommitDataSources.entityStore();+ MaintenanceSchedulerPools pools = new MaintenanceSchedulerPools();+ pools.start(+ dataSource,+ maintenanceConfig,+ config,+ MaintenanceJobManager.getInstance(),+ MaintenanceActionManager.getInstance(),+ TableMaintenanceActionMetaService.getInstance(),+ tableEnumerator,+ policyMetaService);if (!SCHEDULER_POOLS.compareAndSet(null, pools)) {pools.stop();LOG.warn("Table maintenance scheduler pools were started concurrently; discarded duplicate");@@ -95,7 +131,7 @@ public class TableMaintenanceRESTFeature implements Feature {try {registerLifecycleHook();- reconcileExistingPolicies();+ reconcileExistingPolicies(metalakeMetaService, policyMetaService);} catch (RuntimeException e) {unregisterLifecycleHook();SCHEDULER_POOLS.set(null);@@ -121,7 +157,7 @@ public class TableMaintenanceRESTFeature implements Feature {*/public static void stopSchedulers() {unregisterLifecycleHook();- TableMaintenanceSchedulerPools pools = SCHEDULER_POOLS.getAndSet(null);+ MaintenanceSchedulerPools pools = SCHEDULER_POOLS.getAndSet(null);if (pools != null) {pools.stop();LOG.info("Table maintenance scheduler pools stopped");@@ -130,15 +166,16 @@ public class TableMaintenanceRESTFeature implements Feature {private static void registerLifecycleHook() {PolicyExpandLifecycleHook hook =- new PolicyExpandLifecycleHook(PolicyExpandRegistrar.joiningCurrentTransaction());+ new PolicyExpandLifecycleHook(PolicyExpandClient.joiningCurrentTransaction());PolicyLifecycleHooks.register(hook);LIFECYCLE_HOOK.set(hook);}- private static void reconcileExistingPolicies() {- PolicyExpandRegistrar registrar = PolicyExpandRegistrar.joiningCurrentTransaction();- PolicyExpandLifecycleHook aligner = new PolicyExpandLifecycleHook(registrar);- new PolicyExpandReconciler(aligner, registrar).reconcileAll();+ private static void reconcileExistingPolicies(+ MetalakeMetaService metalakeMetaService, PolicyMetaService policyMetaService) {+ new PolicyExpandReconciler(+ PolicyExpandClient.joiningCurrentTransaction(), metalakeMetaService, policyMetaService)+ .reconcileAll();}private static void unregisterLifecycleHook() {@@ -148,19 +185,6 @@ public class TableMaintenanceRESTFeature implements Feature {}}- private static DataSource resolveEntityStoreDataSource() {- Object dataSource =- SqlSessionFactoryHelper.getInstance()- .getSqlSessionFactory()- .getConfiguration()- .getEnvironment()- .getDataSource();- if (!(dataSource instanceof DataSource)) {- throw new IllegalStateException("Entity store data source is not available");- }- return (DataSource) dataSource;- }-/*** Stops TMS scheduler pools when the Jersey application is destroyed (Jetty stop), before the* relational entity store shuts down.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/TestMaintenanceActionManager.javasimilarity index 73%rename from plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/occupancy/TestOccupancyGate.javarename to plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/TestMaintenanceActionManager.javaindex a8376c15da..1033732439 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/occupancy/TestOccupancyGate.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/TestMaintenanceActionManager.java@@ -16,7 +16,7 @@* specific language governing permissions and limitations* under the License.*/-package org.apache.gravitino.maintenance.occupancy;+package org.apache.gravitino.maintenance;import static org.apache.gravitino.maintenance.storage.TableMaintenanceActionTestUtils.expireClaim;@@ -25,8 +25,7 @@ import com.google.common.collect.ImmutableSet;import java.io.IOException;import org.apache.gravitino.MetadataObject;import org.apache.gravitino.Namespace;-import org.apache.gravitino.maintenance.TableMaintenanceConfig;-import org.apache.gravitino.maintenance.storage.service.OccupancyClaim;+import org.apache.gravitino.maintenance.model.OccupancyClaim;import org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService;import org.apache.gravitino.meta.PolicyEntity;import org.apache.gravitino.meta.TableEntity;@@ -35,7 +34,7 @@ import org.apache.gravitino.storage.relational.TestJDBCBackend;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.TestTemplate;-class TestOccupancyGate extends TestJDBCBackend {+class TestMaintenanceActionManager extends TestJDBCBackend {@TestTemplatevoid testUnboundClaimAndBoundSlotOccupyUntilMarkFinished() throws IOException {@@ -46,24 +45,26 @@ class TestOccupancyGate extends TestJDBCBackend {TableEntity table = createAndInsertTableEntity(Namespace.of(metalakeName, "cat", "sch"), "tbl");TableMaintenanceActionMetaService actions = TableMaintenanceActionMetaService.getInstance();- OccupancyGate gate = new OccupancyGate(actions);+ MaintenanceActionManager actionManager = new MaintenanceActionManager(actions);long policyId = insertPolicy(metalakeName, "occ-policy").id();- Assertions.assertFalse(gate.isInFlight(table.id(), policyId));+ Assertions.assertFalse(actionManager.isOccupied(table.id(), policyId));OccupancyClaim claim =- actions.insertInFlight(- table.id(), policyId, TableMaintenanceConfig.DEFAULT_CLAIM_TIMEOUT_MS);- Assertions.assertTrue(gate.isInFlight(table.id(), policyId));+ actions+ .tryAcquireInFlight(+ table.id(), policyId, TableMaintenanceConfig.DEFAULT_CLAIM_TIMEOUT_MS)+ .orElseThrow();+ Assertions.assertTrue(actionManager.isOccupied(table.id(), policyId));actions.bindJobId(claim, 7001L);- Assertions.assertTrue(gate.isInFlight(table.id(), policyId));- Assertions.assertTrue(- gate.shouldSkip(table.id(), policyId, 3_600_000L, System.currentTimeMillis()));+ Assertions.assertTrue(actionManager.isOccupied(table.id(), policyId));+ Assertions.assertFalse(+ actionManager.canStart(table.id(), policyId, 3_600_000L, System.currentTimeMillis()));long finishedAt = System.currentTimeMillis();actions.markFinished(claim.actionId(), finishedAt);- Assertions.assertFalse(gate.isInFlight(table.id(), policyId));+ Assertions.assertFalse(actionManager.isOccupied(table.id(), policyId));Assertions.assertEquals(finishedAt, actions.getByJobIdAndTableId(7001L, table.id()).finishedAt());}@@ -77,21 +78,23 @@ class TestOccupancyGate extends TestJDBCBackend {TableEntity table = createAndInsertTableEntity(Namespace.of(metalakeName, "cat", "sch"), "tbl");TableMaintenanceActionMetaService actions = TableMaintenanceActionMetaService.getInstance();- OccupancyGate gate = new OccupancyGate(actions);+ MaintenanceActionManager actionManager = new MaintenanceActionManager(actions);long policyId = insertPolicy(metalakeName, "occ-policy-2").id();OccupancyClaim claim =- actions.insertInFlight(- table.id(), policyId, TableMaintenanceConfig.DEFAULT_CLAIM_TIMEOUT_MS);+ actions+ .tryAcquireInFlight(+ table.id(), policyId, TableMaintenanceConfig.DEFAULT_CLAIM_TIMEOUT_MS)+ .orElseThrow();long jobId = 8001L;actions.bindJobId(claim, jobId);long finishedAt = 1_700_000_000_000L;actions.markFinished(claim.actionId(), finishedAt);Assertions.assertTrue(- gate.withinMinInterval(table.id(), policyId, 60_000L, finishedAt + 1_000L));+ actionManager.isCoolingDown(table.id(), policyId, 60_000L, finishedAt + 1_000L));Assertions.assertFalse(- gate.withinMinInterval(table.id(), policyId, 60_000L, finishedAt + 120_000L));+ actionManager.isCoolingDown(table.id(), policyId, 60_000L, finishedAt + 120_000L));}@TestTemplate@@ -104,19 +107,20 @@ class TestOccupancyGate extends TestJDBCBackend {TableMaintenanceActionMetaService actions = TableMaintenanceActionMetaService.getInstance();long claimTimeoutMs = TableMaintenanceConfig.DEFAULT_CLAIM_TIMEOUT_MS;- OccupancyGate gate = new OccupancyGate(actions, claimTimeoutMs);+ MaintenanceActionManager actionManager = new MaintenanceActionManager(actions, claimTimeoutMs);long policyId = insertPolicy(metalakeName, "occ-policy-3").id();- OccupancyClaim claim = actions.insertInFlight(table.id(), policyId, claimTimeoutMs);+ OccupancyClaim claim =+ actions.tryAcquireInFlight(table.id(), policyId, claimTimeoutMs).orElseThrow();Assertions.assertTrue(actions.hasLiveUnboundClaim(table.id(), policyId, claimTimeoutMs));- Assertions.assertTrue(gate.isInFlight(table.id(), policyId));+ Assertions.assertTrue(actionManager.isOccupied(table.id(), policyId));expireClaim(claim, claimTimeoutMs);- // Unbound TTL is evaluated in the DAO against the database clock, so OccupancyGate agrees with+ // Unbound TTL is evaluated in the DAO against the database clock, so the manager agrees with// acquire/reclaim even when the JVM clock would disagree (multi-node skew).Assertions.assertFalse(actions.hasLiveUnboundClaim(table.id(), policyId, claimTimeoutMs));- Assertions.assertFalse(gate.isInFlight(table.id(), policyId));+ Assertions.assertFalse(actionManager.isOccupied(table.id(), policyId));Assertions.assertTrue(actions.tryAcquireInFlight(table.id(), policyId, claimTimeoutMs).isPresent());Assertions.assertEquals(claim.actionId(), actions.getById(claim.actionId()).actionId());diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestCompactionInJobRecommender.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestCompactionInJobRecommender.javadeleted file mode 100644index e4b3662199..0000000000--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestCompactionInJobRecommender.java+++ /dev/null@@ -1,64 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.injob;--import static org.mockito.Mockito.mock;-import static org.mockito.Mockito.when;--import java.util.Collections;-import java.util.Optional;-import org.apache.gravitino.meta.PolicyEntity;-import org.apache.gravitino.policy.PolicyContents;-import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;--/** Unit tests for {@link CompactionInJobRecommender} (delegates to CompactionTriggerEvaluator). */-class TestCompactionInJobRecommender {-- @Test- void testRecommendUsesTriggerExpr() {- PolicyEntity policy = mock(PolicyEntity.class);- when(policy.content())- .thenReturn(PolicyContents.icebergDataCompaction(500L, 3L, Collections.emptyMap()));-- CompactionInJobRecommender recommender =- new CompactionInJobRecommender(policyId -> Optional.of(policy));- String metrics =- "{\"custom-data-file-mse\":600,\"custom-delete-file-number\":0,\"snapshotId\":1}";- Assertions.assertEquals(- RecommendDecision.MAINTAIN, recommender.recommend(1L, 7L, 99L, metrics));-- String below =- "{\"custom-data-file-mse\":100,\"custom-delete-file-number\":1,\"snapshotId\":1}";- Assertions.assertEquals(RecommendDecision.SKIP, recommender.recommend(1L, 7L, 99L, below));- }-- @Test- void testMissingMetricsSkips() {- PolicyEntity policy = mock(PolicyEntity.class);- when(policy.content()).thenReturn(PolicyContents.icebergDataCompaction());-- CompactionInJobRecommender recommender =- new CompactionInJobRecommender(policyId -> Optional.of(policy));- Assertions.assertEquals(- RecommendDecision.SKIP,- recommender.recommend(- 1L, 7L, 99L, "{\"snapshotId\":1,\"maintenanceType\":\"rewrite_data_files\"}"));- }-}diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestMetricsJson.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestMetricsJson.javadeleted file mode 100644index 7b3a328ff2..0000000000--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestMetricsJson.java+++ /dev/null@@ -1,44 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.injob;--import java.util.Map;-import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;--/** Unit tests for {@link MetricsJson}. */-class TestMetricsJson {-- @Test- void testParseNumericValues() {- Map<String, Object> metrics =- MetricsJson.parseNumericValues(- "{\"custom-data-file-mse\":1.5,\"custom-delete-file-number\":3,\"name\":\"x\"}");- Assertions.assertEquals(1.5D, metrics.get("custom-data-file-mse"));- Assertions.assertEquals(3L, metrics.get("custom-delete-file-number"));- Assertions.assertFalse(metrics.containsKey("name"));- }-- @Test- void testBlankOrInvalidReturnsEmpty() {- Assertions.assertTrue(MetricsJson.parseNumericValues(null).isEmpty());- Assertions.assertTrue(MetricsJson.parseNumericValues("").isEmpty());- Assertions.assertTrue(MetricsJson.parseNumericValues("not-json").isEmpty());- }-}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.javadeleted file mode 100644index 8247cf6768..0000000000--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestTableMaintenanceInJobPipeline.java+++ /dev/null@@ -1,98 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */--package org.apache.gravitino.maintenance.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;-import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.TestTemplate;--class TestTableMaintenanceInJobPipeline extends TestJDBCBackend {-- private static final String METRICS_JSON = "{\"mse\":1}";-- private TableMaintenanceActionMetaService actionMetaService;- private TableMaintenanceInJobPipeline maintainPipeline;- private TableMaintenanceInJobPipeline skipPipeline;-- @BeforeEach- void setUp() {- actionMetaService = TableMaintenanceActionMetaService.getInstance();- TableMaintenanceInJobSampler sampler =- new TableMaintenanceInJobSampler(- TableSnapshotMetricsMetaService.getInstance(), actionMetaService);- maintainPipeline =- new TableMaintenanceInJobPipeline(- sampler, (tableId, policyId, snapshotId, metricsJson) -> RecommendDecision.MAINTAIN);- skipPipeline =- new TableMaintenanceInJobPipeline(- sampler, (tableId, policyId, snapshotId, metricsJson) -> RecommendDecision.SKIP);- }-- @TestTemplate- void testContinuesWhenNoDriftAndRecommenderMaintains() {- long actionId = insertBoundAction(2001L, 10L, 20L);- InJobGateOutcome outcome =- maintainPipeline.gateCronJob(actionId, 10L, 20L, 100L, METRICS_JSON, () -> 100L);- Assertions.assertTrue(outcome.continueMaintenance());- Assertions.assertNull(outcome.stopReason());- }-- @TestTemplate- void testStopsOnDriftBeforeRecommend() {- long actionId = insertBoundAction(2002L, 11L, 21L);- InJobGateOutcome outcome =- maintainPipeline.gateCronJob(actionId, 11L, 21L, 200L, METRICS_JSON, () -> 201L);- Assertions.assertFalse(outcome.continueMaintenance());- Assertions.assertEquals(InJobGateOutcome.StopReason.SNAPSHOT_DRIFT, outcome.stopReason());- }-- @TestTemplate- void testStopsWhenRecommenderSkips() {- long actionId = insertBoundAction(2003L, 12L, 22L);- InJobGateOutcome outcome =- skipPipeline.gateCronJob(actionId, 12L, 22L, 300L, METRICS_JSON, () -> 300L);- Assertions.assertFalse(outcome.continueMaintenance());- Assertions.assertEquals(InJobGateOutcome.StopReason.RECOMMENDER_SKIP, outcome.stopReason());- }-- @TestTemplate- void testCommitChainTypeRecommendGate() {- InJobGateOutcome maintain =- maintainPipeline.gateCommitChainType(1L, 2L, 400L, METRICS_JSON, () -> 400L);- Assertions.assertTrue(maintain.continueMaintenance());-- InJobGateOutcome skip =- skipPipeline.gateCommitChainType(1L, 2L, 401L, METRICS_JSON, () -> 401L);- Assertions.assertEquals(InJobGateOutcome.StopReason.RECOMMENDER_SKIP, skip.stopReason());- }-- private long insertBoundAction(long jobId, long tableId, long policyId) {- OccupancyClaim claim =- actionMetaService.insertInFlight(- 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.javadeleted file mode 100644index d7451327b7..0000000000--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestTableMaintenanceInJobSampler.java+++ /dev/null@@ -1,108 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */--package org.apache.gravitino.maintenance.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;-import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.BeforeEach;-import org.junit.jupiter.api.TestTemplate;--class TestTableMaintenanceInJobSampler extends TestJDBCBackend {-- private static final String METRICS_JSON = "{\"mse\":3}";-- private TableMaintenanceInJobSampler sampler;- private TableMaintenanceActionMetaService actionMetaService;- private TableSnapshotMetricsMetaService metricsMetaService;-- @BeforeEach- void setUp() {- actionMetaService = TableMaintenanceActionMetaService.getInstance();- metricsMetaService = TableSnapshotMetricsMetaService.getInstance();- sampler = new TableMaintenanceInJobSampler(metricsMetaService, actionMetaService);- }-- @TestTemplate- void testCronJobSamplePersistsAndContinuesWhenNoDrift() {- long actionId = insertBoundAction(1001L, 1L, 2L);- InJobGateOutcome outcome =- sampler.sampleAndGateCronJob(actionId, 1L, 2L, 100L, METRICS_JSON, () -> 100L);-- Assertions.assertTrue(outcome.continueMaintenance());- Assertions.assertNull(outcome.stopReason());- long metricsId = actionMetaService.getById(actionId).beforeMetricsId();- TableSnapshotMetricsPO stored = metricsMetaService.getMetrics(metricsId);- Assertions.assertNotNull(stored);- Assertions.assertEquals(METRICS_JSON, stored.metricsValue());- Assertions.assertEquals(100L, stored.snapshotId());- }-- @TestTemplate- void testCronJobEndsEarlyWhenSnapshotDriftsAfterSample() {- long actionId = insertBoundAction(1002L, 3L, 4L);- InJobGateOutcome outcome =- 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());- long metricsId = actionMetaService.getById(actionId).beforeMetricsId();- Assertions.assertNotNull(metricsMetaService.getMetrics(metricsId));- }-- @TestTemplate- void testCronJobSampleRetryWithSameS0IsIdempotent() {- long actionId = insertBoundAction(1003L, 5L, 6L);- InJobGateOutcome first =- sampler.sampleAndGateCronJob(actionId, 5L, 6L, 300L, METRICS_JSON, () -> 300L);- long metricsId = actionMetaService.getById(actionId).beforeMetricsId();- InJobGateOutcome retry =- sampler.sampleAndGateCronJob(actionId, 5L, 6L, 300L, "{\"mse\":9}", () -> 300L);-- Assertions.assertTrue(first.continueMaintenance());- Assertions.assertTrue(retry.continueMaintenance());- Assertions.assertEquals(metricsId, actionMetaService.getById(actionId).beforeMetricsId());- Assertions.assertEquals(METRICS_JSON, metricsMetaService.getMetrics(metricsId).metricsValue());- }-- @TestTemplate- void testCommitChainTypeGateWithoutReSample() {- InJobGateOutcome ok = sampler.gateCommitChainType(300L, () -> 300L);- Assertions.assertTrue(ok.continueMaintenance());-- InJobGateOutcome drift = sampler.gateCommitChainType(300L, () -> 301L);- Assertions.assertFalse(drift.continueMaintenance());- Assertions.assertEquals(InJobGateOutcome.StopReason.SNAPSHOT_DRIFT, drift.stopReason());- }-- private long insertBoundAction(long jobId, long tableId, long policyId) {- OccupancyClaim claim =- actionMetaService.insertInFlight(- 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/TestTriggerExprInJobRecommender.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestTriggerExprInJobRecommender.javadeleted file mode 100644index 34a4019375..0000000000--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestTriggerExprInJobRecommender.java+++ /dev/null@@ -1,55 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.injob;--import static org.mockito.Mockito.mock;-import static org.mockito.Mockito.when;--import java.util.Optional;-import org.apache.gravitino.meta.PolicyEntity;-import org.apache.gravitino.policy.PolicyContents;-import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;--/** Unit tests for {@link TriggerExprInJobRecommender}. */-class TestTriggerExprInJobRecommender {-- @Test- void testOrphanTriggerTrueMaintains() {- PolicyEntity policy = mock(PolicyEntity.class);- when(policy.content()).thenReturn(PolicyContents.icebergOrphanFileRemoval());-- TriggerExprInJobRecommender recommender =- new TriggerExprInJobRecommender(policyId -> Optional.of(policy));- Assertions.assertEquals(- RecommendDecision.MAINTAIN, recommender.recommend(2L, 1L, 9L, "{}", policy));- }-- @Test- void testMissingTriggerExprDefaultsToSkip() {- // rewrite-manifests rules omit trigger-expr; recommender defaults the expression to false.- PolicyEntity policy = mock(PolicyEntity.class);- when(policy.content()).thenReturn(PolicyContents.icebergRewriteManifests());-- TriggerExprInJobRecommender recommender =- new TriggerExprInJobRecommender(policyId -> Optional.empty());- Assertions.assertEquals(- RecommendDecision.SKIP, recommender.recommend(2L, 1L, 9L, "{}", policy));- }-}diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestTypeDispatchingInJobRecommender.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestTypeDispatchingInJobRecommender.javadeleted file mode 100644index 836cea899c..0000000000--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/injob/TestTypeDispatchingInJobRecommender.java+++ /dev/null@@ -1,146 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.injob;--import static org.mockito.ArgumentMatchers.any;-import static org.mockito.ArgumentMatchers.anyLong;-import static org.mockito.ArgumentMatchers.anyString;-import static org.mockito.ArgumentMatchers.eq;-import static org.mockito.Mockito.mock;-import static org.mockito.Mockito.never;-import static org.mockito.Mockito.times;-import static org.mockito.Mockito.verify;-import static org.mockito.Mockito.when;--import java.util.Collections;-import java.util.Optional;-import java.util.function.Function;-import org.apache.gravitino.meta.PolicyEntity;-import org.apache.gravitino.policy.Policy;-import org.apache.gravitino.policy.PolicyContents;-import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;--/** Unit tests for {@link TypeDispatchingInJobRecommender}. */-class TestTypeDispatchingInJobRecommender {-- @Test- void testDispatchesCompaction() {- PolicyEntity policy = mock(PolicyEntity.class);- when(policy.policyType()).thenReturn(Policy.BuiltInType.ICEBERG_COMPACTION);- when(policy.content()).thenReturn(PolicyContents.icebergDataCompaction());- Function<Long, Optional<PolicyEntity>> policies = policiesReturning(policy);- InJobRecommender compaction = mock(InJobRecommender.class);- when(compaction.recommend(eq(2L), eq(1L), eq(9L), anyString(), eq(policy)))- .thenReturn(RecommendDecision.SKIP);- InJobRecommender triggerExpr = mock(InJobRecommender.class);- InJobRecommender placeholder = mock(InJobRecommender.class);-- TypeDispatchingInJobRecommender dispatcher =- new TypeDispatchingInJobRecommender(policies, compaction, triggerExpr, placeholder);- Assertions.assertEquals(RecommendDecision.SKIP, dispatcher.recommend(2L, 1L, 9L, "{\"x\":1}"));- verify(compaction).recommend(2L, 1L, 9L, "{\"x\":1}", policy);- verify(triggerExpr, never())- .recommend(anyLong(), anyLong(), anyLong(), anyString(), any(PolicyEntity.class));- verify(placeholder, never())- .recommend(anyLong(), anyLong(), anyLong(), anyString(), any(PolicyEntity.class));- }-- @Test- void testDispatchesAlwaysMaintainForExpirePlaceholder() {- PolicyEntity policy = mock(PolicyEntity.class);- when(policy.policyType()).thenReturn(Policy.BuiltInType.ICEBERG_SNAPSHOT_EXPIRATION);- when(policy.content()).thenReturn(PolicyContents.icebergSnapshotExpiration());- Function<Long, Optional<PolicyEntity>> policies = policiesReturning(policy);- InJobRecommender compaction = mock(InJobRecommender.class);- InJobRecommender triggerExpr = mock(InJobRecommender.class);- InJobRecommender placeholder = mock(InJobRecommender.class);- when(placeholder.recommend(eq(2L), eq(1L), eq(9L), anyString(), eq(policy)))- .thenReturn(RecommendDecision.MAINTAIN);-- TypeDispatchingInJobRecommender dispatcher =- new TypeDispatchingInJobRecommender(policies, compaction, triggerExpr, placeholder);- Assertions.assertEquals(RecommendDecision.MAINTAIN, dispatcher.recommend(2L, 1L, 9L, "{}"));- verify(placeholder).recommend(2L, 1L, 9L, "{}", policy);- verify(triggerExpr, never())- .recommend(anyLong(), anyLong(), anyLong(), anyString(), any(PolicyEntity.class));- verify(compaction, never())- .recommend(anyLong(), anyLong(), anyLong(), anyString(), any(PolicyEntity.class));- }-- @Test- void testProductionWiringExpirePlaceholderMaintainsDespiteTriggerFalse() {- PolicyEntity policy = mock(PolicyEntity.class);- when(policy.policyType()).thenReturn(Policy.BuiltInType.ICEBERG_SNAPSHOT_EXPIRATION);- when(policy.content()).thenReturn(PolicyContents.icebergSnapshotExpiration());- Function<Long, Optional<PolicyEntity>> policies = policiesReturning(policy);-- TypeDispatchingInJobRecommender dispatcher =- new TypeDispatchingInJobRecommender(- policies,- new CompactionInJobRecommender(policies),- new TriggerExprInJobRecommender(policies),- AlwaysMaintainInJobRecommender.INSTANCE);-- Assertions.assertEquals(RecommendDecision.MAINTAIN, dispatcher.recommend(2L, 1L, 9L, "{}"));- }-- @Test- void testDispatchesTriggerExprForOrphan() {- PolicyEntity policy = mock(PolicyEntity.class);- when(policy.policyType()).thenReturn(Policy.BuiltInType.ICEBERG_ORPHAN_FILE_REMOVAL);- when(policy.content()).thenReturn(PolicyContents.icebergOrphanFileRemoval());- Function<Long, Optional<PolicyEntity>> policies = policiesReturning(policy);-- TriggerExprInJobRecommender triggerExpr = new TriggerExprInJobRecommender(policies);- TypeDispatchingInJobRecommender dispatcher =- new TypeDispatchingInJobRecommender(policies, mock(InJobRecommender.class), triggerExpr);-- Assertions.assertEquals(RecommendDecision.MAINTAIN, dispatcher.recommend(2L, 1L, 9L, "{}"));- }-- @Test- void testCompactionRecommenderReusesLoadedPolicy() {- PolicyEntity policy = mock(PolicyEntity.class);- when(policy.policyType()).thenReturn(Policy.BuiltInType.ICEBERG_COMPACTION);- when(policy.content())- .thenReturn(PolicyContents.icebergDataCompaction(500L, 3L, Collections.emptyMap()));- @SuppressWarnings("unchecked")- Function<Long, Optional<PolicyEntity>> policies = mock(Function.class);- when(policies.apply(7L)).thenReturn(Optional.of(policy));-- CompactionInJobRecommender compaction = new CompactionInJobRecommender(policies);- TypeDispatchingInJobRecommender dispatcher =- new TypeDispatchingInJobRecommender(- policies, compaction, new TriggerExprInJobRecommender(policies));-- String metrics =- "{\"custom-data-file-mse\":600,\"custom-delete-file-number\":0,\"snapshotId\":1}";- Assertions.assertEquals(RecommendDecision.MAINTAIN, dispatcher.recommend(1L, 7L, 99L, metrics));- // Type-dispatch loads once; compaction must not look up again.- verify(policies, times(1)).apply(7L);- }-- @SuppressWarnings("unchecked")- private static Function<Long, Optional<PolicyEntity>> policiesReturning(PolicyEntity policy) {- Function<Long, Optional<PolicyEntity>> policies = mock(Function.class);- when(policies.apply(anyLong())).thenReturn(Optional.of(policy));- return policies;- }-}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/IrcToCommitScheduleIT.javasimilarity index 97%rename from plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/integration/test/IrcToCommitEnqueueIT.javarename to plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/integration/test/IrcToCommitScheduleIT.javaindex d2628331a6..6f59d8b94f 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/IrcToCommitScheduleIT.java@@ -63,11 +63,11 @@ import org.junit.jupiter.api.Test;/*** Boots Gravitino with {@link TableMaintenanceRESTFeature} and {@link* PostCommitMaintenanceListener}, then dispatches an IRC table-update event and asserts commit-job- * enqueue.+ * schedule.** <p>Embedded mode only (same-JVM EventBus / MetaService). Run with {@code -PskipITs} omitted.*/-public class IrcToCommitEnqueueIT extends BaseIT {+public class IrcToCommitScheduleIT extends BaseIT {private static final String LISTENER_NAME = "tmsIrc";@@ -113,7 +113,7 @@ public class IrcToCommitEnqueueIT extends BaseIT {}@Test- void testIrcUpdateEventEnqueuesCommitJob() throws Exception {+ void testIrcUpdateEventSchedulesCommitJob() throws Exception {assumeTrue(ITUtils.EMBEDDED_TEST_MODE.equals(testMode),"Asserts commit submit capture in the same JVM as the EventBus listener");@@ -172,6 +172,6 @@ public class IrcToCommitEnqueueIT extends BaseIT {assertEquals(expectedInstanceId,CAPTURED_COMMIT_ID.get(),- "IRC listener did not enqueue expected commit-job within " + timeoutSeconds + "s");+ "IRC listener did not schedule expected commit-job within " + timeoutSeconds + "s");}}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 8a7b41c3d3..0b560ba51e 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@@ -37,24 +37,19 @@ import org.apache.gravitino.integration.test.util.BaseIT;import org.apache.gravitino.integration.test.util.ITUtils;import org.apache.gravitino.maintenance.TableMaintenanceConfig;import org.apache.gravitino.maintenance.integration.test.MaintenanceSchedulerITSupport.SeededTable;-import org.apache.gravitino.maintenance.occupancy.OccupancyGate;import org.apache.gravitino.maintenance.policy.MaintenanceAuthConfigs;-import org.apache.gravitino.maintenance.policy.PolicyExpandRegistrar;import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;import org.apache.gravitino.maintenance.scheduler.MaintenanceTaskIds;import org.apache.gravitino.maintenance.scheduler.SchedulerPoolTestHooks;-import org.apache.gravitino.maintenance.scheduler.policy.expand.ExpandTableCandidate;-import org.apache.gravitino.maintenance.scheduler.policy.expand.NearestPolicyTableEnumerator;+import org.apache.gravitino.maintenance.scheduler.policy.expand.PolicyExpandClient;import org.apache.gravitino.maintenance.web.rest.feature.TableMaintenanceRESTFeature;-import org.apache.gravitino.meta.PolicyEntity;-import org.apache.gravitino.storage.relational.service.PolicyMetaService;import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;/*** Boots Gravitino with {@link TableMaintenanceRESTFeature} and exercises policy-expand → cron-job- * enqueue through the live expand pool and nearest-policy table walk.+ * schedule through the live expand pool and nearest-policy table walk.** <p>Embedded mode only (same-JVM MetaService / SchedulerClient). Run with {@code -PskipITs}* omitted.@@ -95,7 +90,7 @@ public class PolicyExpandToCronIT extends BaseIT {}@Test- void testExpandPoolEnqueuesCronJobForTaggedTable() throws Exception {+ void testExpandPoolSchedulesCronJobForTaggedTable() throws Exception {assumeTrue(ITUtils.EMBEDDED_TEST_MODE.equals(testMode),"Asserts cron submit capture in the same JVM as the expand pool");@@ -107,23 +102,14 @@ public class PolicyExpandToCronIT extends BaseIT {MaintenanceSchedulerITSupport.seedTaggedCompactionTable(client.loadMetalake(metalake), metalake, TIME_TRIGGER, /*commitTrigger=*/ null);- PolicyEntity policy = PolicyMetaService.getInstance().getPolicyById(seeded.policyId);- List<ExpandTableCandidate> candidates =- new NearestPolicyTableEnumerator()- .listTableIds(policy, 10, new OccupancyGate()::shouldSkip, 0L);- assertEquals(- List.of(seeded.tableId),- candidates.stream().map(ExpandTableCandidate::tableId).toList(),- "nearest enumerator should see the tagged Iceberg table");-DataSource ds = dataSource();assertTrue(- PolicyExpandRegistrar.forReads(ds).scheduledExecutionTime(seeded.policyId).isPresent(),+ PolicyExpandClient.forReads(ds).scheduledExecutionTime(seeded.policyId).isPresent(),"createPolicy should register a policy-expand row via PolicyExpandLifecycleHook");// Force the expand lease overdue so the live expand pool picks it (production next fire is// tomorrow 02:00 for TIME_TRIGGER).- PolicyExpandRegistrar.forReads(ds).scheduleAt(seeded.policyId, Instant.now().minusSeconds(5));+ PolicyExpandClient.forReads(ds).scheduleAt(seeded.policyId, Instant.now().minusSeconds(5));awaitCronCapture(MaintenanceTaskIds.forCronTable(seeded.tableId, seeded.policyId), 30L);@@ -150,7 +136,7 @@ public class PolicyExpandToCronIT extends BaseIT {assertEquals(expectedInstanceId,CAPTURED_CRON_ID.get(),- "expand pool did not enqueue expected cron-job within " + timeoutSeconds + "s");+ "expand pool did not schedule expected cron-job within " + timeoutSeconds + "s");}private static DataSource dataSource() {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 75f8d99757..98be5c9572 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@@ -42,9 +42,9 @@ import org.apache.gravitino.Namespace;import org.apache.gravitino.integration.test.util.BaseIT;import org.apache.gravitino.integration.test.util.ITUtils;import org.apache.gravitino.maintenance.TableMaintenanceConfig;+import org.apache.gravitino.maintenance.model.OccupancyClaim;import org.apache.gravitino.maintenance.storage.mapper.provider.MaintenanceMapperPackageProvider;import org.apache.gravitino.maintenance.storage.po.TableMaintenanceActionPO;-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.maintenance.web.rest.feature.TableMaintenanceRESTFeature;@@ -132,8 +132,12 @@ public class TableMaintenanceActionRESTIT extends BaseIT {TableMaintenanceActionMetaService actions = TableMaintenanceActionMetaService.getInstance();OccupancyClaim claim =- actions.insertInFlight(- tableId, policyId, TableMaintenanceConfig.forTest(1, 1, 1, 500L, 1_000L, 4, 10));+ actions+ .tryAcquireInFlight(+ tableId,+ policyId,+ TableMaintenanceConfig.forTest(1, 1, 1, 500L, 1_000L, 4, 10).claimTimeoutMs())+ .orElseThrow();assertNotNull(claim);actions.bindJobId(claim, jobId);long actionId = claim.actionId();diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/listener/TestPostCommitMaintenanceListener.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/listener/TestPostCommitMaintenanceListener.javaindex 496e9a0182..dc9eb76ccf 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/listener/TestPostCommitMaintenanceListener.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/listener/TestPostCommitMaintenanceListener.java@@ -18,23 +18,10 @@*/package org.apache.gravitino.maintenance.listener;-import static org.mockito.ArgumentMatchers.anyLong;-import static org.mockito.ArgumentMatchers.eq;-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.time.Instant;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.listener.api.event.Event;import org.apache.gravitino.listener.api.event.OperationStatus;import org.apache.gravitino.listener.api.event.OperationType;-import org.apache.gravitino.maintenance.scheduler.job.commit.CommitJobClient;-import org.apache.gravitino.maintenance.scheduler.job.commit.CommitJobEnqueueResult;-import org.apache.gravitino.meta.AuditInfo;-import org.apache.gravitino.meta.TableEntity;-import org.apache.gravitino.utils.NamespaceUtil;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Test;@@ -48,52 +35,10 @@ class TestPostCommitMaintenanceListener {}@Test- void testIgnoresUnrelatedEvents() {- PostCommitMaintenanceListener listener = new PostCommitMaintenanceListener();- CommitJobClient scheduler = mock(CommitJobClient.class);- listener.setCommitJobClient(scheduler);-- listener.onPostEvent(new OtherEvent("u", NameIdentifier.of("ml", "c", "s", "t")));-- verify(scheduler, never()).enqueueNow(anyLong());- }-- @Test- void testEnqueueUpsertsCommitJob() {+ void testIgnoresUnrelatedEventsWhenNotStarted() {PostCommitMaintenanceListener listener = new PostCommitMaintenanceListener();- CommitJobClient scheduler = mock(CommitJobClient.class);- when(scheduler.enqueueNow(eq(42L))).thenReturn(CommitJobEnqueueResult.INSERTED);- listener.setCommitJobClient(scheduler);- listener.setTableLookup(- ident ->- TableEntity.builder()- .withId(42L)- .withName("t")- .withNamespace(NamespaceUtil.ofTable("ml", "c", "s"))- .withAuditInfo(- AuditInfo.builder().withCreator("test").withCreateTime(Instant.EPOCH).build())- .build());-- listener.enqueueCommitJob(NameIdentifier.of("ml", "c", "s", "t"));-- verify(scheduler).enqueueNow(42L);- }-- @Test- void testEnqueueSkippedWhenSchedulerNotStarted() {- PostCommitMaintenanceListener listener = new PostCommitMaintenanceListener();- listener.setTableLookup(- ident ->- TableEntity.builder()- .withId(1L)- .withName("t")- .withNamespace(NamespaceUtil.ofTable("ml", "c", "s"))- .withAuditInfo(- AuditInfo.builder().withCreator("test").withCreateTime(Instant.EPOCH).build())- .build());-Assertions.assertDoesNotThrow(- () -> listener.enqueueCommitJob(NameIdentifier.of("ml", "c", "s", "t")));+ () -> listener.onPostEvent(new OtherEvent("u", NameIdentifier.of("ml", "c", "s", "t"))));}private static final class OtherEvent extends Event {diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/policy/TestPolicyExpandLifecycleHook.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/policy/TestPolicyExpandLifecycleHook.javaindex 69336594a1..0a027ca5b6 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/policy/TestPolicyExpandLifecycleHook.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/policy/TestPolicyExpandLifecycleHook.java@@ -22,6 +22,7 @@ import java.util.Map;import java.util.Set;import javax.sql.DataSource;import org.apache.gravitino.MetadataObject;+import org.apache.gravitino.maintenance.scheduler.policy.expand.PolicyExpandClient;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.PolicyEntity;import org.apache.gravitino.policy.IcebergDataCompactionContent;@@ -41,8 +42,8 @@ class TestPolicyExpandLifecycleHook extends TestJDBCBackend {@TestTemplatevoid testEnabledMaintenancePolicyIsScheduled() {- PolicyExpandRegistrar writer = PolicyExpandRegistrar.joiningCurrentTransaction();- PolicyExpandRegistrar reader = PolicyExpandRegistrar.forReads(entityStoreDataSource());+ PolicyExpandClient writer = PolicyExpandClient.joiningCurrentTransaction();+ PolicyExpandClient reader = PolicyExpandClient.forReads(entityStoreDataSource());PolicyExpandLifecycleHook hook = new PolicyExpandLifecycleHook(writer);SessionUtils.doMultipleWithCommit(() -> hook.afterPersist(policy(42L, true, compaction(CRON))));@@ -51,40 +52,38 @@ class TestPolicyExpandLifecycleHook extends TestJDBCBackend {}@TestTemplate- void testDisabledMaintenancePolicyRemovesTheRow() {- PolicyExpandRegistrar writer = PolicyExpandRegistrar.joiningCurrentTransaction();- PolicyExpandRegistrar reader = PolicyExpandRegistrar.forReads(entityStoreDataSource());+ void testDisabledOrNonMaintenancePolicyRemovesTheRow() {+ PolicyExpandClient writer = PolicyExpandClient.joiningCurrentTransaction();+ PolicyExpandClient reader = PolicyExpandClient.forReads(entityStoreDataSource());PolicyExpandLifecycleHook hook = new PolicyExpandLifecycleHook(writer);SessionUtils.doMultipleWithCommit(() -> hook.afterPersist(policy(7L, true, compaction(CRON))));Assertions.assertTrue(reader.scheduledExecutionTime(7L).isPresent());-SessionUtils.doMultipleWithCommit(() -> hook.afterUpdate(policy(7L, false, compaction(CRON))));Assertions.assertTrue(reader.scheduledExecutionTime(7L).isEmpty());- }-- @TestTemplate- void testNonMaintenancePolicyRemovesAnyStrayRow() {- PolicyExpandRegistrar writer = PolicyExpandRegistrar.joiningCurrentTransaction();- PolicyExpandRegistrar reader = PolicyExpandRegistrar.forReads(entityStoreDataSource());- PolicyExpandLifecycleHook hook = new PolicyExpandLifecycleHook(writer);- PolicyContent custom = PolicyContents.custom(Map.of(), Set.of(MetadataObject.Type.TABLE), null);- SessionUtils.doMultipleWithCommit(() -> writer.sync(1L, true, CRON));+ SessionUtils.doMultipleWithCommit(+ () -> writer.scheduleAt(1L, PolicyExpandClient.nextExecution(CRON)));Assertions.assertTrue(reader.scheduledExecutionTime(1L).isPresent());-SessionUtils.doMultipleWithCommit(- () -> hook.afterPersist(policy(1L, true, custom, Policy.BuiltInType.CUSTOM)));+ () ->+ hook.afterPersist(+ policy(+ 1L,+ true,+ PolicyContents.custom(Map.of(), Set.of(MetadataObject.Type.TABLE), null),+ Policy.BuiltInType.CUSTOM)));Assertions.assertTrue(reader.scheduledExecutionTime(1L).isEmpty());}@TestTemplatevoid testDeleteRemovesByPolicyId() {- PolicyExpandRegistrar writer = PolicyExpandRegistrar.joiningCurrentTransaction();- PolicyExpandRegistrar reader = PolicyExpandRegistrar.forReads(entityStoreDataSource());+ PolicyExpandClient writer = PolicyExpandClient.joiningCurrentTransaction();+ PolicyExpandClient reader = PolicyExpandClient.forReads(entityStoreDataSource());PolicyExpandLifecycleHook hook = new PolicyExpandLifecycleHook(writer);- SessionUtils.doMultipleWithCommit(() -> writer.sync(11L, true, CRON));+ SessionUtils.doMultipleWithCommit(+ () -> writer.scheduleAt(11L, PolicyExpandClient.nextExecution(CRON)));Assertions.assertTrue(reader.scheduledExecutionTime(11L).isPresent());SessionUtils.doMultipleWithCommit(() -> hook.beforeRemove(11L));diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/policy/TestPolicyExpandReconciler.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/policy/TestPolicyExpandReconciler.javaindex a3018ae46f..f91028e932 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/policy/TestPolicyExpandReconciler.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/policy/TestPolicyExpandReconciler.java@@ -18,13 +18,12 @@*/package org.apache.gravitino.maintenance.policy;-import com.github.kagkarlsson.scheduler.task.ExecutionComplete;-import com.github.kagkarlsson.scheduler.task.ExecutionOperations;import java.io.IOException;import java.time.Instant;import java.time.temporal.ChronoUnit;import java.util.List;import javax.sql.DataSource;+import org.apache.gravitino.maintenance.scheduler.policy.expand.PolicyExpandClient;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.BaseMetalake;import org.apache.gravitino.meta.PolicyEntity;@@ -66,14 +65,13 @@ class TestPolicyExpandReconciler extends TestJDBCBackend {PolicyMetaService.getInstance().insertPolicy(policy, false);DataSource dataSource = entityStoreDataSource();- PolicyExpandRegistrar reader = PolicyExpandRegistrar.forReads(dataSource);+ PolicyExpandClient reader = PolicyExpandClient.forReads(dataSource);Assertions.assertTrue(reader.scheduledExecutionTime(policy.id()).isEmpty());- PolicyExpandRegistrar writer = PolicyExpandRegistrar.joiningCurrentTransaction();- PolicyExpandLifecycleHook aligner = new PolicyExpandLifecycleHook(writer);+ PolicyExpandClient writer = PolicyExpandClient.joiningCurrentTransaction();int aligned =new PolicyExpandReconciler(- aligner, writer, MetalakeMetaService.getInstance(), PolicyMetaService.getInstance())+ writer, MetalakeMetaService.getInstance(), PolicyMetaService.getInstance()).reconcileAll();Assertions.assertTrue(aligned >= 1);@@ -98,14 +96,13 @@ class TestPolicyExpandReconciler extends TestJDBCBackend {// db-scheduler / JDBC timestamps are microsecond precision; truncate so round-trip equals.Instant overdue = Instant.now().minusSeconds(3600).truncatedTo(ChronoUnit.MICROS);- PolicyExpandRegistrar writer = PolicyExpandRegistrar.joiningCurrentTransaction();- PolicyExpandRegistrar reader = PolicyExpandRegistrar.forReads(entityStoreDataSource());+ PolicyExpandClient writer = PolicyExpandClient.joiningCurrentTransaction();+ PolicyExpandClient reader = PolicyExpandClient.forReads(entityStoreDataSource());SessionUtils.doMultipleWithCommit(() -> writer.scheduleAt(policy.id(), overdue));Assertions.assertEquals(overdue, reader.scheduledExecutionTime(policy.id()).orElseThrow());- PolicyExpandLifecycleHook aligner = new PolicyExpandLifecycleHook(writer);new PolicyExpandReconciler(- aligner, writer, MetalakeMetaService.getInstance(), PolicyMetaService.getInstance())+ writer, MetalakeMetaService.getInstance(), PolicyMetaService.getInstance()).reconcileAll();Assertions.assertEquals(overdue, reader.scheduledExecutionTime(policy.id()).orElseThrow());@@ -127,14 +124,14 @@ class TestPolicyExpandReconciler extends TestJDBCBackend {.build();PolicyMetaService.getInstance().insertPolicy(policy, false);- PolicyExpandRegistrar writer = PolicyExpandRegistrar.joiningCurrentTransaction();- PolicyExpandRegistrar reader = PolicyExpandRegistrar.forReads(entityStoreDataSource());- SessionUtils.doMultipleWithCommit(() -> writer.sync(policy.id(), true, LATER_CRON));+ PolicyExpandClient writer = PolicyExpandClient.joiningCurrentTransaction();+ PolicyExpandClient reader = PolicyExpandClient.forReads(entityStoreDataSource());+ SessionUtils.doMultipleWithCommit(+ () -> writer.scheduleAt(policy.id(), PolicyExpandClient.nextExecution(LATER_CRON)));Instant staleDue = reader.scheduledExecutionTime(policy.id()).orElseThrow();- PolicyExpandLifecycleHook aligner = new PolicyExpandLifecycleHook(writer);new PolicyExpandReconciler(- aligner, writer, MetalakeMetaService.getInstance(), PolicyMetaService.getInstance())+ writer, MetalakeMetaService.getInstance(), PolicyMetaService.getInstance()).reconcileAll();Instant corrected = reader.scheduledExecutionTime(policy.id()).orElseThrow();@@ -162,66 +159,33 @@ class TestPolicyExpandReconciler extends TestJDBCBackend {Mockito.when(policies.listPoliciesByNamespace(NamespaceUtil.ofPolicy("ml"))).thenReturn(List.of(bad));- PolicyExpandRegistrar writer = PolicyExpandRegistrar.joiningCurrentTransaction();- SessionUtils.doMultipleWithCommit(() -> writer.sync(7L, true, CRON));- PolicyExpandRegistrar reader = PolicyExpandRegistrar.forReads(entityStoreDataSource());+ PolicyExpandClient writer = PolicyExpandClient.joiningCurrentTransaction();+ SessionUtils.doMultipleWithCommit(+ () -> writer.scheduleAt(7L, PolicyExpandClient.nextExecution(CRON)));+ PolicyExpandClient reader = PolicyExpandClient.forReads(entityStoreDataSource());Assertions.assertTrue(reader.scheduledExecutionTime(7L).isPresent());- PolicyExpandLifecycleHook aligner = new PolicyExpandLifecycleHook(writer);Assertions.assertDoesNotThrow(- () -> new PolicyExpandReconciler(aligner, writer, metalakes, policies).reconcileAll());+ () -> new PolicyExpandReconciler(writer, metalakes, policies).reconcileAll());Assertions.assertTrue(reader.scheduledExecutionTime(7L).isEmpty());}@TestTemplatevoid testReconcileRemovesOrphanExpandRow() {- PolicyExpandRegistrar writer = PolicyExpandRegistrar.joiningCurrentTransaction();- SessionUtils.doMultipleWithCommit(() -> writer.sync(99L, true, CRON));- PolicyExpandRegistrar reader = PolicyExpandRegistrar.forReads(entityStoreDataSource());+ PolicyExpandClient writer = PolicyExpandClient.joiningCurrentTransaction();+ SessionUtils.doMultipleWithCommit(+ () -> writer.scheduleAt(99L, PolicyExpandClient.nextExecution(CRON)));+ PolicyExpandClient reader = PolicyExpandClient.forReads(entityStoreDataSource());Assertions.assertTrue(reader.scheduledExecutionTime(99L).isPresent());MetalakeMetaService metalakes = Mockito.mock(MetalakeMetaService.class);PolicyMetaService policies = Mockito.mock(PolicyMetaService.class);Mockito.when(metalakes.listMetalakes()).thenReturn(List.of());- PolicyExpandLifecycleHook aligner = new PolicyExpandLifecycleHook(writer);- new PolicyExpandReconciler(aligner, writer, metalakes, policies).reconcileAll();+ new PolicyExpandReconciler(writer, metalakes, policies).reconcileAll();Assertions.assertTrue(reader.scheduledExecutionTime(99L).isEmpty());}- @TestTemplate- void testCompletePickReschedulesEnabledPolicy() throws IOException {- createAndInsertMakeLake(METALAKE + "_pick");- String metalake = METALAKE + "_pick";- PolicyEntity policy =- PolicyEntity.builder()- .withId(RandomIdGenerator.INSTANCE.nextId())- .withName("picked")- .withNamespace(NamespaceUtil.ofPolicy(metalake))- .withPolicyType(Policy.BuiltInType.ICEBERG_COMPACTION)- .withContent(compaction(CRON))- .withEnabled(true)- .withAuditInfo(AuditInfo.EMPTY)- .build();- PolicyMetaService.getInstance().insertPolicy(policy, false);-- ExecutionOperations<Void> operations = Mockito.mock(ExecutionOperations.class);- ExecutionComplete complete = ExecutionComplete.simulatedSuccess(Instant.now());- PolicyExpandLifecycleHook.completePick("policy:" + policy.id(), complete, operations);-- Mockito.verify(operations)- .reschedule(Mockito.eq(complete), Mockito.argThat(due -> due.isAfter(Instant.now())));- Mockito.verify(operations, Mockito.never()).remove();- }-- @TestTemplate- void testCompletePickRemovesMissingPolicy() {- ExecutionOperations<Void> operations = Mockito.mock(ExecutionOperations.class);- ExecutionComplete complete = ExecutionComplete.simulatedSuccess(Instant.now());- PolicyExpandLifecycleHook.completePick("policy:424242", complete, operations);- Mockito.verify(operations).remove();- }-private static DataSource entityStoreDataSource() {return SqlSessionFactoryHelper.getInstance().getSqlSessionFactory()diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/policy/TestPolicyExpandRegistrar.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/policy/TestPolicyExpandRegistrar.javadeleted file mode 100644index b3d6fc10ae..0000000000--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/policy/TestPolicyExpandRegistrar.java+++ /dev/null@@ -1,147 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.policy;--import com.github.kagkarlsson.scheduler.SchedulerClient;-import com.github.kagkarlsson.scheduler.task.TaskInstanceId;-import java.time.Instant;-import java.time.temporal.ChronoUnit;-import java.util.Map;-import javax.sql.DataSource;-import org.apache.gravitino.Config;-import org.apache.gravitino.maintenance.TableMaintenanceConfig;-import org.apache.gravitino.maintenance.scheduler.TableMaintenanceSchedulerPools;-import org.apache.gravitino.storage.relational.TestJDBCBackend;-import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;-import org.apache.gravitino.storage.relational.utils.SessionUtils;-import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.TestTemplate;--class TestPolicyExpandRegistrar extends TestJDBCBackend {-- private static final String CRON = "0 0 2 * * ?";- private static final String LATER_CRON = "0 30 4 * * ?";-- @TestTemplate- void testSyncInsertsReschedulesAndRemovesTheExpandRow() {- DataSource dataSource = entityStoreDataSource();- PolicyExpandRegistrar writer = PolicyExpandRegistrar.joiningCurrentTransaction();- PolicyExpandRegistrar reader = PolicyExpandRegistrar.forReads(dataSource);-- SessionUtils.doMultipleWithCommit(() -> writer.sync(42L, true, CRON));- Instant firstDue = executionTime(reader, 42L);- Assertions.assertTrue(firstDue.isAfter(Instant.now()));-- SessionUtils.doMultipleWithCommit(() -> writer.sync(42L, true, LATER_CRON));- Instant secondDue = executionTime(reader, 42L);- Assertions.assertNotEquals(firstDue, secondDue);-- SessionUtils.doMultipleWithCommit(() -> writer.sync(42L, false, LATER_CRON));- Assertions.assertTrue(reader.scheduledExecutionTime(42L).isEmpty());-- SessionUtils.doMultipleWithCommit(() -> writer.sync(42L, true, CRON));- Assertions.assertTrue(reader.scheduledExecutionTime(42L).isPresent());- SessionUtils.doMultipleWithCommit(() -> writer.remove(42L));- Assertions.assertTrue(reader.scheduledExecutionTime(42L).isEmpty());- SessionUtils.doMultipleWithCommit(() -> writer.remove(42L));- }-- @TestTemplate- void testFailedTransactionRollsBackTheExpandRow() {- DataSource dataSource = entityStoreDataSource();- PolicyExpandRegistrar writer = PolicyExpandRegistrar.joiningCurrentTransaction();- PolicyExpandRegistrar reader = PolicyExpandRegistrar.forReads(dataSource);-- Assertions.assertThrows(- IllegalStateException.class,- () ->- SessionUtils.doMultipleWithCommit(- () -> writer.sync(99L, true, CRON),- () -> {- throw new IllegalStateException("boom");- }));-- Assertions.assertTrue(reader.scheduledExecutionTime(99L).isEmpty());- }-- @TestTemplate- void testInvalidCronFailsBeforeAnExpandRowIsWritten() {- DataSource dataSource = entityStoreDataSource();- PolicyExpandRegistrar writer = PolicyExpandRegistrar.joiningCurrentTransaction();- PolicyExpandRegistrar reader = PolicyExpandRegistrar.forReads(dataSource);-- Assertions.assertThrows(- IllegalArgumentException.class,- () -> SessionUtils.doMultipleWithCommit(() -> writer.sync(100L, true, "not a cron")));-- Assertions.assertTrue(reader.scheduledExecutionTime(100L).isEmpty());- }-- @TestTemplate- void testRunningPoolsRemoveExpandRowForMissingPolicy() throws Exception {- Instant overdue = Instant.now().minusSeconds(30).truncatedTo(ChronoUnit.MICROS);- PolicyExpandRegistrar writer = PolicyExpandRegistrar.joiningCurrentTransaction();- DataSource dataSource = entityStoreDataSource();- SessionUtils.doMultipleWithCommit(() -> writer.scheduleAt(11L, overdue));-- SchedulerClient client =- SchedulerClient.Builder.create(- dataSource, TableMaintenanceSchedulerPools.policyExpandTask())- .tableName(TableMaintenanceSchedulerPools.EXPAND_TASKS_TABLE)- .build();- TaskInstanceId instanceId =- TaskInstanceId.of(TableMaintenanceSchedulerPools.POLICY_EXPAND, "policy:11");- Assertions.assertTrue(client.getScheduledExecution(instanceId).isPresent());-- TableMaintenanceSchedulerPools pools = new TableMaintenanceSchedulerPools();- Config gravitinoConfig = new Config(false) {};- gravitinoConfig.loadFromMap(- Map.of(- MaintenanceAuthConfigs.GRAVITINO_MAINTENANCE_GRAVITINO_AUTH_URI.getKey(),- "http://localhost:8090"),- k -> true);- pools.start(- dataSource, TableMaintenanceConfig.forTest(1, 1, 1, 100L, 1_000L, 4, 10), gravitinoConfig);- try {- long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(5);- while (client.getScheduledExecution(instanceId).isPresent()) {- Assertions.assertTrue(- System.nanoTime() < deadline,- "expand row for missing policy should be removed after pick");- Thread.sleep(100L);- }- } finally {- pools.stop();- }- }-- private static DataSource entityStoreDataSource() {- return SqlSessionFactoryHelper.getInstance()- .getSqlSessionFactory()- .getConfiguration()- .getEnvironment()- .getDataSource();- }-- private static Instant executionTime(PolicyExpandRegistrar registrar, long policyId) {- return registrar- .scheduledExecutionTime(policyId)- .orElseThrow(() -> new AssertionError("missing expand row " + policyId));- }-}diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/SchedulerPoolTestHooks.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/SchedulerPoolTestHooks.javaindex eb55ac8eaf..ff4884975d 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/SchedulerPoolTestHooks.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/SchedulerPoolTestHooks.java@@ -22,10 +22,10 @@ import com.google.common.base.Preconditions;import java.util.function.BiConsumer;/**- * Same-package test access to {@link TableMaintenanceSchedulerPools} submit handlers.+ * Same-package test access to {@link MaintenanceSchedulerPools} submit handlers.** <p>Keeps production pools free of {@code *ForTest} APIs while still allowing BaseITs to record- * cron/commit enqueue without a real Spark {@code runJob}.+ * cron/commit schedule without a real Spark {@code runJob}.*/public final class SchedulerPoolTestHooks {@@ -37,7 +37,7 @@ public final class SchedulerPoolTestHooks {* @param submitHandler handler used by the cron pool task*/public static void installCronSubmit(BiConsumer<String, MaintenanceJobSpec> submitHandler) {- TableMaintenanceSchedulerPools.CRON_SUBMIT.set(Preconditions.checkNotNull(submitHandler));+ MaintenanceSchedulerPools.CRON_SUBMIT.set(Preconditions.checkNotNull(submitHandler));}/**@@ -46,6 +46,6 @@ public final class SchedulerPoolTestHooks {* @param submitHandler handler used by the commit pool task*/public static void installCommitSubmit(BiConsumer<String, MaintenanceJobSpec> submitHandler) {- TableMaintenanceSchedulerPools.COMMIT_SUBMIT.set(Preconditions.checkNotNull(submitHandler));+ MaintenanceSchedulerPools.COMMIT_SUBMIT.set(Preconditions.checkNotNull(submitHandler));}}diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/TestAutocommitDataSources.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/TestAutocommitDataSources.javanew file mode 100644index 0000000000..9d09e1d413--- /dev/null+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/TestAutocommitDataSources.java@@ -0,0 +1,158 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.maintenance.scheduler;++import com.github.kagkarlsson.scheduler.SchedulerClient;+import com.github.kagkarlsson.scheduler.task.TaskInstanceId;+import java.time.Instant;+import java.util.List;+import java.util.Map;+import java.util.function.Function;+import javax.sql.DataSource;+import org.apache.gravitino.Config;+import org.apache.gravitino.maintenance.model.TableCandidate;+import org.apache.gravitino.maintenance.policy.MaintenanceAuthConfigs;+import org.apache.gravitino.maintenance.scheduler.job.cron.CronJobClient;+import org.apache.gravitino.meta.AuditInfo;+import org.apache.gravitino.meta.PolicyEntity;+import org.apache.gravitino.policy.Policy;+import org.apache.gravitino.policy.PolicyContents;+import org.apache.gravitino.storage.relational.TestJDBCBackend;+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;+import org.apache.gravitino.utils.NamespaceUtil;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.TestTemplate;++class TestAutocommitDataSources extends TestJDBCBackend {++ @TestTemplate+ void testRunInTransactionCommitsSchedulerClientCancel() throws Exception {+ DataSource dataSource = dataSource();+ SchedulerClient client = CronJobClient.schedulerClient(dataSource);+ TaskInstanceId instanceId = scheduleOneExpireRow(501L, 50L);++ Assertions.assertTrue(client.getScheduledExecution(instanceId).isPresent());+ AutocommitDataSources.runInTransaction(+ dataSource,+ (Function<DataSource, Void>)+ txDs -> {+ CronJobClient.schedulerClientOn(txDs).cancel(instanceId);+ return null;+ });+ Assertions.assertTrue(client.getScheduledExecution(instanceId).isEmpty());+ }++ @TestTemplate+ void testRunInTransactionRollsBackSchedulerClientCancelWhenWorkThrows() {+ DataSource dataSource = dataSource();+ SchedulerClient client = CronJobClient.schedulerClient(dataSource);+ TaskInstanceId instanceId = scheduleOneExpireRow(502L, 51L);++ Assertions.assertTrue(client.getScheduledExecution(instanceId).isPresent());+ Assertions.assertThrows(+ IllegalStateException.class,+ () ->+ AutocommitDataSources.runInTransaction(+ dataSource,+ (Function<DataSource, Void>)+ txDs -> {+ CronJobClient.schedulerClientOn(txDs).cancel(instanceId);+ throw new IllegalStateException("abort after cancel");+ }));+ Assertions.assertTrue(+ client.getScheduledExecution(instanceId).isPresent(),+ "cancel must roll back when the transactional work throws");+ }++ @TestTemplate+ void testRunInTransactionRollsBackCancelWhenLaterStepThrows() {+ DataSource dataSource = dataSource();+ SchedulerClient client = CronJobClient.schedulerClient(dataSource);+ TaskInstanceId peerId = scheduleOneExpireRow(503L, 52L);++ Assertions.assertThrows(+ IllegalStateException.class,+ () ->+ AutocommitDataSources.runInTransaction(+ dataSource,+ (Function<DataSource, Void>)+ txDs -> {+ CronJobClient.schedulerClientOn(txDs).cancel(peerId);+ throw new IllegalStateException("simulate reschedule failure after cancel");+ }));++ Assertions.assertTrue(+ client.getScheduledExecution(peerId).isPresent(),+ "peer cancel must roll back when a later step in the same transaction fails");+ }++ private static TaskInstanceId scheduleOneExpireRow(long tableId, long policyId) {+ PolicyEntity policy = expirePolicy(policyId);+ CronJobClient cronJobs = new CronJobClient(dataSource(), configWithUri());+ Assertions.assertEquals(+ 1,+ cronJobs.scheduleNow(+ policy,+ List.of(new TableCandidate(tableId, "iceberg", "db.t" + tableId, List.of(policy))),+ 10));+ SchedulerClient client = CronJobClient.schedulerClient(dataSource());+ return client+ .getScheduledExecutionsForTask(MaintenanceSchedulerPools.CRON_JOB, MaintenanceJobSpec.class)+ .stream()+ .filter(+ execution -> {+ MaintenanceJobSpec data = execution.getData();+ return data != null && data.tableIds().contains(tableId);+ })+ .map(execution -> execution.getTaskInstance())+ .findFirst()+ .orElseThrow();+ }++ private static DataSource dataSource() {+ return SqlSessionFactoryHelper.getInstance()+ .getSqlSessionFactory()+ .getConfiguration()+ .getEnvironment()+ .getDataSource();+ }++ private static Config configWithUri() {+ Config config = new Config(false) {};+ config.loadFromMap(+ Map.of(+ MaintenanceAuthConfigs.GRAVITINO_MAINTENANCE_GRAVITINO_AUTH_URI.getKey(),+ "http://localhost:8090"),+ t -> true);+ return config;+ }++ private static PolicyEntity expirePolicy(long id) {+ return PolicyEntity.builder()+ .withId(id)+ .withName("e-" + id)+ .withNamespace(NamespaceUtil.ofPolicy("ml"))+ .withPolicyType(Policy.BuiltInType.ICEBERG_SNAPSHOT_EXPIRATION)+ .withEnabled(true)+ .withContent(PolicyContents.icebergSnapshotExpiration())+ .withAuditInfo(+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.EPOCH).build())+ .build();+ }+}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 1bb42b00cf..00af8a05fb 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@@ -22,13 +22,14 @@ import com.github.kagkarlsson.scheduler.serializer.JacksonSerializer;import com.github.kagkarlsson.scheduler.serializer.Serializer;import java.nio.charset.StandardCharsets;import java.time.Instant;+import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import org.apache.gravitino.Config;import org.apache.gravitino.json.JsonUtils;+import org.apache.gravitino.maintenance.model.TableCandidate;import org.apache.gravitino.maintenance.policy.MaintenanceAuthConfigs;-import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceJobTemplates;-import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceTableRefs.ResolvedTableRef;+import org.apache.gravitino.maintenance.scheduler.job.MaintenanceJobTemplates;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.PolicyEntity;import org.apache.gravitino.policy.IcebergDataCompactionContent;@@ -48,10 +49,9 @@ class TestMaintenanceJobSpecFactory {PolicyEntity policy = compaction(202L);MaintenanceJobSpec spec =factory.forCron(- policy,List.of(- new ResolvedTableRef(10L, "iceberg", "db.t1"),- new ResolvedTableRef(11L, "iceberg", "db.t2")));+ candidate(10L, "iceberg", "db.t1", policy),+ candidate(11L, "iceberg", "db.t2", policy)));Assertions.assertTrue(spec.isValid());Assertions.assertEquals("ml", spec.metalake());@@ -83,27 +83,34 @@ class TestMaintenanceJobSpecFactory {Assertions.assertTrue(perTable.get("tables").contains("\"table_identifier\":\"db.t1\""));Assertions.assertTrue(perTable.containsKey("updater_options"));Assertions.assertEquals("4g", perTable.get("spark_executor_memory"));++ MaintenanceJobSpec mixedPolicies =+ factory.forCron(+ List.of(+ candidate(10L, "iceberg", "db.t1", compaction(201L)),+ candidate(11L, "iceberg", "db.t2", compaction(202L))));+ Assertions.assertEquals(201L, mixedPolicies.getTasks().get(0).getPolicyId());+ Assertions.assertEquals(202L, mixedPolicies.getTasks().get(1).getPolicyId());}@Testvoid testForCronRejectsMixedCatalogs() {MaintenanceJobSpecFactory factory = new MaintenanceJobSpecFactory(configWithUri());+ PolicyEntity policy = compaction(1L);Assertions.assertThrows(IllegalArgumentException.class,() ->factory.forCron(- compaction(1L),List.of(- new ResolvedTableRef(10L, "iceberg", "db.t1"),- new ResolvedTableRef(11L, "other", "db.t2"))));+ candidate(10L, "iceberg", "db.t1", policy),+ candidate(11L, "other", "db.t2", policy))));}@Testvoid testJacksonRoundTrip() {MaintenanceJobSpecFactory factory = new MaintenanceJobSpecFactory(configWithUri());MaintenanceJobSpec original =- factory.forCron(- compaction(1L), List.of(new ResolvedTableRef(9L, "iceberg", "schema.table")));+ factory.forCron(List.of(candidate(9L, "iceberg", "schema.table", compaction(1L))));Serializer serializer = new JacksonSerializer(JsonUtils.anyFieldMapper());byte[] bytes = serializer.serialize(original);MaintenanceJobSpec restored = serializer.deserialize(MaintenanceJobSpec.class, bytes);@@ -117,35 +124,52 @@ class TestMaintenanceJobSpecFactory {}@Test- void testMergeResourceKeysTakesMax() {+ void testMergeSparkConfJsonTakesMaxMemory() {+ String merged =+ MaintenanceJobSpecFactory.mergeSparkConfJson(+ "{\"spark.executor.memory\":\"4g\",\"shared\":\"first\"}",+ "{\"spark.executor.memory\":\"8g\",\"shared\":\"later\",\"spark.executor.cores\":\"2\"}");+ Assertions.assertNotNull(merged);+ Assertions.assertTrue(merged.contains("\"spark.executor.memory\":\"8g\""));+ Assertions.assertTrue(merged.contains("\"shared\":\"first\""));+ Assertions.assertTrue(merged.contains("\"spark.executor.cores\":\"2\""));+ }++ @Test+ void testMergeResourceKeysTakesMaxIncludingMemoryUnits() {Map<String, String> into =- MaintenanceJobSpecFactory.newLinkedMap(+ linkedMap("spark_executor_memory", "4g", "spark_executor_cores", "2", "catalog_uri", "http://a");Map<String, String> from =- MaintenanceJobSpecFactory.newLinkedMap(+ linkedMap("spark_executor_memory", "7g", "spark_executor_cores", "1", "catalog_uri", "http://b");MaintenanceJobSpecFactory.mergeResourceKeys(into, from);Assertions.assertEquals("7g", into.get("spark_executor_memory"));Assertions.assertEquals("2", into.get("spark_executor_cores"));Assertions.assertEquals("http://a", into.get("catalog_uri"));- }- @Test- void testMergeResourceKeysComparesMemoryUnits() {- Map<String, String> into =- MaintenanceJobSpecFactory.newLinkedMap("spark_executor_memory", "1g");- Map<String, String> from =- MaintenanceJobSpecFactory.newLinkedMap("spark_executor_memory", "512m");- MaintenanceJobSpecFactory.mergeResourceKeys(into, from);- Assertions.assertEquals("1g", into.get("spark_executor_memory"));+ Map<String, String> units = linkedMap("spark_executor_memory", "1g");+ MaintenanceJobSpecFactory.mergeResourceKeys(units, linkedMap("spark_executor_memory", "512m"));+ Assertions.assertEquals("1g", units.get("spark_executor_memory"));- Map<String, String> mixed =- MaintenanceJobSpecFactory.newLinkedMap("spark_executor_memory", "512m");- MaintenanceJobSpecFactory.mergeResourceKeys(- mixed, MaintenanceJobSpecFactory.newLinkedMap("spark_executor_memory", "1500m"));+ Map<String, String> mixed = linkedMap("spark_executor_memory", "512m");+ MaintenanceJobSpecFactory.mergeResourceKeys(mixed, linkedMap("spark_executor_memory", "1500m"));Assertions.assertEquals("1500m", mixed.get("spark_executor_memory"));}+ private static Map<String, String> linkedMap(String... kv) {+ Map<String, String> map = new LinkedHashMap<>();+ for (int i = 0; i + 1 < kv.length; i += 2) {+ map.put(kv[i], kv[i + 1]);+ }+ return map;+ }++ private static TableCandidate candidate(+ long tableId, String catalogName, String tableIdentifier, PolicyEntity policy) {+ return new TableCandidate(tableId, catalogName, tableIdentifier, List.of(policy));+ }+private static Config configWithUri() {Config config = new Config(false) {};config.loadFromMap(diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/TestMaintenanceTaskIds.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/TestMaintenanceTaskIds.javaindex a98ddaaeb4..033709a142 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/TestMaintenanceTaskIds.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/TestMaintenanceTaskIds.java@@ -25,43 +25,28 @@ import org.junit.jupiter.api.Test;class TestMaintenanceTaskIds {@Test- void testSeparators() {+ void testFormatParseAndRejectInvalid() {Assertions.assertEquals(':', MaintenanceTaskIds.KV_SEP);Assertions.assertEquals(';', MaintenanceTaskIds.PAIR_SEP);- }- @Test- void testExpandPolicyRoundTrip() {Assertions.assertEquals("policy:42", MaintenanceTaskIds.forExpandPolicy(42L));Assertions.assertEquals(42L, MaintenanceTaskIds.parseExpandPolicy("policy:42").orElseThrow());- }- @Test- void testCronTableRoundTrip() {- String id = MaintenanceTaskIds.forCronTable(10L, 20L);- Assertions.assertEquals("table:10;policy:20", id);- Optional<long[]> parsed = MaintenanceTaskIds.parseCronTable(id);- Assertions.assertTrue(parsed.isPresent());- Assertions.assertArrayEquals(new long[] {10L, 20L}, parsed.get());- }+ String cronTable = MaintenanceTaskIds.forCronTable(10L, 20L);+ Assertions.assertEquals("table:10;policy:20", cronTable);+ Optional<long[]> cronTableParsed = MaintenanceTaskIds.parseCronTable(cronTable);+ Assertions.assertTrue(cronTableParsed.isPresent());+ Assertions.assertArrayEquals(new long[] {10L, 20L}, cronTableParsed.get());- @Test- void testCronBatchRoundTrip() {Assertions.assertEquals("batch:0;policy:9", MaintenanceTaskIds.forCronBatch(0L, 9L));Assertions.assertEquals("batch:12;policy:9", MaintenanceTaskIds.forCronBatch(12L, 9L));- Optional<long[]> parsed = MaintenanceTaskIds.parseCronBatch("batch:12;policy:9");- Assertions.assertTrue(parsed.isPresent());- Assertions.assertArrayEquals(new long[] {12L, 9L}, parsed.get());- }+ Optional<long[]> cronBatchParsed = MaintenanceTaskIds.parseCronBatch("batch:12;policy:9");+ Assertions.assertTrue(cronBatchParsed.isPresent());+ Assertions.assertArrayEquals(new long[] {12L, 9L}, cronBatchParsed.get());- @Test- void testCommitTableRoundTrip() {Assertions.assertEquals("table:99", MaintenanceTaskIds.forCommitTable(99L));Assertions.assertEquals(99L, MaintenanceTaskIds.parseCommitTable("table:99").orElseThrow());- }- @Test- void testParseRejectsInvalid() {Assertions.assertTrue(MaintenanceTaskIds.parseExpandPolicy(null).isEmpty());Assertions.assertTrue(MaintenanceTaskIds.parseExpandPolicy("42").isEmpty());Assertions.assertTrue(MaintenanceTaskIds.parseExpandPolicy("policy:").isEmpty());diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/TestTableMaintenanceSchedulerPools.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/TestTableMaintenanceSchedulerPools.javadeleted file mode 100644index ce90bf342b..0000000000--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/TestTableMaintenanceSchedulerPools.java+++ /dev/null@@ -1,60 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */--package org.apache.gravitino.maintenance.scheduler;--import javax.sql.DataSource;-import org.apache.gravitino.Config;-import org.apache.gravitino.maintenance.TableMaintenanceConfig;-import org.apache.gravitino.storage.relational.TestJDBCBackend;-import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;-import org.junit.jupiter.api.AfterEach;-import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.TestTemplate;--class TestTableMaintenanceSchedulerPools extends TestJDBCBackend {-- private TableMaintenanceSchedulerPools pools;-- @AfterEach- void tearDown() {- if (pools != null) {- pools.stop();- }- }-- @TestTemplate- void testCronAndCommitPoolsStartAndStop() {- DataSource dataSource =- SqlSessionFactoryHelper.getInstance()- .getSqlSessionFactory()- .getConfiguration()- .getEnvironment()- .getDataSource();- pools = new TableMaintenanceSchedulerPools();- Config gravitinoConfig = new Config(false) {};- Assertions.assertDoesNotThrow(- () ->- pools.start(- dataSource,- TableMaintenanceConfig.forTest(1, 1, 1, 500L, 1_000L, 4, 10),- gravitinoConfig));- Assertions.assertDoesNotThrow(pools::stop);- }-}diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/TestMaintenanceAuthConsistency.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/TestMaintenanceAuthConsistency.javanew file mode 100644index 0000000000..225c889d7e--- /dev/null+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/TestMaintenanceAuthConsistency.java@@ -0,0 +1,153 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.maintenance.scheduler.job;++import java.time.Instant;+import java.util.List;+import java.util.Map;+import org.apache.gravitino.Config;+import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;+import org.apache.gravitino.meta.AuditInfo;+import org.apache.gravitino.meta.PolicyEntity;+import org.apache.gravitino.policy.IcebergDataCompactionContent;+import org.apache.gravitino.policy.Policy;+import org.apache.gravitino.policy.PolicyContents;+import org.apache.gravitino.utils.NamespaceUtil;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++class TestMaintenanceAuthConsistency {++ @Test+ void testAgreeingAuthPasses() {+ Config config = new Config(false) {};+ PolicyEntity a = policy(1L, Map.of("rest.auth.type", "none"), Map.of("auth_type", "none"));+ PolicyEntity b = policy(2L, Map.of("rest.auth.type", "none"), Map.of("auth_type", "none"));+ Assertions.assertDoesNotThrow(+ () -> MaintenanceAuthConsistency.requireSameAuth(List.of(a, b), config));+ }++ @Test+ void testMismatchingAuthFails() {+ Config config = new Config(false) {};+ IllegalArgumentException gravitino =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ MaintenanceAuthConsistency.requireSameAuth(+ List.of(+ policy(1L, Map.of(), Map.of("auth_type", "none")),+ policy(2L, Map.of(), Map.of("auth_type", "simple", "username", "u"))),+ config));+ Assertions.assertTrue(gravitino.getMessage().contains("gravitinoAuth mismatch"));+ Assertions.assertTrue(gravitino.getMessage().contains("auth_type"));++ IllegalArgumentException irc =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () ->+ MaintenanceAuthConsistency.requireSameAuth(+ List.of(+ policy(1L, Map.of("rest.auth.type", "none"), Map.of()),+ policy(2L, Map.of("rest.auth.type", "basic"), Map.of())),+ config));+ Assertions.assertTrue(irc.getMessage().contains("ircAuth mismatch"));+ Assertions.assertTrue(irc.getMessage().contains("differing keys=[rest.auth.type]"));+ }++ @Test+ void testMismatchMessageOmitsAuthValues() {+ Config config = new Config(false) {};+ String secretA = "SuperSecretPassword-A";+ String secretB = "SuperSecretPassword-B";+ PolicyEntity a =+ policy(+ 1L,+ Map.of("rest.auth.type", "basic", "rest.auth.basic.password", secretA),+ Map.of("auth_type", "basic", "password", secretA));+ PolicyEntity b =+ policy(+ 2L,+ Map.of("rest.auth.type", "basic", "rest.auth.basic.password", secretB),+ Map.of("auth_type", "basic", "password", secretB));+ IllegalArgumentException ex =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> MaintenanceAuthConsistency.requireSameAuth(List.of(a, b), config));+ String message = ex.getMessage();+ Assertions.assertFalse(message.contains(secretA), message);+ Assertions.assertFalse(message.contains(secretB), message);+ Assertions.assertTrue(message.contains("differing keys="), message);+ Assertions.assertTrue(+ message.contains("password") || message.contains("rest.auth.basic.password"), message);+ }++ @Test+ void testClusterIrcAuthOverlayMakesPoliciesAgree() {+ Config config = new Config(false) {};+ config.loadFromMap(Map.of("gravitino.maintenance.ircAuth.rest.auth.type", "basic"), t -> true);+ PolicyEntity a = policy(1L, Map.of("rest.auth.type", "none"), Map.of());+ PolicyEntity b = policy(2L, Map.of("rest.auth.type", "oauth"), Map.of());+ Assertions.assertDoesNotThrow(+ () -> MaintenanceAuthConsistency.requireSameAuth(List.of(a, b), config));+ }++ @Test+ void testHasSameAuth() {+ Config config = new Config(false) {};+ MaintenanceJobSpec left = spec("{\"auth_type\":\"none\"}", "{\"rest.auth.type\":\"none\"}");+ MaintenanceJobSpec right = spec("{\"auth_type\":\"none\"}", "{\"rest.auth.type\":\"none\"}");+ MaintenanceJobSpec mismatch =+ spec("{\"auth_type\":\"none\"}", "{\"rest.auth.type\":\"basic\"}");+ Assertions.assertTrue(MaintenanceAuthConsistency.hasSameAuth(config, left, right));+ Assertions.assertFalse(MaintenanceAuthConsistency.hasSameAuth(config, left, mismatch));+ }++ private static MaintenanceJobSpec spec(String updaterOptions, String sparkConf) {+ return new MaintenanceJobSpec(List.of(), updaterOptions, sparkConf);+ }++ private static PolicyEntity policy(+ long id, Map<String, String> jobOptions, Map<String, String> updaterOptions) {+ return PolicyEntity.builder()+ .withId(id)+ .withName("p-" + id)+ .withNamespace(NamespaceUtil.ofPolicy("ml"))+ .withPolicyType(Policy.BuiltInType.ICEBERG_COMPACTION)+ .withContent(+ PolicyContents.icebergDataCompaction(+ IcebergDataCompactionContent.DEFAULT_MIN_DATA_FILE_MSE,+ IcebergDataCompactionContent.DEFAULT_MIN_DELETE_FILE_NUMBER,+ IcebergDataCompactionContent.DEFAULT_DATA_FILE_MSE_WEIGHT,+ IcebergDataCompactionContent.DEFAULT_DELETE_FILE_NUMBER_WEIGHT,+ IcebergDataCompactionContent.DEFAULT_MAX_PARTITION_NUM,+ "binpack",+ "",+ Map.of(),+ null,+ true,+ null,+ jobOptions,+ updaterOptions))+ .withEnabled(true)+ .withAuditInfo(+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.EPOCH).build())+ .build();+ }+}diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestMaintenanceJobConfBuilder.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/TestMaintenanceJobConfBuilder.javasimilarity index 99%rename from plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestMaintenanceJobConfBuilder.javarename to plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/TestMaintenanceJobConfBuilder.javaindex b60bc5bd04..8880a1b598 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestMaintenanceJobConfBuilder.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/TestMaintenanceJobConfBuilder.java@@ -16,7 +16,7 @@* specific language governing permissions and limitations* under the License.*/-package org.apache.gravitino.maintenance.scheduler.job.cron;+package org.apache.gravitino.maintenance.scheduler.job;import java.time.Clock;import java.time.Instant;diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestMaintenanceJobTemplates.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/TestMaintenanceJobTemplates.javasimilarity index 97%rename from plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestMaintenanceJobTemplates.javarename to plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/TestMaintenanceJobTemplates.javaindex fe951b975f..59f360c589 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestMaintenanceJobTemplates.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/TestMaintenanceJobTemplates.java@@ -16,7 +16,7 @@* specific language governing permissions and limitations* under the License.*/-package org.apache.gravitino.maintenance.scheduler.job.cron;+package org.apache.gravitino.maintenance.scheduler.job;import org.apache.gravitino.policy.Policy;import org.junit.jupiter.api.Assertions;diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestCommitAuthConsistency.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestCommitAuthConsistency.javadeleted file mode 100644index 092ed061a6..0000000000--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestCommitAuthConsistency.java+++ /dev/null@@ -1,145 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.job.commit;--import java.time.Instant;-import java.util.List;-import java.util.Map;-import org.apache.gravitino.Config;-import org.apache.gravitino.meta.AuditInfo;-import org.apache.gravitino.meta.PolicyEntity;-import org.apache.gravitino.policy.IcebergDataCompactionContent;-import org.apache.gravitino.policy.Policy;-import org.apache.gravitino.policy.PolicyContents;-import org.apache.gravitino.utils.NamespaceUtil;-import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;--class TestCommitAuthConsistency {-- @Test- void testAgreeingAuthPasses() {- Config config = new Config(false) {};- CommitChainMember a = member(1L, Map.of("rest.auth.type", "none"), Map.of("auth_type", "none"));- CommitChainMember b = member(2L, Map.of("rest.auth.type", "none"), Map.of("auth_type", "none"));- Assertions.assertDoesNotThrow(- () -> CommitAuthConsistency.requireConsistent(List.of(a, b), config));- }-- @Test- void testMismatchingGravitinoAuthFails() {- Config config = new Config(false) {};- CommitChainMember a = member(1L, Map.of(), Map.of("auth_type", "none"));- CommitChainMember b = member(2L, Map.of(), Map.of("auth_type", "simple", "username", "u"));- IllegalArgumentException ex =- Assertions.assertThrows(- IllegalArgumentException.class,- () -> CommitAuthConsistency.requireConsistent(List.of(a, b), config));- String message = ex.getMessage();- Assertions.assertTrue(message.contains("gravitinoAuth mismatch"));- Assertions.assertTrue(message.contains("policy 1 vs policy 2"));- Assertions.assertTrue(message.contains("differing keys="));- Assertions.assertTrue(message.contains("auth_type"));- Assertions.assertTrue(message.contains("username"));- }-- @Test- void testMismatchingIrcAuthFails() {- Config config = new Config(false) {};- CommitChainMember a = member(1L, Map.of("rest.auth.type", "none"), Map.of());- CommitChainMember b = member(2L, Map.of("rest.auth.type", "basic"), Map.of());- IllegalArgumentException ex =- Assertions.assertThrows(- IllegalArgumentException.class,- () -> CommitAuthConsistency.requireConsistent(List.of(a, b), config));- String message = ex.getMessage();- Assertions.assertTrue(message.contains("ircAuth mismatch"));- Assertions.assertTrue(message.contains("policy 1 vs policy 2"));- Assertions.assertTrue(message.contains("differing keys=[rest.auth.type]"));- }-- @Test- void testMismatchMessageOmitsAuthValues() {- Config config = new Config(false) {};- String secretA = "SuperSecretPassword-A";- String secretB = "SuperSecretPassword-B";- CommitChainMember a =- member(- 1L,- Map.of("rest.auth.type", "basic", "rest.auth.basic.password", secretA),- Map.of("auth_type", "basic", "password", secretA));- CommitChainMember b =- member(- 2L,- Map.of("rest.auth.type", "basic", "rest.auth.basic.password", secretB),- Map.of("auth_type", "basic", "password", secretB));- IllegalArgumentException ex =- Assertions.assertThrows(- IllegalArgumentException.class,- () -> CommitAuthConsistency.requireConsistent(List.of(a, b), config));- String message = ex.getMessage();- Assertions.assertFalse(message.contains(secretA), message);- Assertions.assertFalse(message.contains(secretB), message);- Assertions.assertTrue(message.contains("differing keys="), message);- Assertions.assertTrue(- message.contains("password") || message.contains("rest.auth.basic.password"), message);- }-- @Test- void testClusterIrcAuthOverlayMakesPoliciesAgree() {- Config config = new Config(false) {};- config.loadFromMap(Map.of("gravitino.maintenance.ircAuth.rest.auth.type", "basic"), t -> true);- // Policies disagree in content, but cluster ircAuth wins on overlay.- CommitChainMember a = member(1L, Map.of("rest.auth.type", "none"), Map.of());- CommitChainMember b = member(2L, Map.of("rest.auth.type", "oauth"), Map.of());- Assertions.assertDoesNotThrow(- () -> CommitAuthConsistency.requireConsistent(List.of(a, b), config));- }-- private static CommitChainMember member(- long id, Map<String, String> jobOptions, Map<String, String> updaterOptions) {- PolicyEntity policy =- PolicyEntity.builder()- .withId(id)- .withName("p-" + id)- .withNamespace(NamespaceUtil.ofPolicy("ml"))- .withPolicyType(Policy.BuiltInType.ICEBERG_COMPACTION)- .withContent(- PolicyContents.icebergDataCompaction(- IcebergDataCompactionContent.DEFAULT_MIN_DATA_FILE_MSE,- IcebergDataCompactionContent.DEFAULT_MIN_DELETE_FILE_NUMBER,- IcebergDataCompactionContent.DEFAULT_DATA_FILE_MSE_WEIGHT,- IcebergDataCompactionContent.DEFAULT_DELETE_FILE_NUMBER_WEIGHT,- IcebergDataCompactionContent.DEFAULT_MAX_PARTITION_NUM,- "binpack",- "",- Map.of(),- null,- true,- null,- jobOptions,- updaterOptions))- .withEnabled(true)- .withAuditInfo(- AuditInfo.builder().withCreator("test").withCreateTime(Instant.EPOCH).build())- .build();- return new CommitChainMember(- Policy.BuiltInType.ICEBERG_COMPACTION, policy, "rewrite_data_files");- }-}diff --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.javadeleted file mode 100644index c464c49701..0000000000--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestCommitJobClient.java+++ /dev/null@@ -1,192 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.job.commit;--import com.github.kagkarlsson.scheduler.SchedulerClient;-import com.github.kagkarlsson.scheduler.task.TaskInstanceId;-import java.time.Instant;-import java.util.HashSet;-import java.util.List;-import java.util.Map;-import java.util.Optional;-import java.util.Set;-import java.util.function.Function;-import javax.sql.DataSource;-import org.apache.gravitino.Config;-import org.apache.gravitino.maintenance.policy.MaintenanceAuthConfigs;-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;-import org.apache.gravitino.maintenance.scheduler.MaintenanceTaskIds;-import org.apache.gravitino.maintenance.scheduler.TableMaintenanceSchedulerPools;-import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceTableRefs.ResolvedTableRef;-import org.apache.gravitino.meta.AuditInfo;-import org.apache.gravitino.meta.PolicyEntity;-import org.apache.gravitino.policy.IcebergDataCompactionContent;-import org.apache.gravitino.policy.Policy;-import org.apache.gravitino.policy.PolicyContents;-import org.apache.gravitino.storage.relational.TestJDBCBackend;-import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;-import org.apache.gravitino.utils.NamespaceUtil;-import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.TestTemplate;--class TestCommitJobClient extends TestJDBCBackend {-- private static final long TABLE_ID = 101L;- private static final long POLICY_ID = 202L;- private static final String GRAVITINO_URI = "http://localhost:8090";-- @TestTemplate- void testEnqueueSkipsWhenAllWithinMinInterval() {- CommitJobClient scheduler =- new CommitJobClient(- dataSource(),- configWithUri(),- fixedCollector(List.of(member(POLICY_ID))),- coolingGate(POLICY_ID));- Assertions.assertEquals(CommitJobEnqueueResult.SKIPPED, scheduler.enqueueNow(TABLE_ID));- Assertions.assertTrue(- CommitJobClient.schedulerClient(dataSource())- .getScheduledExecution(- TaskInstanceId.of(- TableMaintenanceSchedulerPools.COMMIT_JOB,- MaintenanceTaskIds.forCommitTable(TABLE_ID)))- .isEmpty());- }-- @TestTemplate- void testEnqueueWritesSpecAndIsIdempotent() {- CommitJobClient scheduler =- new CommitJobClient(- dataSource(),- configWithUri(),- fixedCollector(List.of(member(POLICY_ID))),- allowAllGate());-- Assertions.assertEquals(CommitJobEnqueueResult.INSERTED, scheduler.enqueueNow(TABLE_ID));- Assertions.assertEquals(CommitJobEnqueueResult.ALREADY_QUEUED, scheduler.enqueueNow(TABLE_ID));-- SchedulerClient client = CommitJobClient.schedulerClient(dataSource());- MaintenanceJobSpec spec =- (MaintenanceJobSpec)- client- .getScheduledExecution(- TaskInstanceId.of(- TableMaintenanceSchedulerPools.COMMIT_JOB,- MaintenanceTaskIds.forCommitTable(TABLE_ID)))- .get()- .getData();- Assertions.assertTrue(spec.isValid());- Assertions.assertEquals(List.of(TABLE_ID), spec.tableIds());- 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(- List<CommitChainMember> chain) {- ResolvedTableRef ref = new ResolvedTableRef(TABLE_ID, "iceberg", "db.t");- CollectedCommitChain collected = new CollectedCommitChain(chain, ref);- return tableId -> tableId == TABLE_ID ? Optional.of(collected) : Optional.empty();- }-- private static CommitChainMember member(long policyId) {- return new CommitChainMember(- Policy.BuiltInType.ICEBERG_COMPACTION, policy(policyId), "rewrite_data_files");- }-- private static CommitOccupancyGate allowAllGate() {- return new CommitOccupancyGate() {- @Override- public boolean isInFlight(long tableId, long policyId) {- return false;- }-- @Override- public boolean withinMinInterval(- long tableId, long policyId, long minIntervalMs, long nowMs) {- return false;- }- };- }-- private static CommitOccupancyGate coolingGate(long... policyIds) {- Set<Long> cooling = new HashSet<>();- for (long id : policyIds) {- cooling.add(id);- }- return new CommitOccupancyGate() {- @Override- public boolean isInFlight(long tableId, long policyId) {- return false;- }-- @Override- public boolean withinMinInterval(- long tableId, long policyId, long minIntervalMs, long nowMs) {- return cooling.contains(policyId);- }- };- }-- private static DataSource dataSource() {- return SqlSessionFactoryHelper.getInstance()- .getSqlSessionFactory()- .getConfiguration()- .getEnvironment()- .getDataSource();- }-- private static Config configWithUri() {- Config config = new Config(false) {};- config.loadFromMap(- Map.of(- MaintenanceAuthConfigs.GRAVITINO_MAINTENANCE_GRAVITINO_AUTH_URI.getKey(),- GRAVITINO_URI),- t -> true);- return config;- }-- private static PolicyEntity policy(long id) {- return PolicyEntity.builder()- .withId(id)- .withName("p-" + id)- .withNamespace(NamespaceUtil.ofPolicy("ml"))- .withPolicyType(Policy.BuiltInType.ICEBERG_COMPACTION)- .withContent(- PolicyContents.icebergDataCompaction(- IcebergDataCompactionContent.DEFAULT_MIN_DATA_FILE_MSE,- IcebergDataCompactionContent.DEFAULT_MIN_DELETE_FILE_NUMBER,- IcebergDataCompactionContent.DEFAULT_DATA_FILE_MSE_WEIGHT,- IcebergDataCompactionContent.DEFAULT_DELETE_FILE_NUMBER_WEIGHT,- IcebergDataCompactionContent.DEFAULT_MAX_PARTITION_NUM,- "binpack",- "",- Map.of(),- null,- true,- null,- Map.of("spark_executor_memory", "4g"),- Map.of("gravitino_uri", GRAVITINO_URI)))- .withEnabled(true)- .withAuditInfo(- AuditInfo.builder().withCreator("test").withCreateTime(Instant.EPOCH).build())- .build();- }-}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 ecf8dfd3f9..0c3ca9a985 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@@ -24,12 +24,12 @@ import java.util.List;import java.util.Map;import org.apache.gravitino.Config;import org.apache.gravitino.json.JsonUtils;+import org.apache.gravitino.maintenance.model.TableCandidate;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.maintenance.scheduler.job.MaintenanceJobTemplates;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.PolicyEntity;import org.apache.gravitino.policy.IcebergDataCompactionContent;@@ -45,16 +45,12 @@ class TestCommitJobSpecFactory {@Testvoid testForCommitBuildsPerTypeTasksAndSharedBags() {- CommitJobSpecFactory factory = new CommitJobSpecFactory(configWithUri());- CommitChainMember compaction =- new CommitChainMember(- Policy.BuiltInType.ICEBERG_COMPACTION, compaction(202L), "rewrite_data_files");- CommitChainMember expire =- new CommitChainMember(- Policy.BuiltInType.ICEBERG_SNAPSHOT_EXPIRATION, expire(303L), "expire_snapshots");+ MaintenanceJobSpecFactory factory = new MaintenanceJobSpecFactory(configWithUri());MaintenanceJobSpec spec =factory.forCommit(- List.of(compaction, expire), new ResolvedTableRef(101L, "iceberg", "db.t"));+ List.of(+ new TableCandidate(+ 101L, "iceberg", "db.t", List.of(compaction(202L), expire(303L)))));Assertions.assertTrue(spec.isValid());Assertions.assertEquals(2, spec.getTasks().size());@@ -86,26 +82,22 @@ class TestCommitJobSpecFactory {}@Test- void testMergeSparkConfMapsMergesByKey() {+ void testMergeSparkConfMaps() throws Exception {Map<String, String> into = new HashMap<>();into.put("spark.executor.memory", "4g");into.put("shared", "first");- CommitJobSpecFactory.mergeSparkConfMaps(+ MaintenanceJobSpecFactory.mergeSparkConfMaps(into,"{\"spark.executor.cores\":\"2\",\"shared\":\"later\",\"spark.driver.memory\":\"2g\"}");-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 testMergeSparkConfMapsAddsWhenMissing() throws Exception {- Map<String, String> into = new HashMap<>();- CommitJobSpecFactory.mergeSparkConfMaps(- into, JsonUtils.anyFieldMapper().writeValueAsString(Map.of("k", "v")));- Assertions.assertEquals("v", into.get("k"));+ Map<String, String> empty = new HashMap<>();+ MaintenanceJobSpecFactory.mergeSparkConfMaps(+ empty, JsonUtils.anyFieldMapper().writeValueAsString(Map.of("k", "v")));+ Assertions.assertEquals("v", empty.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 c86e823454..26150eafb7 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@@ -28,20 +28,20 @@ import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;-import java.util.HashSet;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Optional;import java.util.Set;import org.apache.gravitino.Config;+import org.apache.gravitino.maintenance.MaintenanceActionManager;+import org.apache.gravitino.maintenance.MaintenanceJobManager;+import org.apache.gravitino.maintenance.model.OccupancyClaim;import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;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;-import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceJobTemplates;-import org.apache.gravitino.maintenance.storage.service.OccupancyClaim;+import org.apache.gravitino.maintenance.scheduler.job.MaintenanceJobConfBuilder;+import org.apache.gravitino.maintenance.scheduler.job.MaintenanceJobTemplates;import org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Test;@@ -53,135 +53,86 @@ class TestMaintenanceCommitSubmitPipeline {private static final long POLICY_ID = 202L;private static final long EXPIRE_POLICY_ID = 303L;private static final long CLAIM_TIMEOUT_MS = 60_000L;+ private static final String UPDATER =+ "{\"gravitino_uri\":\"http://localhost:8090\",\"metalake\":\"ml\"}";@Test- void testUnparseableInstanceSkipsSubmit() {- MaintenanceJobSubmitter submitter = mock(MaintenanceJobSubmitter.class);+ void testEarlyExitsSkipSubmit() {+ MaintenanceJobManager mgr = mock(MaintenanceJobManager.class);TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);- pipeline(allowAllGate(), actions, submitter).submit("not-a-table-id", spec());- verify(submitter, never()).runJob(anyString(), anyString(), anyMap());- }+ String instance = MaintenanceTaskIds.forCommitTable(TABLE_ID);- @Test- void testNullSpecSkipsSubmit() {- MaintenanceJobSubmitter submitter = mock(MaintenanceJobSubmitter.class);- TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);- pipeline(allowAllGate(), actions, submitter)- .submit(MaintenanceTaskIds.forCommitTable(TABLE_ID), null);- verify(submitter, never()).runJob(anyString(), anyString(), anyMap());- verify(actions, never()).tryAcquireInFlightBatch(anyLong(), anyList(), anyLong());- }+ pipeline(Set.of(), actions, mgr).submit("not-a-table-id", spec());+ pipeline(Set.of(), actions, mgr).submit(instance, null);+ pipeline(Set.of(POLICY_ID), actions, mgr).submit(instance, spec());- @Test- void testInFlightRemainingMemberSkipsSubmit() {- MaintenanceJobSubmitter submitter = mock(MaintenanceJobSubmitter.class);- TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);- pipeline(inFlightGate(POLICY_ID), actions, submitter)- .submit(MaintenanceTaskIds.forCommitTable(TABLE_ID), spec());verify(actions, never()).tryAcquireInFlightBatch(anyLong(), anyList(), anyLong());- verify(submitter, never()).runJob(anyString(), anyString(), anyMap());+ verify(mgr, never()).submitAndBind(anyString(), anyMap(), anyList());}@Testvoid testSubmitClaimsEveryChainPolicyAndUsesSpecJobConf() {- MaintenanceJobSubmitter submitter = mock(MaintenanceJobSubmitter.class);- when(submitter.runJob(anyString(), anyString(), anyMap())).thenReturn(999L);- TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);+ MaintenanceJobManager mgr = mock(MaintenanceJobManager.class);List<OccupancyClaim> claims = List.of(new OccupancyClaim(1L, 2L), new OccupancyClaim(3L, 4L));+ when(mgr.submitAndBind(eq("ml"), anyMap(), eq(claims))).thenReturn(Optional.of(999L));+ TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);when(actions.tryAcquireInFlightBatch(eq(TABLE_ID), eq(List.of(POLICY_ID, EXPIRE_POLICY_ID)), eq(CLAIM_TIMEOUT_MS))).thenReturn(Optional.of(claims));- Map<String, String> p1 = new LinkedHashMap<>();- p1.put("catalog_name", "iceberg");- p1.put("table_identifier", "db.t");- Map<String, String> p2 = new LinkedHashMap<>(p1);+ Map<String, String> params =+ new LinkedHashMap<>(Map.of("catalog_name", "iceberg", "table_identifier", "db.t"));MaintenanceJobSpec spec =new MaintenanceJobSpec(List.of(- 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\"}",+ new Task(TABLE_ID, POLICY_ID, "rewrite_data_files", null, params),+ new Task(+ TABLE_ID,+ EXPIRE_POLICY_ID,+ "expire_snapshots",+ null,+ new LinkedHashMap<>(params))),+ UPDATER,null);- pipeline(allowAllGate(), actions, submitter)- .submit(MaintenanceTaskIds.forCommitTable(TABLE_ID), spec);+ pipeline(Set.of(), actions, mgr).submit(MaintenanceTaskIds.forCommitTable(TABLE_ID), spec);@SuppressWarnings("unchecked")ArgumentCaptor<Map<String, String>> confCaptor = ArgumentCaptor.forClass(Map.class);- verify(submitter)- .runJob(- eq("ml"),- eq(MaintenanceJobTemplates.ICEBERG_MAINTENANCE_TEMPLATE),- confCaptor.capture());- verify(actions).bindJobIds(claims, 999L);- verify(actions, never()).bindJobId(org.mockito.ArgumentMatchers.any(), anyLong());-+ verify(mgr).submitAndBind(eq("ml"), confCaptor.capture(), eq(claims));Map<String, String> conf = confCaptor.getValue();Assertions.assertEquals("rewrite_data_files,expire_snapshots",conf.get(MaintenanceJobTemplates.MAINTENANCE_TYPES_KEY));- Assertions.assertFalse(conf.containsKey("tms_table_id"));- Assertions.assertFalse(conf.containsKey("tms_policy_id"));- Assertions.assertEquals("iceberg", conf.get("catalog_name"));Assertions.assertNull(conf.get("table_identifier"));- Assertions.assertTrue(conf.get("tables").contains("\"table_identifier\":\"db.t\""));Assertions.assertTrue(conf.get("tables").contains("\"table_id\":" + TABLE_ID));}private static MaintenanceCommitSubmitPipeline pipeline(- CommitOccupancyGate gate,+ Set<Long> inFlightPolicies,TableMaintenanceActionMetaService actions,- MaintenanceJobSubmitter submitter) {+ MaintenanceJobManager mgr) {+ TableMaintenanceActionMetaService gateMeta = mock(TableMaintenanceActionMetaService.class);+ when(gateMeta.hasLiveUnboundClaim(anyLong(), anyLong(), anyLong()))+ .thenAnswer(inv -> inFlightPolicies.contains((Long) inv.getArgument(1)));+ when(gateMeta.listInFlight(anyLong(), anyLong())).thenReturn(List.of());+ // MaintenanceActionManager is final; drive isOccupied via a stub meta service.+ MaintenanceActionManager actionManager =+ new MaintenanceActionManager(gateMeta, CLAIM_TIMEOUT_MS);return new MaintenanceCommitSubmitPipeline(- gate,+ actionManager,actions,- submitter,+ mgr,new MaintenanceJobConfBuilder(new Config(false) {}),CLAIM_TIMEOUT_MS);}- private static CommitOccupancyGate allowAllGate() {- return new CommitOccupancyGate() {- @Override- public boolean isInFlight(long tableId, long policyId) {- return false;- }-- @Override- public boolean withinMinInterval(- long tableId, long policyId, long minIntervalMs, long nowMs) {- return false;- }- };- }-- private static CommitOccupancyGate inFlightGate(long... policyIds) {- Set<Long> blocked = new HashSet<>();- for (long id : policyIds) {- blocked.add(id);- }- return new CommitOccupancyGate() {- @Override- public boolean isInFlight(long tableId, long policyId) {- return blocked.contains(policyId);- }-- @Override- public boolean withinMinInterval(- long tableId, long policyId, long minIntervalMs, long nowMs) {- return false;- }- };- }-private static MaintenanceJobSpec spec() {- Map<String, String> parameters = new LinkedHashMap<>();- parameters.put("catalog_name", "iceberg");- parameters.put("table_identifier", "db.t");+ Map<String, String> parameters =+ new LinkedHashMap<>(Map.of("catalog_name", "iceberg", "table_identifier", "db.t"));return new MaintenanceJobSpec(List.of(new Task(TABLE_ID, POLICY_ID, "rewrite_data_files", null, parameters)),- "{\"gravitino_uri\":\"http://localhost:8090\",\"metalake\":\"ml\"}",+ UPDATER,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 4731dd87a8..a9b28f7f30 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@@ -32,14 +32,12 @@ import java.util.stream.Collectors;import java.util.stream.LongStream;import javax.sql.DataSource;import org.apache.gravitino.Config;-import org.apache.gravitino.MetadataObject;import org.apache.gravitino.json.JsonUtils;+import org.apache.gravitino.maintenance.model.TableCandidate;import org.apache.gravitino.maintenance.policy.MaintenanceAuthConfigs;import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;+import org.apache.gravitino.maintenance.scheduler.MaintenanceSchedulerPools;import org.apache.gravitino.maintenance.scheduler.MaintenanceTaskIds;-import org.apache.gravitino.maintenance.scheduler.TableMaintenanceSchedulerPools;-import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceTableRefs.ResolvedTableRef;-import org.apache.gravitino.maintenance.scheduler.policy.expand.ExpandTableCandidate;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.PolicyEntity;import org.apache.gravitino.policy.IcebergDataCompactionContent;@@ -56,46 +54,35 @@ class TestCronJobClient extends TestJDBCBackend {private static final String GRAVITINO_URI = "http://localhost:8090";@TestTemplate- void testEnqueueIsIdempotentAndRespectsBatchSize() {+ void testScheduleIsIdempotentAndRespectsBatchSize() {DataSource dataSource = dataSource();CronJobClient scheduler = scheduler(dataSource);PolicyEntity policy = compactionPolicy(7L);- List<ExpandTableCandidate> three =- List.of(- candidate(1L, MetadataObject.Type.TABLE),- candidate(2L, MetadataObject.Type.TABLE),- candidate(3L, MetadataObject.Type.TABLE));- Assertions.assertEquals(2, scheduler.enqueueNow(policy, three, 2));+ List<TableCandidate> three =+ List.of(candidate(1L, policy), candidate(2L, policy), candidate(3L, policy));+ Assertions.assertEquals(2, scheduler.scheduleNow(policy, three, 2));Assertions.assertEquals(- 0,- scheduler.enqueueNow(- policy,- List.of(- candidate(1L, MetadataObject.Type.TABLE), candidate(2L, MetadataObject.Type.TABLE)),- 2));+ 0, scheduler.scheduleNow(policy, List.of(candidate(1L, policy), candidate(2L, policy)), 2));SchedulerClient client = CronJobClient.schedulerClient(dataSource);Assertions.assertTrue(client.getScheduledExecution(TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB,- MaintenanceTaskIds.forCronTable(1L, 7L)))+ MaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronTable(1L, 7L))).isPresent());Assertions.assertTrue(client.getScheduledExecution(TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB,- MaintenanceTaskIds.forCronTable(2L, 7L)))+ MaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronTable(2L, 7L))).isPresent());Assertions.assertTrue(client.getScheduledExecution(TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB,- MaintenanceTaskIds.forCronTable(3L, 7L)))+ MaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronTable(3L, 7L))).isEmpty());MaintenanceJobSpec spec =@@ -103,7 +90,7 @@ class TestCronJobClient extends TestJDBCBackend {client.getScheduledExecution(TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB,+ MaintenanceSchedulerPools.CRON_JOB,MaintenanceTaskIds.forCronTable(1L, 7L))).get().getData();@@ -113,45 +100,44 @@ class TestCronJobClient extends TestJDBCBackend {}@TestTemplate- void testSnapshotExpiryFillsIncompleteBatchBeforeAllocatingNextId() {+ void testSnapshotExpiryMergesIntoIncompleteBatch() {DataSource dataSource = dataSource();CronJobClient scheduler = scheduler(dataSource);PolicyEntity policy = expirePolicy(9L);+ SchedulerClient client = CronJobClient.schedulerClient(dataSource);+ TaskInstanceId batch0 =+ TaskInstanceId.of(+ MaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronBatch(0L, 9L));Assertions.assertEquals(1,- scheduler.enqueueNow(- policy,- List.of(- candidate(10L, MetadataObject.Type.SCHEMA),- candidate(11L, MetadataObject.Type.SCHEMA)),- 10));-+ scheduler.scheduleNow(policy, List.of(candidate(10L, policy), candidate(11L, policy)), 10));Assertions.assertEquals(0,- scheduler.enqueueNow(+ scheduler.scheduleNow(policy,List.of(- candidate(10L, MetadataObject.Type.SCHEMA),- candidate(11L, MetadataObject.Type.SCHEMA),- candidate(12L, MetadataObject.Type.CATALOG),- candidate(13L, MetadataObject.Type.SCHEMA)),+ candidate(10L, policy),+ candidate(11L, policy),+ candidate(12L, policy),+ candidate(13L, policy)),10));-- SchedulerClient client = CronJobClient.schedulerClient(dataSource);- TaskInstanceId batch0 =- TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronBatch(0L, 9L));- TaskInstanceId batch1 =- TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronBatch(1L, 9L));- Assertions.assertTrue(client.getScheduledExecution(batch0).isPresent());- Assertions.assertTrue(client.getScheduledExecution(batch1).isEmpty());- MaintenanceJobSpec data =+ Assertions.assertTrue(+ client+ .getScheduledExecution(+ TaskInstanceId.of(+ MaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronBatch(1L, 9L)))+ .isEmpty());+ MaintenanceJobSpec filled =(MaintenanceJobSpec) client.getScheduledExecution(batch0).get().getData();- Assertions.assertEquals(List.of(10L, 11L, 12L, 13L), data.tableIds());- Assertions.assertEquals(4, data.getTasks().size());- Assertions.assertTrue(data.getUpdaterOptions() != null && !data.getUpdaterOptions().isBlank());+ Assertions.assertEquals(List.of(10L, 11L, 12L, 13L), filled.tableIds());+ Assertions.assertTrue(+ filled.getUpdaterOptions() != null && !filled.getUpdaterOptions().isBlank());++ Assertions.assertEquals(0, scheduler.scheduleNow(policy, List.of(candidate(99L, policy)), 10));+ Assertions.assertEquals(+ List.of(10L, 11L, 12L, 13L, 99L),+ ((MaintenanceJobSpec) client.getScheduledExecution(batch0).get().getData()).tableIds());}@TestTemplate@@ -161,11 +147,11 @@ class TestCronJobClient extends TestJDBCBackend {PolicyEntity policy = expirePolicy(9L);int cap = 10; // CronJobClient snapshot-expiry batch capacity- List<ExpandTableCandidate> full = schemaCandidates(1, cap);- Assertions.assertEquals(1, scheduler.enqueueNow(policy, full, 100));- List<ExpandTableCandidate> fullPlusOne = new ArrayList<>(full);- fullPlusOne.add(candidate(cap + 1L, MetadataObject.Type.SCHEMA));- Assertions.assertEquals(1, scheduler.enqueueNow(policy, fullPlusOne, 100));+ List<TableCandidate> full = schemaCandidates(1, cap, policy);+ Assertions.assertEquals(1, scheduler.scheduleNow(policy, full, 100));+ List<TableCandidate> fullPlusOne = new ArrayList<>(full);+ fullPlusOne.add(candidate(cap + 1L, policy));+ Assertions.assertEquals(1, scheduler.scheduleNow(policy, fullPlusOne, 100));SchedulerClient client = CronJobClient.schedulerClient(dataSource);MaintenanceJobSpec batch0 =@@ -173,7 +159,7 @@ class TestCronJobClient extends TestJDBCBackend {client.getScheduledExecution(TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB,+ MaintenanceSchedulerPools.CRON_JOB,MaintenanceTaskIds.forCronBatch(0L, 9L))).get().getData();@@ -182,7 +168,7 @@ class TestCronJobClient extends TestJDBCBackend {client.getScheduledExecution(TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB,+ MaintenanceSchedulerPools.CRON_JOB,MaintenanceTaskIds.forCronBatch(1L, 9L))).get().getData();@@ -191,166 +177,80 @@ class TestCronJobClient extends TestJDBCBackend {}@TestTemplate- void testSnapshotExpiryIncompleteBatchAbsorbsUnpickedTableJob() {- DataSource dataSource = dataSource();- CronJobClient scheduler = scheduler(dataSource);- PolicyEntity policy = expirePolicy(9L);-- Assertions.assertEquals(- 1, scheduler.enqueueNow(policy, List.of(candidate(99L, MetadataObject.Type.TABLE)), 10));-- SchedulerClient client = CronJobClient.schedulerClient(dataSource);- TaskInstanceId tableJob =- TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronTable(99L, 9L));- Assertions.assertTrue(client.getScheduledExecution(tableJob).isPresent());-- Assertions.assertEquals(- 1,- scheduler.enqueueNow(- policy,- List.of(- candidate(10L, MetadataObject.Type.SCHEMA),- candidate(11L, MetadataObject.Type.SCHEMA)),- 10));-- TaskInstanceId batch0 =- TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronBatch(0L, 9L));- Assertions.assertTrue(client.getScheduledExecution(batch0).isPresent());- Assertions.assertTrue(- client.getScheduledExecution(tableJob).isEmpty(),- "unpicked table: row should be cancelled after merge into batch");- MaintenanceJobSpec data =- (MaintenanceJobSpec) client.getScheduledExecution(batch0).get().getData();- Assertions.assertEquals(List.of(10L, 11L, 99L), data.tableIds());- }-- @TestTemplate- void testSnapshotExpiryTableJobsCoalesceIntoBatch() {+ void testSnapshotExpiryMergesAcrossPoliciesSameCatalog() {DataSource dataSource = dataSource();CronJobClient scheduler = scheduler(dataSource);- PolicyEntity policy = expirePolicy(9L);+ PolicyEntity policy9 = expirePolicy(9L);+ PolicyEntity policy10 = expirePolicy(10L);Assertions.assertEquals(- 1, scheduler.enqueueNow(policy, List.of(candidate(21L, MetadataObject.Type.TABLE)), 10));+ 1, scheduler.scheduleNow(policy9, List.of(candidate(21L, policy9)), 10));Assertions.assertEquals(- 1, scheduler.enqueueNow(policy, List.of(candidate(22L, MetadataObject.Type.TABLE)), 10));+ 0, scheduler.scheduleNow(policy10, List.of(candidate(22L, policy10)), 10));SchedulerClient client = CronJobClient.schedulerClient(dataSource);- TaskInstanceId table21 =- TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronTable(21L, 9L));- TaskInstanceId table22 =- TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronTable(22L, 9L));TaskInstanceId batch0 =TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronBatch(0L, 9L));- Assertions.assertTrue(client.getScheduledExecution(table21).isEmpty());- Assertions.assertTrue(client.getScheduledExecution(table22).isEmpty());+ MaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronBatch(0L, 9L));Assertions.assertTrue(client.getScheduledExecution(batch0).isPresent());MaintenanceJobSpec data =(MaintenanceJobSpec) client.getScheduledExecution(batch0).get().getData();- Assertions.assertEquals(List.of(22L, 21L), data.tableIds());+ Assertions.assertEquals(List.of(21L, 22L), data.tableIds());+ Assertions.assertEquals(9L, data.getTasks().get(0).getPolicyId());+ Assertions.assertEquals(10L, data.getTasks().get(1).getPolicyId());}@TestTemplate- void testSnapshotExpiryTableMergesIntoExistingIncompleteBatch() {+ void testSnapshotExpiryDoesNotMergeAuthMismatch() {DataSource dataSource = dataSource();CronJobClient scheduler = scheduler(dataSource);- PolicyEntity policy = expirePolicy(9L);+ PolicyEntity policy9 = expirePolicyWithAuth(9L, Map.of("auth_type", "none"));+ PolicyEntity policy10 =+ expirePolicyWithAuth(10L, Map.of("auth_type", "simple", "username", "u"));Assertions.assertEquals(- 1,- scheduler.enqueueNow(- policy,- List.of(- candidate(10L, MetadataObject.Type.SCHEMA),- candidate(11L, MetadataObject.Type.SCHEMA)),- 10));+ 1, scheduler.scheduleNow(policy9, List.of(candidate(21L, policy9)), 10));Assertions.assertEquals(- 0, scheduler.enqueueNow(policy, List.of(candidate(99L, MetadataObject.Type.TABLE)), 10));-- SchedulerClient client = CronJobClient.schedulerClient(dataSource);- TaskInstanceId tableJob =- TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronTable(99L, 9L));- TaskInstanceId batch0 =- TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronBatch(0L, 9L));- Assertions.assertTrue(client.getScheduledExecution(tableJob).isEmpty());- MaintenanceJobSpec data =- (MaintenanceJobSpec) client.getScheduledExecution(batch0).get().getData();- Assertions.assertEquals(List.of(10L, 11L, 99L), data.tableIds());- }-- @TestTemplate- void testSnapshotExpiryMergesAcrossPoliciesSameCatalog() {- DataSource dataSource = dataSource();- CronJobClient scheduler = scheduler(dataSource);-- Assertions.assertEquals(- 1,- scheduler.enqueueNow(- expirePolicy(9L), List.of(candidate(21L, MetadataObject.Type.TABLE)), 10));- Assertions.assertEquals(- 1,- scheduler.enqueueNow(- expirePolicy(10L), List.of(candidate(22L, MetadataObject.Type.TABLE)), 10));+ 1, scheduler.scheduleNow(policy10, List.of(candidate(22L, policy10)), 10));SchedulerClient client = CronJobClient.schedulerClient(dataSource);Assertions.assertTrue(client.getScheduledExecution(TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB,- MaintenanceTaskIds.forCronTable(21L, 9L)))- .isEmpty());+ MaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronBatch(0L, 9L)))+ .isPresent(),+ "auth-mismatched peer must not be cancelled");Assertions.assertTrue(client.getScheduledExecution(TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB,- MaintenanceTaskIds.forCronTable(22L, 10L)))- .isEmpty());- TaskInstanceId batch0 =- TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronBatch(0L, 10L));- Assertions.assertTrue(client.getScheduledExecution(batch0).isPresent());- MaintenanceJobSpec data =- (MaintenanceJobSpec) client.getScheduledExecution(batch0).get().getData();- Assertions.assertEquals(List.of(22L, 21L), data.tableIds());+ MaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronBatch(0L, 10L)))+ .isPresent());}@TestTemplatevoid testSnapshotExpiryDoesNotMergeDifferentCatalogs() {DataSource dataSource = dataSource();- CronJobClient scheduler = multiCatalogScheduler(dataSource);+ CronJobClient scheduler = scheduler(dataSource);+ PolicyEntity policy = expirePolicy(9L);+ Assertions.assertEquals(1, scheduler.scheduleNow(policy, List.of(candidate(1L, policy)), 10));Assertions.assertEquals(- 1,- scheduler.enqueueNow(- expirePolicy(9L), List.of(candidate(1L, MetadataObject.Type.TABLE)), 10));- Assertions.assertEquals(- 1,- scheduler.enqueueNow(- expirePolicy(9L), List.of(candidate(1001L, MetadataObject.Type.TABLE)), 10));+ 1, scheduler.scheduleNow(policy, List.of(candidate(1001L, policy)), 10));SchedulerClient client = CronJobClient.schedulerClient(dataSource);Assertions.assertTrue(client.getScheduledExecution(TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB,- MaintenanceTaskIds.forCronTable(1L, 9L)))+ MaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronBatch(0L, 9L))).isPresent());Assertions.assertTrue(client.getScheduledExecution(TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB,- MaintenanceTaskIds.forCronTable(1001L, 9L)))+ MaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronBatch(1L, 9L))).isPresent());}@@ -361,16 +261,13 @@ class TestCronJobClient extends TestJDBCBackend {PolicyEntity policy = expirePolicy(9L);int cap = 10; // CronJobClient snapshot-expiry batch capacity- // Full batch at capacity — must not be absorbed into a later incomplete peer.- Assertions.assertEquals(1, scheduler.enqueueNow(policy, schemaCandidates(1, cap), 100));+ // Full batch at capacity — must not be claimed into a later incomplete peer.+ Assertions.assertEquals(+ 1, scheduler.scheduleNow(policy, schemaCandidates(1, cap, policy), 100));Assertions.assertEquals(1,- scheduler.enqueueNow(- policy,- List.of(- candidate(100L, MetadataObject.Type.SCHEMA),- candidate(101L, MetadataObject.Type.SCHEMA)),- 100));+ scheduler.scheduleNow(+ policy, List.of(candidate(100L, policy), candidate(101L, policy)), 100));SchedulerClient client = CronJobClient.schedulerClient(dataSource);MaintenanceJobSpec batch0 =@@ -378,7 +275,7 @@ class TestCronJobClient extends TestJDBCBackend {client.getScheduledExecution(TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB,+ MaintenanceSchedulerPools.CRON_JOB,MaintenanceTaskIds.forCronBatch(0L, 9L))).get().getData();@@ -387,7 +284,7 @@ class TestCronJobClient extends TestJDBCBackend {client.getScheduledExecution(TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB,+ MaintenanceSchedulerPools.CRON_JOB,MaintenanceTaskIds.forCronBatch(1L, 9L))).get().getData();@@ -396,45 +293,39 @@ class TestCronJobClient extends TestJDBCBackend {}@TestTemplate- void testPendingCronGateSkipsQueuedTables() {+ void testIsTableAlreadyQueuedSkipsQueuedTables() {DataSource dataSource = dataSource();CronJobClient scheduler = scheduler(dataSource);+ PolicyEntity policy = expirePolicy(9L);Assertions.assertEquals(1,- scheduler.enqueueNow(- expirePolicy(9L),- List.of(- candidate(10L, MetadataObject.Type.SCHEMA),- candidate(11L, MetadataObject.Type.SCHEMA)),- 10));+ scheduler.scheduleNow(policy, List.of(candidate(10L, policy), candidate(11L, policy)), 10));- PendingCronExpandOccupancyGate gate =- new PendingCronExpandOccupancyGate((t, p, m, n) -> false, dataSource);- Assertions.assertTrue(gate.shouldSkip(10L, 9L, 0L, System.currentTimeMillis()));- Assertions.assertFalse(gate.shouldSkip(12L, 9L, 0L, System.currentTimeMillis()));+ Assertions.assertTrue(scheduler.isTableAlreadyQueued(10L, 9L));+ Assertions.assertFalse(scheduler.isTableAlreadyQueued(12L, 9L));}@TestTemplatevoid testCronJobTaskRemovesRowAfterPick() throws Exception {DataSource dataSource = dataSource();- CronJobClient enqueue = scheduler(dataSource);+ CronJobClient cronJobs = scheduler(dataSource);Assertions.assertEquals(1,- enqueue.enqueueNow(- compactionPolicy(9L), List.of(candidate(99L, MetadataObject.Type.TABLE)), 1));+ cronJobs.scheduleNow(+ compactionPolicy(9L), List.of(candidate(99L, compactionPolicy(9L))), 1));TaskInstanceId instanceId =TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronTable(99L, 9L));+ MaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronTable(99L, 9L));SchedulerClient client = CronJobClient.schedulerClient(dataSource);Assertions.assertTrue(client.getScheduledExecution(instanceId).isPresent());Scheduler cronPool =- Scheduler.create(dataSource, TableMaintenanceSchedulerPools.cronJobTask())+ Scheduler.create(dataSource, MaintenanceSchedulerPools.cronJobTask()).threads(1).pollingInterval(Duration.ofMillis(100)).serializer(new JacksonSerializer(JsonUtils.anyFieldMapper()))- .tableName(TableMaintenanceSchedulerPools.CRON_TASKS_TABLE)+ .tableName(MaintenanceSchedulerPools.CRON_TASKS_TABLE).commitWhenAutocommitDisabled(true).build();cronPool.start();@@ -451,30 +342,13 @@ class TestCronJobClient extends TestJDBCBackend {Assertions.assertEquals(1,- enqueue.enqueueNow(- compactionPolicy(9L), List.of(candidate(99L, MetadataObject.Type.TABLE)), 1));+ cronJobs.scheduleNow(+ compactionPolicy(9L), List.of(candidate(99L, compactionPolicy(9L))), 1));Assertions.assertTrue(client.getScheduledExecution(instanceId).isPresent());}private static CronJobClient scheduler(DataSource dataSource) {- return new CronJobClient(- dataSource,- configWithUri(),- ids ->- ids.stream()- .map(id -> new ResolvedTableRef(id, "iceberg", "db.t" + id))- .collect(Collectors.toList()));- }-- /** Tables with id >= 1000 resolve to catalog {@code other}; others to {@code iceberg}. */- private static CronJobClient multiCatalogScheduler(DataSource dataSource) {- return new CronJobClient(- dataSource,- configWithUri(),- ids ->- ids.stream()- .map(id -> new ResolvedTableRef(id, id >= 1000L ? "other" : "iceberg", "db.t" + id))- .collect(Collectors.toList()));+ return new CronJobClient(dataSource, configWithUri());}private static DataSource dataSource() {@@ -495,13 +369,15 @@ class TestCronJobClient extends TestJDBCBackend {return config;}- private static ExpandTableCandidate candidate(long tableId, MetadataObject.Type level) {- return new ExpandTableCandidate(tableId, level);+ private static TableCandidate candidate(long tableId, PolicyEntity policy) {+ String catalog = tableId >= 1000L ? "other" : "iceberg";+ return new TableCandidate(tableId, catalog, "db.t" + tableId, List.of(policy));}- private static List<ExpandTableCandidate> schemaCandidates(long fromInclusive, long toInclusive) {+ private static List<TableCandidate> schemaCandidates(+ long fromInclusive, long toInclusive, PolicyEntity policy) {return LongStream.rangeClosed(fromInclusive, toInclusive)- .mapToObj(id -> candidate(id, MetadataObject.Type.SCHEMA))+ .mapToObj(id -> candidate(id, policy)).collect(Collectors.toList());}@@ -544,4 +420,18 @@ class TestCronJobClient extends TestJDBCBackend {AuditInfo.builder().withCreator("test").withCreateTime(Instant.EPOCH).build()).build();}++ private static PolicyEntity expirePolicyWithAuth(long id, Map<String, String> updaterOptions) {+ return PolicyEntity.builder()+ .withId(id)+ .withName("e-" + id)+ .withNamespace(NamespaceUtil.ofPolicy("ml"))+ .withPolicyType(Policy.BuiltInType.ICEBERG_SNAPSHOT_EXPIRATION)+ .withEnabled(true)+ .withContent(+ PolicyContents.icebergSnapshotExpiration(null, null, null, null, updaterOptions))+ .withAuditInfo(+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.EPOCH).build())+ .build();+ }}diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestMaintenanceCronSubmitPipeline.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestMaintenanceCronSubmitPipeline.javanew file mode 100644index 0000000000..cc90f74925--- /dev/null+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestMaintenanceCronSubmitPipeline.java@@ -0,0 +1,255 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.maintenance.scheduler.job.cron;++import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyList;+import static org.mockito.ArgumentMatchers.anyLong;+import static org.mockito.ArgumentMatchers.anyMap;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.times;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.function.BiPredicate;+import org.apache.gravitino.Config;+import org.apache.gravitino.maintenance.MaintenanceActionManager;+import org.apache.gravitino.maintenance.MaintenanceJobManager;+import org.apache.gravitino.maintenance.model.OccupancyClaim;+import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;+import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.Task;+import org.apache.gravitino.maintenance.scheduler.MaintenanceTaskIds;+import org.apache.gravitino.maintenance.scheduler.job.MaintenanceJobConfBuilder;+import org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;+import org.mockito.ArgumentCaptor;++class TestMaintenanceCronSubmitPipeline {++ private static final long TABLE_ID = 101L;+ private static final long POLICY_ID = 202L;+ private static final String INSTANCE = MaintenanceTaskIds.forCronTable(TABLE_ID, POLICY_ID);+ private static final long CLAIM_TIMEOUT_MS = 60_000L;+ private static final String UPDATER =+ "{\"gravitino_uri\":\"http://localhost:8090\",\"metalake\":\"metalake\"}";++ @Test+ void testEarlyExitsSkipClaimAndSubmit() {+ MaintenanceJobManager mgr = mock(MaintenanceJobManager.class);+ TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);++ pipeline(false, actions, mgr).submit("not-a-cron-id", spec());+ pipeline(false, actions, mgr).submit(INSTANCE, null);+ pipeline(false, actions, mgr)+ .submit(MaintenanceTaskIds.forCronTable(TABLE_ID, POLICY_ID + 1), spec());+ pipeline(true, actions, mgr).submit(INSTANCE, spec());+ pipeline((t, p) -> t == 11L, actions, mgr)+ .submit(MaintenanceTaskIds.forCronBatch(0L, POLICY_ID), batchSpec(10L, 11L));++ verify(actions, never()).tryAcquireInFlight(anyLong(), anyLong(), anyLong());+ verify(mgr, never()).submitAndBind(anyString(), anyMap(), anyList());+ }++ @Test+ void testLostClaimRaceSkipsSubmit() {+ MaintenanceJobManager mgr = mock(MaintenanceJobManager.class);+ TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);+ when(actions.tryAcquireInFlight(TABLE_ID, POLICY_ID, CLAIM_TIMEOUT_MS))+ .thenReturn(Optional.empty());+ pipeline(false, actions, mgr).submit(INSTANCE, spec());+ verify(mgr, never()).submitAndBind(anyString(), anyMap(), anyList());+ }++ @Test+ void testConfResolveFailureReleasesClaimWithoutSubmit() {+ MaintenanceJobManager mgr = mock(MaintenanceJobManager.class);+ TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);+ OccupancyClaim claim = new OccupancyClaim(8L, 2_000L);+ when(actions.tryAcquireInFlight(TABLE_ID, POLICY_ID, CLAIM_TIMEOUT_MS))+ .thenReturn(Optional.of(claim));+ when(actions.deleteUnboundClaim(claim)).thenReturn(true);++ Assertions.assertDoesNotThrow(+ () -> pipeline(false, actions, mgr).submit(INSTANCE, spec(Map.of(), "{not-json")));+ verify(actions).deleteUnboundClaim(claim);+ verify(mgr, never()).submitAndBind(anyString(), anyMap(), anyList());+ }++ @Test+ void testBatchSubmitOneSparkJobPerTable() {+ MaintenanceJobManager mgr = mock(MaintenanceJobManager.class);+ when(mgr.submitAndBind(anyString(), anyMap(), anyList()))+ .thenReturn(Optional.of(555L), Optional.of(556L));+ TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);+ OccupancyClaim claimA = new OccupancyClaim(1L, 10L);+ OccupancyClaim claimB = new OccupancyClaim(2L, 20L);+ when(actions.tryAcquireInFlight(10L, POLICY_ID, CLAIM_TIMEOUT_MS))+ .thenReturn(Optional.of(claimA));+ when(actions.tryAcquireInFlight(11L, POLICY_ID, CLAIM_TIMEOUT_MS))+ .thenReturn(Optional.of(claimB));++ pipeline(false, actions, mgr)+ .submit(MaintenanceTaskIds.forCronBatch(0L, POLICY_ID), batchSpec(10L, 11L));++ @SuppressWarnings("unchecked")+ ArgumentCaptor<Map<String, String>> confs = ArgumentCaptor.forClass(Map.class);+ @SuppressWarnings("unchecked")+ ArgumentCaptor<List<OccupancyClaim>> claims = ArgumentCaptor.forClass(List.class);+ verify(mgr, times(2)).submitAndBind(eq("metalake"), confs.capture(), claims.capture());+ Assertions.assertTrue(confs.getAllValues().get(0).get("tables").contains("db.t1"));+ Assertions.assertTrue(confs.getAllValues().get(1).get("tables").contains("db.t2"));+ Assertions.assertEquals(List.of(List.of(claimA), List.of(claimB)), claims.getAllValues());+ }++ @Test+ void testMixedPolicySpecSubmitsEachTask() {+ long peerTable = TABLE_ID + 1;+ long policyB = POLICY_ID + 1;+ MaintenanceJobManager mgr = mock(MaintenanceJobManager.class);+ when(mgr.submitAndBind(anyString(), anyMap(), anyList())).thenReturn(Optional.of(1L));+ TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);+ when(actions.tryAcquireInFlight(TABLE_ID, POLICY_ID, CLAIM_TIMEOUT_MS))+ .thenReturn(Optional.of(new OccupancyClaim(1L, 10L)));+ when(actions.tryAcquireInFlight(peerTable, policyB, CLAIM_TIMEOUT_MS))+ .thenReturn(Optional.of(new OccupancyClaim(2L, 20L)));+ MaintenanceJobSpec mixed = expireSpec(TABLE_ID, POLICY_ID, peerTable, policyB);++ MaintenanceCronSubmitPipeline submit = pipeline(false, actions, mgr);+ submit.submit(MaintenanceTaskIds.forCronBatch(0L, POLICY_ID), mixed);+ submit.submit(INSTANCE, mixed);++ verify(actions, times(2)).tryAcquireInFlight(TABLE_ID, POLICY_ID, CLAIM_TIMEOUT_MS);+ verify(actions, times(2)).tryAcquireInFlight(peerTable, policyB, CLAIM_TIMEOUT_MS);+ verify(mgr, times(4)).submitAndBind(eq("metalake"), anyMap(), anyList());+ }++ @Test+ void testBatchInFlightUsesPerTaskPolicyId() {+ long peerTable = TABLE_ID + 1;+ long policyB = POLICY_ID + 1;+ MaintenanceJobManager mgr = mock(MaintenanceJobManager.class);+ TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);++ // In-flight only for the peer policy. Abort the whole batch; wrong if gated on POLICY_ID alone.+ pipeline((t, p) -> t == peerTable && p == policyB, actions, mgr)+ .submit(+ MaintenanceTaskIds.forCronBatch(0L, POLICY_ID),+ expireSpec(TABLE_ID, POLICY_ID, peerTable, policyB));++ verify(actions, never()).tryAcquireInFlight(anyLong(), anyLong(), anyLong());+ verify(mgr, never()).submitAndBind(anyString(), anyMap(), anyList());+ }++ @Test+ void testConsumesSpecJobConfWithoutRebuild() {+ MaintenanceJobManager mgr = mock(MaintenanceJobManager.class);+ when(mgr.submitAndBind(anyString(), anyMap(), anyList())).thenReturn(Optional.of(1L));+ TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);+ when(actions.tryAcquireInFlight(TABLE_ID, POLICY_ID, CLAIM_TIMEOUT_MS))+ .thenReturn(Optional.of(new OccupancyClaim(1L, 1L)));++ Map<String, String> params = new LinkedHashMap<>();+ params.put("strategy", "binpack");+ pipeline(false, actions, mgr)+ .submit(INSTANCE, spec(params, "{\"spark.sql.catalog.iceberg.rest.auth.type\":\"basic\"}"));++ @SuppressWarnings("unchecked")+ ArgumentCaptor<Map<String, String>> confCaptor = ArgumentCaptor.forClass(Map.class);+ verify(mgr).submitAndBind(eq("metalake"), confCaptor.capture(), anyList());+ verify(actions, never()).deleteUnboundClaim(any());+ Map<String, String> conf = confCaptor.getValue();+ Assertions.assertNull(conf.get("table_identifier"));+ Assertions.assertEquals("binpack", conf.get("strategy"));+ Assertions.assertTrue(conf.get("tables").contains("db.t"));+ Assertions.assertTrue(conf.get("updater_options").contains("gravitino_uri"));+ Assertions.assertTrue(conf.get("spark_conf").contains("basic"));+ }++ private static MaintenanceCronSubmitPipeline pipeline(+ boolean inFlight, TableMaintenanceActionMetaService actions, MaintenanceJobManager mgr) {+ return pipeline((t, p) -> inFlight, actions, mgr);+ }++ private static MaintenanceCronSubmitPipeline pipeline(+ BiPredicate<Long, Long> inFlight,+ TableMaintenanceActionMetaService actions,+ MaintenanceJobManager mgr) {+ return new MaintenanceCronSubmitPipeline(+ occupancyGate(inFlight),+ actions,+ mgr,+ new MaintenanceJobConfBuilder(new Config(false) {}),+ CLAIM_TIMEOUT_MS);+ }++ /**+ * Real manager over a stub meta service — {@link MaintenanceActionManager} is final and not+ * mockable.+ */+ private static MaintenanceActionManager occupancyGate(BiPredicate<Long, Long> inFlight) {+ TableMaintenanceActionMetaService meta = mock(TableMaintenanceActionMetaService.class);+ when(meta.hasLiveUnboundClaim(anyLong(), anyLong(), anyLong()))+ .thenAnswer(inv -> inFlight.test(inv.getArgument(0), inv.getArgument(1)));+ when(meta.listInFlight(anyLong(), anyLong())).thenReturn(List.of());+ return new MaintenanceActionManager(meta, CLAIM_TIMEOUT_MS);+ }++ private static MaintenanceJobSpec spec() {+ return spec(Map.of(), 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)),+ UPDATER,+ sparkConf);+ }++ private static MaintenanceJobSpec batchSpec(long table1, long table2) {+ return expireSpec(table1, POLICY_ID, table2, POLICY_ID);+ }++ private static MaintenanceJobSpec expireSpec(+ long table1, long policy1, long table2, long policy2) {+ return new MaintenanceJobSpec(+ List.of(expireTask(table1, policy1, "db.t1"), expireTask(table2, policy2, "db.t2")),+ UPDATER,+ null);+ }++ private static Task expireTask(long tableId, long policyId, String identifier) {+ return new Task(+ tableId,+ policyId,+ "expire_snapshots",+ null,+ new LinkedHashMap<>(Map.of("catalog_name", "iceberg", "table_identifier", identifier)));+ }+}diff --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.javadeleted file mode 100644index 4fe32a0cc9..0000000000--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestMaintenanceSparkSubmitPipeline.java+++ /dev/null@@ -1,325 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.job.cron;--import static org.mockito.ArgumentMatchers.any;-import static org.mockito.ArgumentMatchers.anyLong;-import static org.mockito.ArgumentMatchers.anyMap;-import static org.mockito.ArgumentMatchers.anyString;-import static org.mockito.ArgumentMatchers.eq;-import static org.mockito.Mockito.doThrow;-import static org.mockito.Mockito.mock;-import static org.mockito.Mockito.never;-import static org.mockito.Mockito.times;-import static org.mockito.Mockito.verify;-import static org.mockito.Mockito.when;--import java.util.LinkedHashMap;-import java.util.List;-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.Task;-import org.apache.gravitino.maintenance.scheduler.MaintenanceTaskIds;-import org.apache.gravitino.maintenance.storage.service.OccupancyClaim;-import org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService;-import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;-import org.mockito.ArgumentCaptor;--class TestMaintenanceSparkSubmitPipeline {-- private static final long TABLE_ID = 101L;- private static final long POLICY_ID = 202L;- private static final String INSTANCE = MaintenanceTaskIds.forCronTable(TABLE_ID, POLICY_ID);- private static final long CLAIM_TIMEOUT_MS = 60_000L;-- @Test- void testUnparseableInstanceSkipsSubmit() {- MaintenanceJobSubmitter submitter = mock(MaintenanceJobSubmitter.class);- TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);- pipeline(mockGate(false), actions, submitter).submit("not-a-cron-id", spec());- verify(submitter, never()).runJob(anyString(), anyString(), anyMap());- verify(actions, never()).tryAcquireInFlight(anyLong(), anyLong(), anyLong());- }-- @Test- void testNullSpecSkipsSubmit() {- MaintenanceJobSubmitter submitter = mock(MaintenanceJobSubmitter.class);- TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);- pipeline(mockGate(false), actions, submitter).submit(INSTANCE, null);- verify(submitter, never()).runJob(anyString(), anyString(), anyMap());- }-- @Test- void testInFlightDoesNotClaimOrSubmit() {- MaintenanceJobSubmitter submitter = mock(MaintenanceJobSubmitter.class);- TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);- pipeline(mockGate(true), actions, submitter).submit(INSTANCE, spec());- verify(actions, never()).tryAcquireInFlight(anyLong(), anyLong(), anyLong());- verify(submitter, never()).runJob(anyString(), anyString(), anyMap());- }-- @Test- void testBatchInFlightAbortsEntirePick() {- MaintenanceJobSubmitter submitter = mock(MaintenanceJobSubmitter.class);- TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);- CronSubmitGate gate = (tableId, policyId) -> tableId == 11L;-- MaintenanceJobSpec batch = batchSpec(10L, 11L, "expire_snapshots");-- pipeline(gate, actions, submitter)- .submit(MaintenanceTaskIds.forCronBatch(0L, POLICY_ID), batch);-- verify(actions, never()).tryAcquireInFlight(anyLong(), anyLong(), anyLong());- verify(submitter, never()).runJob(anyString(), anyString(), anyMap());- }-- @Test- void testLostClaimRaceSkipsSubmit() {- MaintenanceJobSubmitter submitter = mock(MaintenanceJobSubmitter.class);- TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);- when(actions.tryAcquireInFlight(TABLE_ID, POLICY_ID, CLAIM_TIMEOUT_MS))- .thenReturn(Optional.empty());-- pipeline(mockGate(false), actions, submitter).submit(INSTANCE, spec());-- verify(submitter, never()).runJob(anyString(), anyString(), anyMap());- }-- @Test- void testSuccessfulSubmitBindsJobId() {- MaintenanceJobSubmitter submitter = mock(MaintenanceJobSubmitter.class);- when(submitter.runJob(- eq("metalake"), eq(MaintenanceJobTemplates.ICEBERG_MAINTENANCE_TEMPLATE), anyMap()))- .thenReturn(999L);- TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);- OccupancyClaim claim = new OccupancyClaim(7L, 1_000L);- when(actions.tryAcquireInFlight(TABLE_ID, POLICY_ID, CLAIM_TIMEOUT_MS))- .thenReturn(Optional.of(claim));-- pipeline(mockGate(false), actions, submitter).submit(INSTANCE, spec());-- verify(actions).bindJobId(claim, 999L);- verify(actions, never()).deleteUnboundClaim(any());- }-- @Test- void testSubmitFailureReleasesClaim() {- MaintenanceJobSubmitter submitter = mock(MaintenanceJobSubmitter.class);- when(submitter.runJob(anyString(), anyString(), anyMap()))- .thenThrow(new RuntimeException("submit failed"));- TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);- OccupancyClaim claim = new OccupancyClaim(8L, 2_000L);- when(actions.tryAcquireInFlight(TABLE_ID, POLICY_ID, CLAIM_TIMEOUT_MS))- .thenReturn(Optional.of(claim));- when(actions.deleteUnboundClaim(claim)).thenReturn(true);-- Assertions.assertDoesNotThrow(- () -> pipeline(mockGate(false), actions, submitter).submit(INSTANCE, spec()));-- verify(actions).deleteUnboundClaim(claim);- verify(actions, never()).bindJobId(any(), anyLong());- verify(submitter, never()).cancelJob(anyString(), anyLong());- }-- @Test- void testBindFailureCancelsJobAndReleasesClaim() {- MaintenanceJobSubmitter submitter = mock(MaintenanceJobSubmitter.class);- when(submitter.runJob(- eq("metalake"), eq(MaintenanceJobTemplates.ICEBERG_MAINTENANCE_TEMPLATE), anyMap()))- .thenReturn(777L);- TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);- OccupancyClaim claim = new OccupancyClaim(9L, 3_000L);- when(actions.tryAcquireInFlight(TABLE_ID, POLICY_ID, CLAIM_TIMEOUT_MS))- .thenReturn(Optional.of(claim));- doThrow(new RuntimeException("bind failed")).when(actions).bindJobId(claim, 777L);- when(actions.deleteUnboundClaim(claim)).thenReturn(true);-- Assertions.assertDoesNotThrow(- () -> pipeline(mockGate(false), actions, submitter).submit(INSTANCE, spec()));-- verify(submitter).cancelJob("metalake", 777L);- verify(actions).deleteUnboundClaim(claim);- }-- @Test- void testBindFailureSkipsReleaseWhenClaimAlreadyReclaimed() {- MaintenanceJobSubmitter submitter = mock(MaintenanceJobSubmitter.class);- when(submitter.runJob(- eq("metalake"), eq(MaintenanceJobTemplates.ICEBERG_MAINTENANCE_TEMPLATE), anyMap()))- .thenReturn(778L);- TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);- OccupancyClaim staleClaim = new OccupancyClaim(10L, 4_000L);- when(actions.tryAcquireInFlight(TABLE_ID, POLICY_ID, CLAIM_TIMEOUT_MS))- .thenReturn(Optional.of(staleClaim));- doThrow(new RuntimeException("bind lost lease")).when(actions).bindJobId(staleClaim, 778L);- // Concurrent reclaim already moved created_at — fenced delete matches zero rows.- when(actions.deleteUnboundClaim(staleClaim)).thenReturn(false);-- Assertions.assertDoesNotThrow(- () -> pipeline(mockGate(false), actions, submitter).submit(INSTANCE, spec()));-- verify(submitter).cancelJob("metalake", 778L);- verify(actions).deleteUnboundClaim(staleClaim);- verify(actions, never()).deleteById(anyLong());- }-- @Test- void testBatchSubmitOneSparkJobPerTable() {- MaintenanceJobSubmitter submitter = mock(MaintenanceJobSubmitter.class);- when(submitter.runJob(- eq("metalake"), eq(MaintenanceJobTemplates.ICEBERG_MAINTENANCE_TEMPLATE), anyMap()))- .thenReturn(555L, 556L);- TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);- OccupancyClaim claimA = new OccupancyClaim(1L, 10L);- OccupancyClaim claimB = new OccupancyClaim(2L, 20L);- when(actions.tryAcquireInFlight(10L, POLICY_ID, CLAIM_TIMEOUT_MS))- .thenReturn(Optional.of(claimA));- when(actions.tryAcquireInFlight(11L, POLICY_ID, CLAIM_TIMEOUT_MS))- .thenReturn(Optional.of(claimB));-- MaintenanceJobSpec batch = batchSpec(10L, 11L, "expire_snapshots");-- pipeline(mockGate(false), actions, submitter)- .submit(MaintenanceTaskIds.forCronBatch(0L, POLICY_ID), batch);-- @SuppressWarnings("unchecked")- ArgumentCaptor<Map<String, String>> confCaptor = ArgumentCaptor.forClass(Map.class);- verify(submitter, times(2))- .runJob(- eq("metalake"),- eq(MaintenanceJobTemplates.ICEBERG_MAINTENANCE_TEMPLATE),- confCaptor.capture());- List<Map<String, String>> confs = confCaptor.getAllValues();- Assertions.assertEquals("iceberg", confs.get(0).get("catalog_name"));- Assertions.assertNull(confs.get(0).get("table_identifier"));- Assertions.assertTrue(confs.get(0).get("tables").contains("\"table_identifier\":\"db.t1\""));- Assertions.assertTrue(confs.get(0).get("tables").contains("\"table_id\":10"));- Assertions.assertFalse(confs.get(0).containsKey("tms_table_id"));- Assertions.assertEquals("expire_snapshots", confs.get(0).get("maintenance_types"));- Assertions.assertEquals("iceberg", confs.get(1).get("catalog_name"));- Assertions.assertNull(confs.get(1).get("table_identifier"));- Assertions.assertTrue(confs.get(1).get("tables").contains("\"table_identifier\":\"db.t2\""));- Assertions.assertTrue(confs.get(1).get("tables").contains("\"table_id\":11"));- Assertions.assertFalse(confs.get(1).containsKey("tms_table_id"));- Assertions.assertFalse(confs.get(0).containsKey("tms_policy_id"));- verify(actions).bindJobId(claimA, 555L);- verify(actions).bindJobId(claimB, 556L);- }-- @Test- void testConsumesSpecJobConfWithoutRebuild() {- MaintenanceJobSubmitter submitter = mock(MaintenanceJobSubmitter.class);- when(submitter.runJob(anyString(), anyString(), anyMap())).thenReturn(1L);- TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);- when(actions.tryAcquireInFlight(TABLE_ID, POLICY_ID, CLAIM_TIMEOUT_MS))- .thenReturn(Optional.of(new OccupancyClaim(1L, 1L)));-- 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(parameters, "{\"spark.sql.catalog.iceberg.rest.auth.type\":\"basic\"}"));-- @SuppressWarnings("unchecked")- ArgumentCaptor<Map<String, String>> confCaptor = ArgumentCaptor.forClass(Map.class);- verify(submitter)- .runJob(- eq("metalake"),- eq(MaintenanceJobTemplates.ICEBERG_MAINTENANCE_TEMPLATE),- confCaptor.capture());- Map<String, String> conf = confCaptor.getValue();- Assertions.assertEquals("iceberg", conf.get("catalog_name"));- Assertions.assertNull(conf.get("table_identifier"));- Assertions.assertTrue(conf.get("tables").contains("\"table_identifier\":\"db.t\""));- Assertions.assertTrue(conf.get("tables").contains("\"table_id\":" + TABLE_ID));- Assertions.assertFalse(conf.containsKey("tms_table_id"));- Assertions.assertEquals("rewrite_data_files", conf.get("maintenance_types"));- Assertions.assertFalse(conf.containsKey("tms_policy_id"));- Assertions.assertEquals("binpack", conf.get("strategy"));- Assertions.assertTrue(conf.get("updater_options").contains("gravitino_uri"));- Assertions.assertTrue(conf.get("spark_conf").contains("basic"));- }-- @Test- void testPolicyIdMismatchSkipsSubmit() {- MaintenanceJobSubmitter submitter = mock(MaintenanceJobSubmitter.class);- TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);- pipeline(mockGate(false), actions, submitter)- .submit(MaintenanceTaskIds.forCronTable(TABLE_ID, POLICY_ID + 1), spec());- verify(submitter, never()).runJob(anyString(), anyString(), anyMap());- }-- private static MaintenanceSparkSubmitPipeline pipeline(- CronSubmitGate gate,- TableMaintenanceActionMetaService actions,- MaintenanceJobSubmitter submitter) {- return new MaintenanceSparkSubmitPipeline(- gate,- actions,- submitter,- new MaintenanceJobConfBuilder(new Config(false) {}),- CLAIM_TIMEOUT_MS);- }-- private static CronSubmitGate mockGate(boolean inFlight) {- return (tableId, policyId) -> inFlight;- }-- private static MaintenanceJobSpec spec() {- 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 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 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/scheduler/policy/expand/TestNearestMaintenancePolicyResolver.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/TestNearestMaintenancePolicyResolver.javasimilarity index 68%rename from plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/expand/TestNearestMaintenancePolicyResolver.javarename to plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/TestNearestMaintenancePolicyResolver.javaindex 557093eb99..dce711e67c 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/expand/TestNearestMaintenancePolicyResolver.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/TestNearestMaintenancePolicyResolver.java@@ -16,13 +16,14 @@* specific language governing permissions and limitations* under the License.*/-package org.apache.gravitino.maintenance.scheduler.policy.expand;+package org.apache.gravitino.maintenance.scheduler.policy;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.when;import java.time.Instant;import java.util.List;+import java.util.Optional;import org.apache.gravitino.MetadataObject;import org.apache.gravitino.MetadataObjects;import org.apache.gravitino.meta.AuditInfo;@@ -57,7 +58,7 @@ class TestNearestMaintenancePolicyResolver {}@Test- void testTableLevelBeatsCatalogLevel() {+ void testResolveWinnerIdNearestFallbackAndEmpty() {PolicyEntity tablePolicy = policy(10L, "table-compaction");PolicyEntity catalogPolicy = policy(20L, "catalog-compaction");when(objectPolicyResolver.resolveMatches(METALAKE, TABLE))@@ -65,54 +66,20 @@ class TestNearestMaintenancePolicyResolver {new Match[] {new Match(tablePolicy, List.of(TABLE)), new Match(catalogPolicy, List.of(CATALOG))});+ Assertions.assertEquals(+ Optional.of(10L),+ resolver.resolveWinnerId(METALAKE, TABLE, Policy.BuiltInType.ICEBERG_COMPACTION));- NearestMaintenancePolicyResolver.Decision decision =- resolver.resolve(METALAKE, TABLE, Policy.BuiltInType.ICEBERG_COMPACTION);- Assertions.assertEquals(NearestMaintenancePolicyResolver.Decision.Kind.WINNER, decision.kind());- Assertions.assertEquals(java.util.Optional.of(10L), decision.winnerPolicyId());- Assertions.assertEquals(TABLE, decision.winnerLevel());- }-- @Test- void testFallsBackToAncestorWhenTableHasNoMatch() {- PolicyEntity catalogPolicy = policy(20L, "catalog-compaction");when(objectPolicyResolver.resolveMatches(METALAKE, TABLE)).thenReturn(new Match[] {new Match(catalogPolicy, List.of(CATALOG))});+ Assertions.assertEquals(+ Optional.of(20L),+ resolver.resolveWinnerId(METALAKE, TABLE, Policy.BuiltInType.ICEBERG_COMPACTION));- NearestMaintenancePolicyResolver.Decision decision =- resolver.resolve(METALAKE, TABLE, Policy.BuiltInType.ICEBERG_COMPACTION);- Assertions.assertEquals(NearestMaintenancePolicyResolver.Decision.Kind.WINNER, decision.kind());- Assertions.assertEquals(java.util.Optional.of(20L), decision.winnerPolicyId());- Assertions.assertEquals(CATALOG, decision.winnerLevel());- }-- @Test- void testEmptyWhenNoMatchingType() {when(objectPolicyResolver.resolveMatches(METALAKE, TABLE)).thenReturn(new Match[0]);+ Assertions.assertTrue(+ resolver.resolveWinnerId(METALAKE, TABLE, Policy.BuiltInType.ICEBERG_COMPACTION).isEmpty());- NearestMaintenancePolicyResolver.Decision decision =- resolver.resolve(METALAKE, TABLE, Policy.BuiltInType.ICEBERG_COMPACTION);- Assertions.assertEquals(NearestMaintenancePolicyResolver.Decision.Kind.NONE, decision.kind());- }-- @Test- void testSameLevelConflict() {- PolicyEntity p1 = policy(10L, "compaction-a");- PolicyEntity p2 = policy(11L, "compaction-b");- when(objectPolicyResolver.resolveMatches(METALAKE, TABLE))- .thenReturn(new Match[] {new Match(p1, List.of(TABLE)), new Match(p2, List.of(TABLE))});-- NearestMaintenancePolicyResolver.Decision decision =- resolver.resolve(METALAKE, TABLE, Policy.BuiltInType.ICEBERG_COMPACTION);- Assertions.assertEquals(- NearestMaintenancePolicyResolver.Decision.Kind.CONFLICT, decision.kind());- Assertions.assertEquals(TABLE, decision.conflictLevel());- Assertions.assertEquals(List.of(10L, 11L), decision.conflictingPolicyIds());- Assertions.assertTrue(decision.winnerPolicyId().isEmpty());- }-- @Test- void testIgnoresNonMatchingBuiltInType() {PolicyEntity custom =PolicyEntity.builder().withId(99L)@@ -128,10 +95,25 @@ class TestNearestMaintenancePolicyResolver {.build();when(objectPolicyResolver.resolveMatches(METALAKE, TABLE)).thenReturn(new Match[] {new Match(custom, List.of(TABLE))});+ Assertions.assertTrue(+ resolver.resolveWinnerId(METALAKE, TABLE, Policy.BuiltInType.ICEBERG_COMPACTION).isEmpty());+ }- NearestMaintenancePolicyResolver.Decision decision =- resolver.resolve(METALAKE, TABLE, Policy.BuiltInType.ICEBERG_COMPACTION);- Assertions.assertEquals(NearestMaintenancePolicyResolver.Decision.Kind.NONE, decision.kind());+ @Test+ void testSameLevelConflictThrows() {+ when(objectPolicyResolver.resolveMatches(METALAKE, TABLE))+ .thenReturn(+ new Match[] {+ new Match(policy(10L, "a"), List.of(TABLE)),+ new Match(policy(11L, "b"), List.of(TABLE))+ });+ IllegalArgumentException thrown =+ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> resolver.resolveWinnerId(METALAKE, TABLE, Policy.BuiltInType.ICEBERG_COMPACTION));+ Assertions.assertTrue(thrown.getMessage().contains("ambiguous"));+ Assertions.assertTrue(thrown.getMessage().contains("10"));+ Assertions.assertTrue(thrown.getMessage().contains("11"));}private static PolicyEntity policy(long id, String name) {diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/expand/TestNearestPolicyTableEnumerator.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/TestNearestPolicyTableEnumerator.javasimilarity index 77%rename from plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/expand/TestNearestPolicyTableEnumerator.javarename to plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/TestNearestPolicyTableEnumerator.javaindex cbcc510013..0ace72bbdc 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/expand/TestNearestPolicyTableEnumerator.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/TestNearestPolicyTableEnumerator.java@@ -16,7 +16,7 @@* specific language governing permissions and limitations* under the License.*/-package org.apache.gravitino.maintenance.scheduler.policy.expand;+package org.apache.gravitino.maintenance.scheduler.policy;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.eq;@@ -36,6 +36,7 @@ import org.apache.gravitino.SupportsRelationOperations;import org.apache.gravitino.catalog.EntityCombinedTable;import org.apache.gravitino.catalog.SchemaDispatcher;import org.apache.gravitino.catalog.TableDispatcher;+import org.apache.gravitino.maintenance.model.TableCandidate;import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.GenericEntity;import org.apache.gravitino.meta.PolicyEntity;@@ -117,8 +118,8 @@ class TestNearestPolicyTableEnumerator {MetadataObject table =MetadataObjects.of(java.util.Arrays.asList("catalog", "schema", "t1"), MetadataObject.Type.TABLE);- when(nearest.resolve(METALAKE, table, Policy.BuiltInType.ICEBERG_COMPACTION))- .thenReturn(NearestMaintenancePolicyResolver.Decision.winner(10L, table));+ when(nearest.resolveWinnerId(METALAKE, table, Policy.BuiltInType.ICEBERG_COMPACTION))+ .thenReturn(java.util.Optional.of(10L));Assertions.assertEquals(List.of(100L), tableIds(enumerator.listTableIds(policy, 10, allowAll(), 0L)));@@ -166,14 +167,11 @@ class TestNearestPolicyTableEnumerator {MetadataObject table2 =MetadataObjects.of(java.util.Arrays.asList("catalog", "schema", "t2"), MetadataObject.Type.TABLE);- MetadataObject schema =- MetadataObjects.of(- java.util.Arrays.asList("catalog", "schema"), MetadataObject.Type.SCHEMA);- when(nearest.resolve(METALAKE, table1, Policy.BuiltInType.ICEBERG_COMPACTION))- .thenReturn(NearestMaintenancePolicyResolver.Decision.winner(11L, table1));- when(nearest.resolve(METALAKE, table2, Policy.BuiltInType.ICEBERG_COMPACTION))- .thenReturn(NearestMaintenancePolicyResolver.Decision.winner(10L, schema));+ when(nearest.resolveWinnerId(METALAKE, table1, Policy.BuiltInType.ICEBERG_COMPACTION))+ .thenReturn(java.util.Optional.of(11L));+ when(nearest.resolveWinnerId(METALAKE, table2, Policy.BuiltInType.ICEBERG_COMPACTION))+ .thenReturn(java.util.Optional.of(10L));Assertions.assertEquals(List.of(101L), tableIds(enumerator.listTableIds(catalogPolicy, 10, allowAll(), 0L)));@@ -216,10 +214,8 @@ class TestNearestPolicyTableEnumerator {MetadataObject table =MetadataObjects.of(java.util.Arrays.asList("catalog", "a:b", "t1"), MetadataObject.Type.TABLE);- MetadataObject parentSchema =- MetadataObjects.of(java.util.Arrays.asList("catalog", "a"), MetadataObject.Type.SCHEMA);- when(nearest.resolve(METALAKE, table, Policy.BuiltInType.ICEBERG_COMPACTION))- .thenReturn(NearestMaintenancePolicyResolver.Decision.winner(10L, parentSchema));+ when(nearest.resolveWinnerId(METALAKE, table, Policy.BuiltInType.ICEBERG_COMPACTION))+ .thenReturn(java.util.Optional.of(10L));Assertions.assertEquals(List.of(200L), tableIds(enumerator.listTableIds(policy, 10, allowAll(), 0L)));@@ -267,47 +263,16 @@ class TestNearestPolicyTableEnumerator {eq(NamespaceUtil.ofTable(METALAKE, "catalog", "schema")))).thenReturn(List.of(t1, t2, t3));- when(nearest.resolve(+ when(nearest.resolveWinnerId(eq(METALAKE), any(MetadataObject.class), eq(Policy.BuiltInType.ICEBERG_COMPACTION)))- .thenAnswer(- invocation -> {- MetadataObject table = invocation.getArgument(1);- return NearestMaintenancePolicyResolver.Decision.winner(10L, table);- });+ .thenReturn(java.util.Optional.of(10L));- ExpandOccupancyGate gate = (tableId, policyId, minIntervalMs, nowMs) -> tableId != 102L;+ NearestPolicyTableEnumerator.ShouldSkipTable gate =+ (tableId, policyId, minIntervalMs, nowMs) -> tableId != 102L;Assertions.assertEquals(List.of(102L), tableIds(enumerator.listTableIds(policy, 1, gate, 60_000L)));}- @Test- void testSameLevelConflictSkipsTable() throws Exception {- PolicyEntity policy = policy(10L, "compaction");- TagEntity tagA = tag(1L, "t-a");-- when(policyTagRelService.listRelations(- eq(List.of(NameIdentifierUtil.ofPolicy(METALAKE, "compaction"))),- eq(Entity.EntityType.POLICY)))- .thenReturn(List.of(policyTagEdge(policy, tagA)));- when(tagMetaService.listAssociatedMetadataObjectsForTag(tagA.nameIdentifier()))- .thenReturn(- List.of(- GenericEntity.builder()- .withId(100L)- .withName("catalog.schema.t1")- .withEntityType(Entity.EntityType.TABLE)- .build()));-- MetadataObject table =- MetadataObjects.of(- java.util.Arrays.asList("catalog", "schema", "t1"), MetadataObject.Type.TABLE);- when(nearest.resolve(METALAKE, table, Policy.BuiltInType.ICEBERG_COMPACTION))- .thenReturn(NearestMaintenancePolicyResolver.Decision.conflict(table, List.of(10L, 11L)));-- Assertions.assertEquals(- List.of(), tableIds(enumerator.listTableIds(policy, 10, allowAll(), 0L)));- }-@Testvoid testImportsOnlyMissingTablesAfterCatalogList() throws Exception {PolicyEntity policy = stubTaggedObject("catalog.schema", Entity.EntityType.SCHEMA);@@ -325,11 +290,8 @@ class TestNearestPolicyTableEnumerator {EntityCombinedTable.of(Mockito.mock(Table.class), table(501L, "missing")).withImported(true));- MetadataObject schemaObj =- MetadataObjects.of(- java.util.Arrays.asList("catalog", "schema"), MetadataObject.Type.SCHEMA);- stubWinner(tableMeta("catalog", "schema", "known"), schemaObj);- stubWinner(tableMeta("catalog", "schema", "missing"), schemaObj);+ stubWinner(tableMeta("catalog", "schema", "known"));+ stubWinner(tableMeta("catalog", "schema", "missing"));Assertions.assertEquals(List.of(500L, 501L),@@ -338,28 +300,6 @@ class TestNearestPolicyTableEnumerator {verify(tables, never()).loadTable(known);}- @Test- void testImportsOnlyMissingSchemasAfterCatalogList() throws Exception {- PolicyEntity policy = stubTaggedObject("catalog", Entity.EntityType.CATALOG);- SchemaDispatcher schemas = mock(SchemaDispatcher.class);- TableDispatcher tables = mock(TableDispatcher.class);- NameIdentifier known = NameIdentifierUtil.ofSchema(METALAKE, "catalog", "known");- NameIdentifier missing = NameIdentifierUtil.ofSchema(METALAKE, "catalog", "missing");- when(schemas.listSchemas(eq(NamespaceUtil.ofSchema(METALAKE, "catalog"))))- .thenReturn(new NameIdentifier[] {known, missing});- when(schemaMetaService.listSchemasByNamespace(eq(NamespaceUtil.ofSchema(METALAKE, "catalog"))))- .thenReturn(List.of(schema(2L, "known")));- when(schemas.loadSchema(eq(missing))).thenReturn(mock(org.apache.gravitino.Schema.class));- when(tables.listTables(any())).thenReturn(new NameIdentifier[0]);- when(tableMetaService.listTablesByNamespace(any())).thenReturn(List.of());-- Assertions.assertEquals(- List.of(),- tableIds(catalogEnumerator(schemas, tables).listTableIds(policy, 10, allowAll(), 0L)));- verify(schemas).loadSchema(missing);- verify(schemas, never()).loadSchema(known);- }-private PolicyEntity stubTaggedObject(String objectName, Entity.EntityType type)throws Exception {PolicyEntity policy = policy(10L, "compaction");@@ -379,9 +319,9 @@ class TestNearestPolicyTableEnumerator {return policy;}- private void stubWinner(MetadataObject table, MetadataObject nearestObject) {- when(nearest.resolve(METALAKE, table, Policy.BuiltInType.ICEBERG_COMPACTION))- .thenReturn(NearestMaintenancePolicyResolver.Decision.winner(10L, nearestObject));+ private void stubWinner(MetadataObject table) {+ when(nearest.resolveWinnerId(METALAKE, table, Policy.BuiltInType.ICEBERG_COMPACTION))+ .thenReturn(java.util.Optional.of(10L));}private NearestPolicyTableEnumerator catalogEnumerator(@@ -409,11 +349,11 @@ class TestNearestPolicyTableEnumerator {.build();}- private static List<Long> tableIds(List<ExpandTableCandidate> candidates) {- return candidates.stream().map(ExpandTableCandidate::tableId).toList();+ private static List<Long> tableIds(List<TableCandidate> candidates) {+ return candidates.stream().map(TableCandidate::tableId).toList();}- private static ExpandOccupancyGate allowAll() {+ private static NearestPolicyTableEnumerator.ShouldSkipTable allowAll() {return (tableId, policyId, minIntervalMs, nowMs) -> false;}diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/expand/TestPolicyExpandClient.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/expand/TestPolicyExpandClient.javanew file mode 100644index 0000000000..47b22dd174--- /dev/null+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/expand/TestPolicyExpandClient.java@@ -0,0 +1,106 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */+package org.apache.gravitino.maintenance.scheduler.policy.expand;++import java.time.Instant;+import javax.sql.DataSource;+import org.apache.gravitino.storage.relational.TestJDBCBackend;+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;+import org.apache.gravitino.storage.relational.utils.SessionUtils;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.TestTemplate;++class TestPolicyExpandClient extends TestJDBCBackend {++ private static final String CRON = "0 0 2 * * ?";+ private static final String LATER_CRON = "0 30 4 * * ?";++ @TestTemplate+ void testScheduleRescheduleAndRemoveTheExpandRow() {+ DataSource dataSource = entityStoreDataSource();+ PolicyExpandClient writer = PolicyExpandClient.joiningCurrentTransaction();+ PolicyExpandClient reader = PolicyExpandClient.forReads(dataSource);++ SessionUtils.doMultipleWithCommit(() -> schedule(writer, 42L, CRON));+ Instant firstDue = executionTime(reader, 42L);+ Assertions.assertTrue(firstDue.isAfter(Instant.now()));++ SessionUtils.doMultipleWithCommit(() -> schedule(writer, 42L, LATER_CRON));+ Instant secondDue = executionTime(reader, 42L);+ Assertions.assertNotEquals(firstDue, secondDue);++ SessionUtils.doMultipleWithCommit(() -> writer.remove(42L));+ Assertions.assertTrue(reader.scheduledExecutionTime(42L).isEmpty());++ SessionUtils.doMultipleWithCommit(() -> schedule(writer, 42L, CRON));+ Assertions.assertTrue(reader.scheduledExecutionTime(42L).isPresent());+ SessionUtils.doMultipleWithCommit(() -> writer.remove(42L));+ Assertions.assertTrue(reader.scheduledExecutionTime(42L).isEmpty());+ SessionUtils.doMultipleWithCommit(() -> writer.remove(42L));+ }++ @TestTemplate+ void testFailedTransactionRollsBackTheExpandRow() {+ DataSource dataSource = entityStoreDataSource();+ PolicyExpandClient writer = PolicyExpandClient.joiningCurrentTransaction();+ PolicyExpandClient reader = PolicyExpandClient.forReads(dataSource);++ Assertions.assertThrows(+ IllegalStateException.class,+ () ->+ SessionUtils.doMultipleWithCommit(+ () -> schedule(writer, 99L, CRON),+ () -> {+ throw new IllegalStateException("boom");+ }));++ Assertions.assertTrue(reader.scheduledExecutionTime(99L).isEmpty());+ }++ @TestTemplate+ void testInvalidCronFailsBeforeAnExpandRowIsWritten() {+ DataSource dataSource = entityStoreDataSource();+ PolicyExpandClient writer = PolicyExpandClient.joiningCurrentTransaction();+ PolicyExpandClient reader = PolicyExpandClient.forReads(dataSource);++ Assertions.assertThrows(+ IllegalArgumentException.class,+ () -> SessionUtils.doMultipleWithCommit(() -> schedule(writer, 100L, "not a cron")));++ Assertions.assertTrue(reader.scheduledExecutionTime(100L).isEmpty());+ }++ private static DataSource entityStoreDataSource() {+ return SqlSessionFactoryHelper.getInstance()+ .getSqlSessionFactory()+ .getConfiguration()+ .getEnvironment()+ .getDataSource();+ }++ private static void schedule(PolicyExpandClient writer, long policyId, String cron) {+ writer.scheduleAt(policyId, PolicyExpandClient.nextExecution(cron));+ }++ private static Instant executionTime(PolicyExpandClient expandClient, long policyId) {+ return expandClient+ .scheduledExecutionTime(policyId)+ .orElseThrow(() -> new AssertionError("missing expand row " + policyId));+ }+}diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/expand/TestPolicyExpandCrons.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/expand/TestPolicyExpandCrons.javadeleted file mode 100644index f8663223e7..0000000000--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/expand/TestPolicyExpandCrons.java+++ /dev/null@@ -1,40 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.policy.expand;--import java.time.Instant;-import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;--/** Unit tests for {@link PolicyExpandCrons}. */-class TestPolicyExpandCrons {-- @Test- void testNextExecutionReturnsFutureInstant() {- Instant before = Instant.now().minusSeconds(1);- Instant next = PolicyExpandCrons.nextExecution("0 0 2 * * ?");- Assertions.assertTrue(next.isAfter(before));- }-- @Test- void testInvalidCronRejected() {- Assertions.assertThrows(- IllegalArgumentException.class, () -> PolicyExpandCrons.nextExecution("not-a-cron"));- }-}diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/expand/TestPolicyExpandPipeline.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/expand/TestPolicyExpandPipeline.javadeleted file mode 100644index 80ebab9a55..0000000000--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/expand/TestPolicyExpandPipeline.java+++ /dev/null@@ -1,256 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.policy.expand;--import static org.mockito.ArgumentMatchers.any;-import static org.mockito.ArgumentMatchers.anyInt;-import static org.mockito.ArgumentMatchers.anyLong;-import static org.mockito.ArgumentMatchers.eq;-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.time.Instant;-import java.util.List;-import java.util.Optional;-import java.util.function.Function;-import org.apache.gravitino.Config;-import org.apache.gravitino.MetadataObject;-import org.apache.gravitino.Namespace;-import org.apache.gravitino.maintenance.policy.MaintenanceMinIntervalConfigs;-import org.apache.gravitino.maintenance.scheduler.job.cron.CronJobClient;-import org.apache.gravitino.meta.AuditInfo;-import org.apache.gravitino.meta.PolicyEntity;-import org.apache.gravitino.policy.IcebergDataCompactionContent;-import org.apache.gravitino.policy.Policy;-import org.apache.gravitino.policy.PolicyContents;-import org.apache.gravitino.utils.NamespaceUtil;-import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.Test;--class TestPolicyExpandPipeline {-- private static final String CRON = "0 0 2 * * ?";-- @Test- void testMissingPolicyRemovesExpandRow() {- CronJobClient cronJobs = mock(CronJobClient.class);- PolicyExpandPipeline pipeline =- pipeline(id -> Optional.empty(), mock(PolicyTableEnumerator.class), cronJobs, allowAll());-- Assertions.assertTrue(pipeline.expand(1L).isEmpty());- verify(cronJobs, never()).enqueueNow(any(), any(), anyInt());- }-- @Test- void testDisabledPolicyRemovesExpandRow() {- CronJobClient cronJobs = mock(CronJobClient.class);- PolicyExpandPipeline pipeline =- pipeline(- lookup(2L, policy(false, CRON, null)),- mock(PolicyTableEnumerator.class),- cronJobs,- allowAll());-- Assertions.assertTrue(pipeline.expand(2L).isEmpty());- verify(cronJobs, never()).enqueueNow(any(), any(), anyInt());- }-- @Test- void testBlankTimeTriggerRemovesExpandRow() {- CronJobClient cronJobs = mock(CronJobClient.class);- PolicyExpandPipeline pipeline =- pipeline(- lookup(3L, policy(true, " ", null)),- mock(PolicyTableEnumerator.class),- cronJobs,- allowAll());-- Assertions.assertTrue(pipeline.expand(3L).isEmpty());- verify(cronJobs, never()).enqueueNow(any(), any(), anyInt());- }-- @Test- void testInvalidTimeTriggerRemovesExpandRowWithoutEnqueue() {- PolicyTableEnumerator tables = mock(PolicyTableEnumerator.class);- CronJobClient cronJobs = mock(CronJobClient.class);- PolicyExpandPipeline pipeline =- pipeline(lookup(4L, policy(true, "not-a-cron", null)), tables, cronJobs, allowAll());-- Assertions.assertTrue(pipeline.expand(4L).isEmpty());- verify(tables, never()).listTableIds(any(), anyInt(), any(), anyLong());- verify(cronJobs, never()).enqueueNow(any(), any(), anyInt());- }-- @Test- void testExpandEnqueuesCronJobsAndReturnsNextDue() {- PolicyEntity policy = policy(true, CRON, null);- ExpandOccupancyGate gate = allowAll();- PolicyTableEnumerator tables = mock(PolicyTableEnumerator.class);- when(tables.listTableIds(- eq(policy),- eq(2),- eq(gate),- eq(MaintenanceMinIntervalConfigs.DEFAULT_HOURLY_MIN_INTERVAL_MS)))- .thenReturn(List.of(c(10L), c(11L)));- CronJobClient cronJobs = mock(CronJobClient.class);- when(cronJobs.enqueueNow(eq(policy), eq(List.of(c(10L), c(11L))), eq(2))).thenReturn(2);- PolicyExpandPipeline expandPipeline = pipeline(lookup(42L, policy), tables, cronJobs, gate, 2);-- Optional<Instant> next = expandPipeline.expand(42L);- Assertions.assertTrue(next.isPresent());- Assertions.assertTrue(next.get().isAfter(Instant.now().minusSeconds(1)));- verify(cronJobs).enqueueNow(policy, List.of(c(10L), c(11L)), 2);- }-- @Test- void testPassesResolvedMinIntervalToEnumerator() {- PolicyEntity policy = policy(true, CRON, 60_000L);- ExpandOccupancyGate gate = allowAll();- PolicyTableEnumerator tables = mock(PolicyTableEnumerator.class);- when(tables.listTableIds(eq(policy), eq(10), eq(gate), eq(60_000L)))- .thenReturn(List.of(c(11L)));- CronJobClient cronJobs = mock(CronJobClient.class);- when(cronJobs.enqueueNow(eq(policy), eq(List.of(c(11L))), eq(10))).thenReturn(1);-- PolicyExpandPipeline expandPipeline = pipeline(lookup(42L, policy), tables, cronJobs, gate, 10);- Assertions.assertTrue(expandPipeline.expand(42L).isPresent());- verify(tables).listTableIds(eq(policy), eq(10), eq(gate), eq(60_000L));- verify(cronJobs).enqueueNow(policy, List.of(c(11L)), 10);- }-- @Test- void testUsesServerDefaultMinIntervalWhenPolicyOmits() {- PolicyEntity policy = policy(true, CRON, null);- ExpandOccupancyGate gate = allowAll();- PolicyTableEnumerator tables = mock(PolicyTableEnumerator.class);- when(tables.listTableIds(- eq(policy),- eq(10),- eq(gate),- eq(MaintenanceMinIntervalConfigs.DEFAULT_HOURLY_MIN_INTERVAL_MS)))- .thenReturn(List.of(c(10L)));- CronJobClient cronJobs = mock(CronJobClient.class);- when(cronJobs.enqueueNow(eq(policy), eq(List.of(c(10L))), eq(10))).thenReturn(1);-- PolicyExpandPipeline expandPipeline = pipeline(lookup(42L, policy), tables, cronJobs, gate, 10);- Assertions.assertTrue(expandPipeline.expand(42L).isPresent());- verify(tables)- .listTableIds(- eq(policy),- eq(10),- eq(gate),- eq(MaintenanceMinIntervalConfigs.DEFAULT_HOURLY_MIN_INTERVAL_MS));- }-- @Test- void testSnapshotExpiryExpandEnqueuesWithBatchCapacity() {- PolicyEntity policy = expirePolicy(true, CRON);- ExpandOccupancyGate gate = allowAll();- PolicyTableEnumerator tables = mock(PolicyTableEnumerator.class);- List<ExpandTableCandidate> candidates =- List.of(- new ExpandTableCandidate(10L, MetadataObject.Type.SCHEMA),- new ExpandTableCandidate(11L, MetadataObject.Type.SCHEMA));- when(tables.listTableIds(- eq(policy),- eq(5),- eq(gate),- eq(MaintenanceMinIntervalConfigs.DEFAULT_HOURLY_MIN_INTERVAL_MS)))- .thenReturn(candidates);- CronJobClient cronJobs = mock(CronJobClient.class);- when(cronJobs.enqueueNow(eq(policy), eq(candidates), eq(5))).thenReturn(1);-- PolicyExpandPipeline expandPipeline = pipeline(lookup(42L, policy), tables, cronJobs, gate, 5);- Assertions.assertTrue(expandPipeline.expand(42L).isPresent());- verify(cronJobs).enqueueNow(policy, candidates, 5);- }-- private static PolicyExpandPipeline pipeline(- Function<Long, Optional<PolicyEntity>> policyLoader,- PolicyTableEnumerator tables,- CronJobClient cronJobs,- ExpandOccupancyGate gate) {- return pipeline(policyLoader, tables, cronJobs, gate, 100);- }-- private static PolicyExpandPipeline pipeline(- Function<Long, Optional<PolicyEntity>> policyLoader,- PolicyTableEnumerator tables,- CronJobClient cronJobs,- ExpandOccupancyGate gate,- int batchSize) {- return new PolicyExpandPipeline(- policyLoader, tables, cronJobs, gate, new Config(false) {}, batchSize);- }-- private static ExpandTableCandidate c(long tableId) {- return new ExpandTableCandidate(tableId, MetadataObject.Type.TABLE);- }-- private static ExpandOccupancyGate allowAll() {- return (tableId, policyId, minIntervalMs, nowMs) -> false;- }-- private static Function<Long, Optional<PolicyEntity>> lookup(long policyId, PolicyEntity policy) {- return id -> id == policyId ? Optional.of(policy) : Optional.empty();- }-- private static PolicyEntity policy(boolean enabled, String timeTrigger, Long minIntervalMs) {- Namespace ns = NamespaceUtil.ofPolicy("metalake");- return PolicyEntity.builder()- .withId(42L)- .withName("compaction")- .withNamespace(ns)- .withPolicyType(Policy.BuiltInType.ICEBERG_COMPACTION)- .withEnabled(enabled)- .withContent(- PolicyContents.icebergDataCompaction(- IcebergDataCompactionContent.DEFAULT_MIN_DATA_FILE_MSE,- IcebergDataCompactionContent.DEFAULT_MIN_DELETE_FILE_NUMBER,- IcebergDataCompactionContent.DEFAULT_DATA_FILE_MSE_WEIGHT,- IcebergDataCompactionContent.DEFAULT_DELETE_FILE_NUMBER_WEIGHT,- IcebergDataCompactionContent.DEFAULT_MAX_PARTITION_NUM,- IcebergDataCompactionContent.DEFAULT_REWRITE_STRATEGY,- IcebergDataCompactionContent.DEFAULT_SORT_ORDER,- null,- timeTrigger,- null,- minIntervalMs,- null,- null))- .withAuditInfo(- AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())- .build();- }-- private static PolicyEntity expirePolicy(boolean enabled, String timeTrigger) {- return PolicyEntity.builder()- .withId(42L)- .withName("expire")- .withNamespace(NamespaceUtil.ofPolicy("metalake"))- .withPolicyType(Policy.BuiltInType.ICEBERG_SNAPSHOT_EXPIRATION)- .withEnabled(enabled)- .withContent(PolicyContents.icebergSnapshotExpiration(timeTrigger, null, null, null, null))- .withAuditInfo(- AuditInfo.builder().withCreator("test").withCreateTime(Instant.now()).build())- .build();- }-}diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/expand/TestPolicyExpandSnapshotEnqueue.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/expand/TestPolicyExpandSnapshotEnqueue.javadeleted file mode 100644index 5ee2a2fb5f..0000000000--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/expand/TestPolicyExpandSnapshotEnqueue.java+++ /dev/null@@ -1,204 +0,0 @@-/*- * Licensed to the Apache Software Foundation (ASF) under one- * or more contributor license agreements. See the NOTICE file- * distributed with this work for additional information- * regarding copyright ownership. The ASF licenses this file- * to you under the Apache License, Version 2.0 (the- * "License"); you may not use this file except in compliance- * with the License. You may obtain a copy of the License at- *- * http://www.apache.org/licenses/LICENSE-2.0- *- * Unless required by applicable law or agreed to in writing,- * software distributed under the License is distributed on an- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY- * KIND, either express or implied. See the License for the- * specific language governing permissions and limitations- * under the License.- */-package org.apache.gravitino.maintenance.scheduler.policy.expand;--import com.github.kagkarlsson.scheduler.SchedulerClient;-import com.github.kagkarlsson.scheduler.task.TaskInstanceId;-import java.time.Instant;-import java.util.List;-import java.util.Map;-import java.util.Optional;-import java.util.stream.Collectors;-import javax.sql.DataSource;-import org.apache.gravitino.Config;-import org.apache.gravitino.MetadataObject;-import org.apache.gravitino.maintenance.policy.MaintenanceAuthConfigs;-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;-import org.apache.gravitino.maintenance.scheduler.MaintenanceTaskIds;-import org.apache.gravitino.maintenance.scheduler.TableMaintenanceSchedulerPools;-import org.apache.gravitino.maintenance.scheduler.job.cron.CronJobClient;-import org.apache.gravitino.maintenance.scheduler.job.cron.MaintenanceTableRefs.ResolvedTableRef;-import org.apache.gravitino.meta.AuditInfo;-import org.apache.gravitino.meta.PolicyEntity;-import org.apache.gravitino.policy.Policy;-import org.apache.gravitino.policy.PolicyContents;-import org.apache.gravitino.storage.relational.TestJDBCBackend;-import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;-import org.apache.gravitino.utils.NamespaceUtil;-import org.junit.jupiter.api.Assertions;-import org.junit.jupiter.api.TestTemplate;--/**- * Expand pipeline → real {@link CronJobClient}: snapshot-expiry coalesce across two policy expands- * (same catalog).- */-class TestPolicyExpandSnapshotEnqueue extends TestJDBCBackend {-- private static final String GRAVITINO_URI = "http://localhost:8090";- private static final String CRON = "0 0 2 * * ?";-- @TestTemplate- void testTwoPolicyExpandsCoalesceSameCatalogTables() {- DataSource dataSource = dataSource();- CronJobClient cronJobs = cronScheduler(dataSource);-- PolicyEntity policyA = expirePolicy(9L);- PolicyEntity policyB = expirePolicy(10L);- PolicyTableEnumerator tablesA =- (policy, limit, gate, minIntervalMs) ->- List.of(new ExpandTableCandidate(21L, MetadataObject.Type.TABLE));- PolicyTableEnumerator tablesB =- (policy, limit, gate, minIntervalMs) ->- List.of(new ExpandTableCandidate(22L, MetadataObject.Type.TABLE));-- PolicyExpandPipeline expandA =- new PolicyExpandPipeline(- id -> id == 9L ? Optional.of(policyA) : Optional.empty(),- tablesA,- cronJobs,- (t, p, m, n) -> false,- configWithUri(),- 10);- PolicyExpandPipeline expandB =- new PolicyExpandPipeline(- id -> id == 10L ? Optional.of(policyB) : Optional.empty(),- tablesB,- cronJobs,- (t, p, m, n) -> false,- configWithUri(),- 10);-- Assertions.assertTrue(expandA.expand(9L).isPresent());- Assertions.assertTrue(expandB.expand(10L).isPresent());-- SchedulerClient client = CronJobClient.schedulerClient(dataSource);- Assertions.assertTrue(- client- .getScheduledExecution(- TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB,- MaintenanceTaskIds.forCronTable(21L, 9L)))- .isEmpty());- Assertions.assertTrue(- client- .getScheduledExecution(- TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB,- MaintenanceTaskIds.forCronTable(22L, 10L)))- .isEmpty());- TaskInstanceId batch =- TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronBatch(0L, 10L));- Assertions.assertTrue(client.getScheduledExecution(batch).isPresent());- MaintenanceJobSpec data =- (MaintenanceJobSpec) client.getScheduledExecution(batch).get().getData();- Assertions.assertEquals(List.of(22L, 21L), data.tableIds());- }-- @TestTemplate- void testSchemaExpandAbsorbsPriorTableCronJob() {- DataSource dataSource = dataSource();- CronJobClient cronJobs = cronScheduler(dataSource);- PolicyEntity policy = expirePolicy(9L);-- PolicyExpandPipeline tableExpand =- new PolicyExpandPipeline(- id -> Optional.of(policy),- (p, limit, gate, min) ->- List.of(new ExpandTableCandidate(99L, MetadataObject.Type.TABLE)),- cronJobs,- (t, p, m, n) -> false,- configWithUri(),- 10);- PolicyExpandPipeline schemaExpand =- new PolicyExpandPipeline(- id -> Optional.of(policy),- (p, limit, gate, min) ->- List.of(- new ExpandTableCandidate(10L, MetadataObject.Type.SCHEMA),- new ExpandTableCandidate(11L, MetadataObject.Type.SCHEMA)),- cronJobs,- (t, p, m, n) -> false,- configWithUri(),- 10);-- Assertions.assertTrue(tableExpand.expand(9L).isPresent());- Assertions.assertTrue(schemaExpand.expand(9L).isPresent());-- SchedulerClient client = CronJobClient.schedulerClient(dataSource);- Assertions.assertTrue(- client- .getScheduledExecution(- TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB,- MaintenanceTaskIds.forCronTable(99L, 9L)))- .isEmpty());- MaintenanceJobSpec data =- (MaintenanceJobSpec)- client- .getScheduledExecution(- TaskInstanceId.of(- TableMaintenanceSchedulerPools.CRON_JOB,- MaintenanceTaskIds.forCronBatch(0L, 9L)))- .get()- .getData();- Assertions.assertEquals(List.of(10L, 11L, 99L), data.tableIds());- }-- private static CronJobClient cronScheduler(DataSource dataSource) {- return new CronJobClient(- dataSource,- configWithUri(),- ids ->- ids.stream()- .map(id -> new ResolvedTableRef(id, "iceberg", "db.t" + id))- .collect(Collectors.toList()));- }-- private static DataSource dataSource() {- return SqlSessionFactoryHelper.getInstance()- .getSqlSessionFactory()- .getConfiguration()- .getEnvironment()- .getDataSource();- }-- private static Config configWithUri() {- Config config = new Config(false) {};- config.loadFromMap(- Map.of(- MaintenanceAuthConfigs.GRAVITINO_MAINTENANCE_GRAVITINO_AUTH_URI.getKey(),- GRAVITINO_URI),- t -> true);- return config;- }-- private static PolicyEntity expirePolicy(long id) {- return PolicyEntity.builder()- .withId(id)- .withName("e-" + id)- .withNamespace(NamespaceUtil.ofPolicy("ml"))- .withPolicyType(Policy.BuiltInType.ICEBERG_SNAPSHOT_EXPIRATION)- .withEnabled(true)- .withContent(PolicyContents.icebergSnapshotExpiration(CRON, null, null, null, null))- .withAuditInfo(- AuditInfo.builder().withCreator("test").withCreateTime(Instant.EPOCH).build())- .build();- }-}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 daf91ddc61..9a6681c020 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@@ -20,7 +20,7 @@ package org.apache.gravitino.maintenance.storage;import java.sql.PreparedStatement;import java.sql.SQLException;-import org.apache.gravitino.maintenance.storage.service.OccupancyClaim;+import org.apache.gravitino.maintenance.model.OccupancyClaim;import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;import org.apache.ibatis.session.SqlSession;import org.junit.jupiter.api.Assertions;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 c4844eef1c..8a3bb430cf 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@@ -24,6 +24,7 @@ import static org.apache.gravitino.maintenance.storage.TableMaintenanceActionTesimport java.util.List;import java.util.Optional;import org.apache.gravitino.maintenance.TableMaintenanceConfig;+import org.apache.gravitino.maintenance.model.OccupancyClaim;import org.apache.gravitino.storage.relational.TestJDBCBackend;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.TestTemplate;@@ -38,8 +39,12 @@ class TestTableMaintenanceActionMetaService extends TestJDBCBackend {long before = System.currentTimeMillis();OccupancyClaim claim =- actionService.insertInFlight(- 10L, 20L, TableMaintenanceConfig.forTest(1, 1, 1, 500L, 1_000L, 4, 10));+ actionService+ .tryAcquireInFlight(+ 10L,+ 20L,+ TableMaintenanceConfig.forTest(1, 1, 1, 500L, 1_000L, 4, 10).claimTimeoutMs())+ .orElseThrow();long after = System.currentTimeMillis();Assertions.assertNull(actionService.getById(claim.actionId()).jobId());Assertions.assertEquals(0L, actionService.getById(claim.actionId()).finishedAt());@@ -87,13 +92,14 @@ class TestTableMaintenanceActionMetaService extends TestJDBCBackend {TableMaintenanceActionMetaService actions = TableMaintenanceActionMetaService.getInstance();TableMaintenanceConfig config = TableMaintenanceConfig.forTest(1, 1, 1, 500L, 1_000L, 4, 10);long jobId = 777L;- OccupancyClaim claimA = actions.insertInFlight(101L, 201L, config);- OccupancyClaim claimB = actions.insertInFlight(102L, 202L, config);+ OccupancyClaim claimA =+ actions.tryAcquireInFlight(101L, 201L, config.claimTimeoutMs()).orElseThrow();+ OccupancyClaim claimB =+ actions.tryAcquireInFlight(102L, 202L, config.claimTimeoutMs()).orElseThrow();actions.bindJobId(claimA, jobId);actions.bindJobId(claimB, jobId);Assertions.assertEquals(2, actions.listByJobId(jobId).size());- Assertions.assertThrows(IllegalStateException.class, () -> actions.getByJobId(jobId));actions.recordBeforeMetrics(claimA.actionId(), 11L);actions.recordBeforeMetrics(claimB.actionId(), 22L);@@ -119,7 +125,8 @@ class TestTableMaintenanceActionMetaService extends TestJDBCBackend {long tableId = 31L;long policyId = 41L;long jobId = 5100L;- OccupancyClaim claim = actions.insertInFlight(tableId, policyId, config);+ OccupancyClaim claim =+ actions.tryAcquireInFlight(tableId, policyId, config.claimTimeoutMs()).orElseThrow();actions.bindJobId(claim, jobId);// Spark lazy-bound first; submit-side bind must not fail.actions.bindJobId(claim, jobId);@@ -134,8 +141,10 @@ class TestTableMaintenanceActionMetaService extends TestJDBCBackend {long policyA = 48L;long policyB = 49L;long jobId = 5700L;- OccupancyClaim claimA = actions.insertInFlight(tableId, policyA, config);- OccupancyClaim claimB = actions.insertInFlight(tableId, policyB, config);+ OccupancyClaim claimA =+ actions.tryAcquireInFlight(tableId, policyA, config.claimTimeoutMs()).orElseThrow();+ OccupancyClaim claimB =+ actions.tryAcquireInFlight(tableId, policyB, config.claimTimeoutMs()).orElseThrow();actions.bindJobId(claimA, jobId);actions.bindJobId(claimB, jobId);// Spark may lazy-bind before commit-chain submit-side bindJobIds.@@ -148,48 +157,12 @@ class TestTableMaintenanceActionMetaService extends TestJDBCBackend {void testBindJobIdFailsWhenBoundToDifferentJob() {TableMaintenanceActionMetaService actions = TableMaintenanceActionMetaService.getInstance();TableMaintenanceConfig config = TableMaintenanceConfig.forTest(1, 1, 1, 500L, 1_000L, 4, 10);- OccupancyClaim claim = actions.insertInFlight(32L, 42L, config);+ OccupancyClaim claim =+ actions.tryAcquireInFlight(32L, 42L, config.claimTimeoutMs()).orElseThrow();actions.bindJobId(claim, 5200L);Assertions.assertThrows(IllegalStateException.class, () -> actions.bindJobId(claim, 5201L));}- @TestTemplate- void testBindJobIdIfUnboundLazyBindsSoleClaim() {- TableMaintenanceActionMetaService actions = TableMaintenanceActionMetaService.getInstance();- TableMaintenanceConfig config = TableMaintenanceConfig.forTest(1, 1, 1, 500L, 1_000L, 4, 10);- long tableId = 33L;- long policyId = 43L;- long jobId = 5300L;- actions.insertInFlight(tableId, policyId, config);-- Assertions.assertTrue(actions.bindJobIdIfUnbound(tableId, policyId, jobId));- Assertions.assertEquals(- jobId, actions.getByJobIdAndTableIdAndPolicyId(jobId, tableId, policyId).jobId());- // Already bound to same job — still reports success via idempotent bind.- Assertions.assertTrue(actions.bindJobIdIfUnbound(tableId, policyId, jobId));- }-- @TestTemplate- void testBindJobIdIfUnboundDisambiguatesPoliciesOnSameTable() {- TableMaintenanceActionMetaService actions = TableMaintenanceActionMetaService.getInstance();- TableMaintenanceConfig config = TableMaintenanceConfig.forTest(1, 1, 1, 500L, 1_000L, 4, 10);- long tableId = 34L;- long policyA = 44L;- long policyB = 45L;- long jobId = 5400L;- // Two policies → two soft slots on the same table; policyId selects which claim to bind.- actions.insertInFlight(tableId, policyA, config);- actions.insertInFlight(tableId, policyB, config);-- Assertions.assertTrue(actions.bindJobIdIfUnbound(tableId, policyA, jobId));- Assertions.assertEquals(- jobId, actions.getByJobIdAndTableIdAndPolicyId(jobId, tableId, policyA).jobId());- Assertions.assertNull(actions.getByJobIdAndTableIdAndPolicyId(jobId, tableId, policyB));- Assertions.assertTrue(actions.bindJobIdIfUnbound(tableId, policyB, jobId));- Assertions.assertEquals(- jobId, actions.getByJobIdAndTableIdAndPolicyId(jobId, tableId, policyB).jobId());- }-@TestTemplatevoid testOneJobMultiplePoliciesOnSameTableRecordAndFinishPerPolicy() {TableMaintenanceActionMetaService actions = TableMaintenanceActionMetaService.getInstance();@@ -198,8 +171,10 @@ class TestTableMaintenanceActionMetaService extends TestJDBCBackend {long policyA = 46L;long policyB = 47L;long jobId = 5600L;- OccupancyClaim claimA = actions.insertInFlight(tableId, policyA, config);- OccupancyClaim claimB = actions.insertInFlight(tableId, policyB, config);+ OccupancyClaim claimA =+ actions.tryAcquireInFlight(tableId, policyA, config.claimTimeoutMs()).orElseThrow();+ OccupancyClaim claimB =+ actions.tryAcquireInFlight(tableId, policyB, config.claimTimeoutMs()).orElseThrow();actions.bindJobId(claimA, jobId);actions.bindJobId(claimB, jobId);@@ -218,12 +193,6 @@ class TestTableMaintenanceActionMetaService extends TestJDBCBackend {0L, actions.getByJobIdAndTableIdAndPolicyId(jobId, tableId, policyB).finishedAt());}- @TestTemplate- void testBindJobIdIfUnboundReturnsFalseWhenNoClaim() {- TableMaintenanceActionMetaService actions = TableMaintenanceActionMetaService.getInstance();- Assertions.assertFalse(actions.bindJobIdIfUnbound(35L, 55L, 5500L));- }-@TestTemplatevoid testTryAcquireRejectsLiveUnboundAndReclaimsExpired() throws Exception {TableMaintenanceActionMetaService actions = TableMaintenanceActionMetaService.getInstance();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 a6a87604c9..d20de8419b 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@@ -18,24 +18,21 @@*/package org.apache.gravitino.maintenance.web.rest;+import static org.mockito.ArgumentMatchers.anyBoolean;import static org.mockito.ArgumentMatchers.anyLong;import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.doThrow;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;-import org.apache.gravitino.maintenance.MaintenanceMetricsService;+import org.apache.gravitino.exceptions.NoSuchEntityException;+import org.apache.gravitino.maintenance.MaintenanceMetricsManager;import org.apache.gravitino.maintenance.dto.requests.MaintenanceActionFinishRequest;import org.apache.gravitino.maintenance.dto.requests.MaintenanceActionMetricsRequest;-import org.apache.gravitino.maintenance.storage.po.TableMaintenanceActionPO;-import org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService;-import org.apache.gravitino.maintenance.storage.service.TableSnapshotMetricsMetaService;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;@@ -47,130 +44,60 @@ class TestTableMaintenanceActionOperations {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 MaintenanceMetricsManager metricsManager;private TableMaintenanceActionOperations ops;@BeforeEachvoid setUp() throws Exception {- actions = mock(TableMaintenanceActionMetaService.class);- metrics = mock(TableSnapshotMetricsMetaService.class);- ops = operations(id -> METALAKE);+ metricsManager = mock(MaintenanceMetricsManager.class);+ ops = new TableMaintenanceActionOperations(metricsManager);Field httpRequest = TableMaintenanceActionOperations.class.getDeclaredField("httpRequest");httpRequest.setAccessible(true);httpRequest.set(ops, mock(HttpServletRequest.class));}@Test- 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,- ACTION_ID,- /*finish=*/ false,- new MaintenanceActionMetricsRequest(TABLE_ID, POLICY_ID, 100L, "{\"m\":1}"));-+ void testReportBeforeDelegatesToManager() {+ MaintenanceActionMetricsRequest request =+ new MaintenanceActionMetricsRequest(TABLE_ID, POLICY_ID, 100L, "{\"m\":1}");+ Response response = ops.reportBeforeMetrics(METALAKE, ACTION_ID, /*finish=*/ false, request);Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());- verify(metrics).insertMetrics(TABLE_ID, POLICY_ID, 100L, "{\"m\":1}");- verify(actions).recordBeforeMetrics(ACTION_ID, 501L);- verify(actions, never()).markFinished(anyLong(), anyLong());+ verify(metricsManager).reportBeforeMetrics(METALAKE, ACTION_ID, false, request);}@Test- 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,- ACTION_ID,- /*finish=*/ true,- new MaintenanceActionMetricsRequest(TABLE_ID, POLICY_ID, 100L, "{\"m\":1}"));-+ void testReportAfterDelegatesToManager() {+ MaintenanceActionMetricsRequest request =+ new MaintenanceActionMetricsRequest(TABLE_ID, POLICY_ID, 200L, "{\"m\":2}");+ Response response = ops.reportAfterMetrics(METALAKE, ACTION_ID, /*finish=*/ true, request);Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());- verify(actions).markFinished(eq(ACTION_ID), anyLong());- }-- @Test- 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,- 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).recordAfterMetrics(ACTION_ID, 502L);- verify(actions).markFinished(eq(ACTION_ID), anyLong());- }-- @Test- void testReportBeforeMissingActionReturns404() {- when(actions.getById(ACTION_ID)).thenReturn(null);-- Response response =- ops.reportBeforeMetrics(- METALAKE,- ACTION_ID,- /*finish=*/ false,- new MaintenanceActionMetricsRequest(TABLE_ID, POLICY_ID, 100L, "{\"m\":1}"));-- Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());- verify(metrics, never()).insertMetrics(anyLong(), anyLong(), anyLong(), anyString());- }-- @Test- void testReportBeforeUnboundActionReturns404() {- when(actions.getById(ACTION_ID)).thenReturn(action(TABLE_ID, POLICY_ID, 0L, /*jobId=*/ null));-- Response response =- ops.reportBeforeMetrics(- METALAKE,- ACTION_ID,- /*finish=*/ false,- new MaintenanceActionMetricsRequest(TABLE_ID, POLICY_ID, 100L, "{\"m\":1}"));-- Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());- verify(metrics, never()).insertMetrics(anyLong(), anyLong(), anyLong(), anyString());+ verify(metricsManager).reportAfterMetrics(METALAKE, ACTION_ID, true, request);}@Test- void testFinishClosesSoftSlotWithoutMetrics() {- when(actions.getById(ACTION_ID)).thenReturn(action(TABLE_ID, POLICY_ID));-- Response response =- ops.finishAction(- METALAKE, ACTION_ID, new MaintenanceActionFinishRequest(TABLE_ID, POLICY_ID));-+ void testFinishDelegatesToManager() {+ MaintenanceActionFinishRequest request =+ new MaintenanceActionFinishRequest(TABLE_ID, POLICY_ID);+ Response response = ops.finishAction(METALAKE, ACTION_ID, request);Assertions.assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());- verify(metrics, never()).insertMetrics(anyLong(), anyLong(), anyLong(), anyString());- verify(actions).markFinished(eq(ACTION_ID), anyLong());+ verify(metricsManager).finishAction(METALAKE, ACTION_ID, request);}@Test- void testReportAfterAlreadyFinishedReturns404() {- when(actions.getById(ACTION_ID)).thenReturn(action(TABLE_ID, POLICY_ID, /*finishedAt=*/ 9L));-- Response response =- ops.reportAfterMetrics(- METALAKE,- ACTION_ID,- /*finish=*/ false,- new MaintenanceActionMetricsRequest(TABLE_ID, POLICY_ID, 100L, "{\"m\":1}"));-+ void testManagerNotFoundMappedTo404() {+ doThrow(new NoSuchEntityException("missing"))+ .when(metricsManager)+ .reportBeforeMetrics(anyString(), anyLong(), anyBoolean(), eq(null));+ // null body is rejected before manager; use a real body and force manager 404+ MaintenanceActionMetricsRequest request =+ new MaintenanceActionMetricsRequest(TABLE_ID, POLICY_ID, 100L, "{\"m\":1}");+ doThrow(new NoSuchEntityException("missing"))+ .when(metricsManager)+ .reportBeforeMetrics(METALAKE, ACTION_ID, false, request);++ Response response = ops.reportBeforeMetrics(METALAKE, ACTION_ID, /*finish=*/ false, request);Assertions.assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());- verify(metrics, never()).insertMetrics(anyLong(), anyLong(), anyLong(), anyString());}@Test@@ -178,28 +105,4 @@ class TestTableMaintenanceActionOperations {Response response = ops.reportBeforeMetrics(METALAKE, ACTION_ID, /*finish=*/ false, null);Assertions.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());}-- 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, 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()- .withActionId(ACTION_ID)- .withJobId(jobId)- .withTableId(tableId)- .withPolicyId(policyId)- .withFinishedAt(finishedAt)- .build();- }}