Skip to content

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

[MINOR] feat(tms): Coalesce snapshot-expiry cron jobs; rename enqueue clients (#14277)

MaSai800eefa6e60e
diff --git a/design-docs/table-maintenance-service-design.md b/design-docs/table-maintenance-service-design.md
index 8147d3e7d7..3fa9cd8883 100644
--- a/design-docs/table-maintenance-service-design.md
+++ b/design-docs/table-maintenance-service-design.md
@@ -129,10 +129,10 @@ parts:
Do **not** overload “task type”. TMS uses two different identities:
-| Concept | Meaning | Identity today |
-| ------- | ------- | -------------- |
+| Concept | Meaning | Identity today |
+| -------------------------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------ |
| **Policy / activity type** | Which maintenance the policy describes (compaction, manifest-rewrite, snapshot-expiry, orphan-cleanup) | `Policy.BuiltInType` (e.g. `ICEBERG_COMPACTION`) |
-| **Scheduler task kind** | Which db-scheduler row / pool owns the work | `policy-expand`, `cron-job`, `commit-job` |
+| **Scheduler task kind** | Which db-scheduler row / pool owns the work | `policy-expand`, `cron-job`, `commit-job` |
Rules:
@@ -162,14 +162,14 @@ soft-slot claim, light in-flight checks, then `runJob` — and does **not** re-c
rebuild `jobConf`. Both paths end with a short control-plane `runJob` on the Gravitino Job
framework. Read policy first, then scheduling.
-| Store | Role |
-| -------------------------------------------------------------- | ------------------------------------------------------------ |
-| `policy_meta` / `policy_relation_meta` / `policy_version_info` | Triggers + `minIntervalMs` + `jobOptions` / `rewriteOptions` |
-| `scheduled_expand_tasks` / `scheduled_cron_tasks` / `scheduled_commit_tasks` | Scheduler rows (one db-scheduler table per pool) |
-| `table_maintenance_job` | Per-run occupancy; before/after `snapshot_id` |
-| `table_snapshot_metrics` | Metrics keyed by Iceberg `snapshot_id` |
-| `gravitino.conf` | Cluster-static Gravitino / IRC client auth |
-| `job_run_meta` | Spark job run record / `runtime_job_template` |
+| Store | Role |
+| ---------------------------------------------------------------------------- | ------------------------------------------------------------ |
+| `policy_meta` / `policy_relation_meta` / `policy_version_info` | Triggers + `minIntervalMs` + `jobOptions` / `rewriteOptions` |
+| `scheduled_expand_tasks` / `scheduled_cron_tasks` / `scheduled_commit_tasks` | Scheduler rows (one db-scheduler table per pool) |
+| `table_maintenance_job` | Per-run occupancy; before/after `snapshot_id` |
+| `table_snapshot_metrics` | Metrics keyed by Iceberg `snapshot_id` |
+| `gravitino.conf` | Cluster-static Gravitino / IRC client auth |
+| `job_run_meta` | Spark job run record / `runtime_job_template` |
### 5.1 Policy
@@ -187,10 +187,10 @@ state for db-scheduler — not where operators set triggers.
TMS has two trigger modes. They never feed each other's queues:
-| Wire field | Runtime path | Which types |
-| ---------------- | ----------------------------------------- | ----------------------------------------------- |
-| `commitTrigger` | IRC → **commit-job** only (skips expand) | Compaction / manifest-rewrite / snapshot-expiry |
-| `timeTrigger` | **policy-expand** → cron-job | All four types |
+| Wire field | Runtime path | Which types |
+| --------------- | ---------------------------------------- | ----------------------------------------------- |
+| `commitTrigger` | IRC → **commit-job** only (skips expand) | Compaction / manifest-rewrite / snapshot-expiry |
+| `timeTrigger` | **policy-expand** → cron-job | All four types |
**`commitTrigger`** runs after a successful Iceberg commit through IRC. That fits types that
rewrite or expire data and metadata from the commit stream. **`orphan-cleanup` does not:**
@@ -223,12 +223,12 @@ Example content:
}
```
-| Field | Runtime effect |
-| ---------------- | ----------------------------------------------------------------- |
-| `commitTrigger` | IRC upserts commit-job; commit pool submits one chained Job |
-| `timeTrigger` | Sets / refreshes next `policy-expand` due time |
-| `minIntervalMs` | Cooldown for this policy's type; highest when set |
-| `jobOptions` | Non-sensitive Spark / IRC client props (`uri`, `type`, memory, …) |
+| Field | Runtime effect |
+| ---------------- | ---------------------------------------------------------------------- |
+| `commitTrigger` | IRC upserts commit-job; commit pool submits one chained Job |
+| `timeTrigger` | Sets / refreshes next `policy-expand` due time |
+| `minIntervalMs` | Cooldown for this policy's type; highest when set |
+| `jobOptions` | Non-sensitive Spark / IRC client props (`uri`, `type`, memory, …) |
| `updaterOptions` | Non-sensitive Gravitino updater props (`gravitino_uri`, `metalake`, …) |
#### 5.1.2 Sensitive credentials
@@ -251,21 +251,21 @@ They are not interchangeable: one principal for metalake APIs, one for IRC.
At `runJob`, the control plane builds the Job template’s two bags and **overlays** auth onto
each — it does not write secrets back into policy content:
-| Runtime bag | Non-sensitive (examples) | Auth overlay |
-| ------------------- | ------------------------------------------------------------- | --------------------------------------- |
+| Runtime bag | Non-sensitive (examples) | Auth overlay |
+| -------------------- | ------------------------------------------------------------- | --------------------------------------- |
| **`updaterOptions`** | `gravitino_uri`, `metalake`, updater impl names, … | `gravitino.maintenance.gravitinoAuth.*` |
-| **`jobOptions`** | nearest policy `jobOptions` (`uri`, `type`, Spark resources…) | `gravitino.maintenance.ircAuth.*` |
+| **`jobOptions`** | nearest policy `jobOptions` (`uri`, `type`, Spark resources…) | `gravitino.maintenance.ircAuth.*` |
### 5.2 Scheduling and commit
db-scheduler runs **three** isolated pools. Each pool needs its own physical task table (upstream
db-scheduler does not support sharing one table across Scheduler instances):
-| Pool | Table | `task_name` | Role |
-| ------ | ------------------------- | --------------- | ----------------------------------------------- |
-| Expand | `scheduled_expand_tasks` | `policy-expand` | Long-lived lease per policy; fans out cron-jobs |
-| Cron | `scheduled_cron_tasks` | `cron-job` | One-shot crontab Spark submit |
-| Commit | `scheduled_commit_tasks` | `commit-job` | One-shot commit-triggered chained Spark submit |
+| Pool | Table | `task_name` | Role |
+| ------ | ------------------------ | --------------- | ----------------------------------------------- |
+| Expand | `scheduled_expand_tasks` | `policy-expand` | Long-lived lease per policy; fans out cron-jobs |
+| Cron | `scheduled_cron_tasks` | `cron-job` | One-shot crontab Spark submit |
+| Commit | `scheduled_commit_tasks` | `commit-job` | One-shot commit-triggered chained Spark submit |
**policy-expand** stays after each pick. **cron-job** and **commit-job** are deleted after a
short `runJob`. Spark lifetime and in-flight checks use `table_maintenance_action`, not those
@@ -280,24 +280,38 @@ heartbeats free only a hung **short** callback — not a long-running Spark Job.
| Cron | cron-job | 8 | `scheduler.cronThreads` |
| Commit | commit-job | 4 | `scheduler.commitThreads` |
+
PK is `(task_name, task_instance)`. Each table uses upstream db-scheduler DDL (MySQL
`DATETIME(6)` / PostgreSQL `TIMESTAMP WITH TIME ZONE` time columns).
+`task_name` is the registered handler kind (kebab-case, fixed). `task_instance` encodes the
+subject as `key:value` pairs separated by `;` (`:` only inside a pair):
+
+| `task_name` | `task_instance` | Notes |
+| --------------- | ------------------------------------- | ----------------------------------------------- |
+| `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) |
+
+Merging extra tables into an open snapshot-expiry row **does not rename** `task_instance`; it
+updates `task_data` (or inserts a new `batch:…` row and cancels the old `table:…` rows).
+
**TMS tables used by cron-job and commit-job**
`job_run_meta` already records Spark runs. TMS still needs its own per-run row for **in-flight
gates**, **`minIntervalMs`**, and Iceberg **before/after snapshot ids**. That is
`table_maintenance_job`. Metric **values** live in `table_snapshot_metrics`.
-| Column | Type | Notes |
-| -------------------- | -------------------------- | ------------------------------------------------------------------------------------------ |
-| `id` | `BIGINT UNSIGNED` PK | Auto increment |
+| Column | Type | Notes |
+| -------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
+| `id` | `BIGINT UNSIGNED` PK | Auto increment |
| `job_id` | `BIGINT UNSIGNED NULL` | Set at `runJob`; maps to `job_run_meta.job_run_id`; **non-unique** — one Spark job may bind multiple tables; null if released before submit |
-| `table_id` | `BIGINT UNSIGNED NOT NULL` | `table_meta` PK |
-| `policy_id` | `BIGINT UNSIGNED NOT NULL` | Soft slot per policy. Cron: that Job's policy. Commit chain: one row per chain member (same `job_id`) |
-| `before_snapshot_id` | `BIGINT NULL` | Set inside the Spark Job when S0 is sampled |
-| `after_snapshot_id` | `BIGINT NULL` | Iceberg snapshot after job terminal; null while pending |
-| `finished_at` | `BIGINT UNSIGNED NULL` | Epoch millis; **null = in-flight** |
+| `table_id` | `BIGINT UNSIGNED NOT NULL` | `table_meta` PK |
+| `policy_id` | `BIGINT UNSIGNED NOT NULL` | Soft slot per policy. Cron: that Job's policy. Commit chain: one row per chain member (same `job_id`) |
+| `before_snapshot_id` | `BIGINT NULL` | Set inside the Spark Job when S0 is sampled |
+| `after_snapshot_id` | `BIGINT NULL` | Iceberg snapshot after job terminal; null while pending |
+| `finished_at` | `BIGINT UNSIGNED NULL` | Epoch millis; **null = in-flight** |
```sql
CREATE TABLE IF NOT EXISTS `table_maintenance_job` (
@@ -342,8 +356,8 @@ The three subsections below describe each task kind.
#### 5.2.1 `policy-expand`
-Each policy has one long-lived expand row (`{policy_id}`). Expand does not run Spark. When its
-crontab is due, it turns the policy into many short **cron-job** rows (one candidate table at a
+Each policy has one long-lived expand row (`policy:{policy_id}`). Expand does not run Spark. When
+its crontab is due, it turns the policy into many short **cron-job** rows (one candidate table at a
time). The expand row itself stays; only its next due time moves.
- **Create / enable:** insert the expand row, due at the next crontab.
@@ -367,8 +381,9 @@ many cron-jobs due now, then schedules itself for the next 02:00. Expand's due t
Expand writes these one-shot rows **with an enqueue-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.
-Most types use one table per job (`table:{table_id}:{policy_id}`). Batched **snapshot-expiry**
-may use `batch:{batch_id}:{policy_id}` (one snapshot covering several same-catalog tables).
+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 several
+same-catalog tables; member table ids live in `task_data`).
When a cron-job is due (cron pool), keep the callback short — consume the snapshot, claim, submit;
do not sample or rebuild `jobConf` here. For a batch row, **any** in-flight table aborts the whole
@@ -401,7 +416,7 @@ A later wake-up sees the fresher state.
#### 5.2.3 `commit-job`
After a successful IRC table update in the same JVM, an `EventListenerPlugin` upserts one
-commit-job for that table (`{table_id}`). Register it with `gravitino.eventListener.names` /
+commit-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)
builds the onCommit chain and snapshot, then inserts the row.
@@ -509,7 +524,7 @@ gravitino.maintenance.scheduler.commitThreads = 4
`extensionPackages` plus colocated IRC start the TMS Feature and db-scheduler pools. The
**event-listener** config wakes commit maintenance: on successful IRC `IcebergUpdateTableEvent`,
-the listener upserts `commit-job` / `{table_id}`. Without it, the crontab path still works;
+the listener upserts `commit-job` / `table:{table_id}`. Without it, the crontab path still works;
onCommit does not. HTTP / Kafka commit ingress is out of scope.
### 7.2 Scheduler pools
@@ -549,10 +564,10 @@ interval only limits how often a type may run after the last finished job.
Cluster-static — **not** in policy content and **not** a DB table.
-| Prefix | Role | Merged into `runJob` bag |
-| -------------------------------------- | ------------------------------------------------------------ | ----------------------------------------------- |
+| Prefix | Role | Merged into `runJob` bag |
+| -------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------ |
| `gravitino.maintenance.gravitinoAuth.` | Expand / submit / RBAC client; also jobs that call Gravitino | `updaterOptions` (+ non-sensitive updater props) |
-| `gravitino.maintenance.ircAuth.` | Iceberg REST client auth for Spark Jobs → IRC | `jobOptions` (+ policy non-sensitive props) |
+| `gravitino.maintenance.ircAuth.` | Iceberg REST client auth for Spark Jobs → IRC | `jobOptions` (+ policy non-sensitive props) |
Illustrative auth keys (same shape under each prefix; values may be SecretManager references where
the deployment supports them). Auth keys are **overlaid** onto each bag; they do not replace
@@ -584,13 +599,13 @@ gravitino.maintenance.ircAuth.oauthCredential = client_id:client_secret
## 8. Work Plan and Checklist
-| Phase | Work |
-| ----- | --------------------------------------------------------------------------------- |
-| 1 | `TableMaintenanceRESTFeature`; start/stop three db-scheduler pools |
-| 2 | `PolicyExpandPipeline` + `MaintenanceSparkSubmitPipeline` + gates |
+| Phase | Work |
+| ----- | ------------------------------------------------------------------------------------- |
+| 1 | `TableMaintenanceRESTFeature`; start/stop three db-scheduler pools |
+| 2 | `PolicyExpandPipeline` + `MaintenanceSparkSubmitPipeline` + 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 |
+| 4 | IRC EventListener upserts commit-job; policy create → INSERT expand; Job listener |
+| 5 | Metrics, shutdown, docs; `gravitino.conf` client auth; privilege docs |
Implementation checklist:
@@ -601,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_id}`; Spark
+ `maintenance_types` / `policy_ids`; orphan crontab-only; coalesce 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/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
index facf3d3ec8..ade19680e0 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
@@ -28,9 +28,8 @@ 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.scheduler.job.commit.CommitJobScheduler;
-import org.apache.gravitino.maintenance.scheduler.job.commit.CommitJobUpsertResult;
-import org.apache.gravitino.maintenance.scheduler.job.commit.RelationalCommitJobScheduler;
+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.storage.relational.service.TableMetaService;
import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
@@ -38,7 +37,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * Upserts a one-shot {@code commit-job} / {@code {table_id}} after a successful IRC table update
+ * Enqueues a one-shot {@code commit-job} / {@code {table_id}} after a successful IRC table update
* (§5.2.3).
*
* <p>Register with {@code gravitino.eventListener.names} / {@code .{name}.class}. Enqueue builds
@@ -56,7 +55,7 @@ public class PostCommitMaintenanceListener implements EventListenerPlugin {
static final String ICEBERG_UPDATE_TABLE_EVENT =
"org.apache.gravitino.listener.api.event.IcebergUpdateTableEvent";
- private CommitJobScheduler commitJobScheduler;
+ private CommitJobClient commitJobClient;
private Function<NameIdentifier, TableEntity> tableLookupOverride;
@Override
@@ -71,13 +70,13 @@ public class PostCommitMaintenanceListener implements EventListenerPlugin {
if (gravitinoConfig == null) {
throw new IllegalStateException("GravitinoEnv config is not available");
}
- this.commitJobScheduler = new RelationalCommitJobScheduler(dataSource, gravitinoConfig);
- LOG.info("PostCommitMaintenanceListener started (commit-job upsert with spec)");
+ this.commitJobClient = new CommitJobClient(dataSource, gravitinoConfig);
+ LOG.info("PostCommitMaintenanceListener started (commit-job enqueue with spec)");
}
@Override
public void stop() throws RuntimeException {
- commitJobScheduler = null;
+ commitJobClient = null;
}
@Override
@@ -94,15 +93,15 @@ public class PostCommitMaintenanceListener implements EventListenerPlugin {
}
/**
- * Resolves {@code identifier} to a table entity id and upserts {@code commit-job}.
+ * 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) {
- CommitJobScheduler scheduler = commitJobScheduler;
- if (scheduler == null) {
- LOG.debug("Ignoring IcebergUpdateTableEvent; commit-job scheduler is not started");
+ CommitJobClient client = commitJobClient;
+ if (client == null) {
+ LOG.debug("Ignoring IcebergUpdateTableEvent; commit-job client is not started");
return;
}
if (identifier == null) {
@@ -110,10 +109,10 @@ public class PostCommitMaintenanceListener implements EventListenerPlugin {
}
try {
long tableId = resolveTableId(identifier);
- CommitJobUpsertResult result = scheduler.upsertDueNow(tableId);
+ CommitJobEnqueueResult result = client.enqueueNow(tableId);
switch (result) {
case INSERTED:
- LOG.info("Upserted commit-job for table {} ({})", tableId, identifier);
+ LOG.info("Enqueued commit-job for table {} ({})", tableId, identifier);
break;
case ALREADY_QUEUED:
LOG.debug("commit-job already queued for table {} ({})", tableId, identifier);
@@ -125,18 +124,18 @@ public class PostCommitMaintenanceListener implements EventListenerPlugin {
identifier);
break;
default:
- throw new IllegalStateException("Unexpected commit-job upsert result: " + result);
+ 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 upsert commit-job for IRC update {}: {}", identifier, e.toString());
+ LOG.warn("Failed to enqueue commit-job for IRC update {}: {}", identifier, e.toString());
}
}
@VisibleForTesting
- void setCommitJobScheduler(CommitJobScheduler commitJobScheduler) {
- this.commitJobScheduler = commitJobScheduler;
+ void setCommitJobClient(CommitJobClient commitJobClient) {
+ this.commitJobClient = commitJobClient;
}
@VisibleForTesting
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.java
index e38c46bef9..8c04bca777 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
@@ -23,6 +23,7 @@ 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 org.apache.gravitino.meta.PolicyEntity;
import org.apache.gravitino.policy.ExecutablePolicyContent;
@@ -122,19 +123,18 @@ public final class PolicyExpandLifecycleHook implements PolicyLifecycleHook {
* completion would leave the row picked, and db-scheduler then rejects alter and delete of that
* policy.
*
- * @param instanceId db-scheduler task instance id, the policy id
+ * @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) {
- long policyId;
- try {
- policyId = Long.parseLong(instanceId);
- } catch (NumberFormatException ignored) {
+ 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();
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.java
index 2ee07368f3..e61af6ea93 100644
--- 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.java
@@ -42,6 +42,7 @@ 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;
@@ -170,11 +171,8 @@ public final class PolicyExpandRegistrar {
TableMaintenanceSchedulerPools.POLICY_EXPAND,
Void.class,
execution -> {
- try {
- ids.add(Long.parseLong(execution.getTaskInstance().getId()));
- } catch (NumberFormatException ignored) {
- // Non-numeric instance ids are not policy-expand leases from this registrar.
- }
+ MaintenanceTaskIds.parseExpandPolicy(execution.getTaskInstance().getId())
+ .ifPresent(ids::add);
});
return ids;
}
@@ -195,7 +193,8 @@ public final class PolicyExpandRegistrar {
}
private static TaskInstanceId instanceId(long policyId) {
- return TaskInstanceId.of(TableMaintenanceSchedulerPools.POLICY_EXPAND, Long.toString(policyId));
+ return TaskInstanceId.of(
+ TableMaintenanceSchedulerPools.POLICY_EXPAND, MaintenanceTaskIds.forExpandPolicy(policyId));
}
private void scheduleOnce(long policyId, Instant due) {
diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/MaintenanceTaskIds.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/MaintenanceTaskIds.java
new file mode 100644
index 0000000000..86ec9e57af
--- /dev/null
+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/MaintenanceTaskIds.java
@@ -0,0 +1,168 @@
+/*
+ * 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 java.util.Optional;
+
+/**
+ * Builds and parses db-scheduler {@code task_instance} id strings for TMS expand / cron / commit
+ * pools (§5.2).
+ *
+ * <p>Two separators:
+ *
+ * <ul>
+ * <li>{@link #KV_SEP} {@code ':'} — separates a <em>key</em> from its <em>value</em> inside one
+ * pair ({@code table:10})
+ * <li>{@link #PAIR_SEP} {@code ';'} — separates adjacent pairs ({@code table:10;policy:20})
+ * </ul>
+ *
+ * <p>Formats: {@code policy:{policy_id}} (expand); {@code table:{table_id};policy:{policy_id}} /
+ * {@code batch:{batch_id};policy:{policy_id}} (cron); {@code table:{table_id}} (commit).
+ */
+public final class MaintenanceTaskIds {
+
+ /**
+ * Key/value separator inside one pair. Example: {@code table} + {@link #KV_SEP} + {@code 10} →
+ * {@code table:10}.
+ */
+ public static final char KV_SEP = ':';
+
+ /**
+ * Pair separator between adjacent {@code key}{@link #KV_SEP}{@code value} pairs. Example: {@code
+ * table:10} + {@link #PAIR_SEP} + {@code policy:20} → {@code table:10;policy:20}.
+ */
+ public static final char PAIR_SEP = ';';
+
+ private static final String POLICY_KEY = "policy";
+ private static final String TABLE_KEY = "table";
+ private static final String BATCH_KEY = "batch";
+
+ private static final String POLICY_PAIR_PREFIX = POLICY_KEY + KV_SEP;
+ private static final String TABLE_PAIR_PREFIX = TABLE_KEY + KV_SEP;
+ private static final String BATCH_PAIR_PREFIX = BATCH_KEY + KV_SEP;
+ /** Leading {@link #PAIR_SEP} plus the {@code policy}{@link #KV_SEP} prefix of the next pair. */
+ private static final String POLICY_PAIR_SUFFIX = PAIR_SEP + POLICY_PAIR_PREFIX;
+
+ private MaintenanceTaskIds() {}
+
+ /**
+ * @param policyId policy entity id
+ * @return {@code policy:{policy_id}}
+ */
+ public static String forExpandPolicy(long policyId) {
+ return POLICY_PAIR_PREFIX + policyId;
+ }
+
+ /**
+ * @param tableId table entity id
+ * @param policyId policy entity id
+ * @return {@code table:{table_id};policy:{policy_id}}
+ */
+ public static String forCronTable(long tableId, long policyId) {
+ return TABLE_PAIR_PREFIX + tableId + POLICY_PAIR_SUFFIX + policyId;
+ }
+
+ /**
+ * @param batchId per-policy batch sequence id ({@code 0}, {@code 1}, …)
+ * @param policyId policy entity id
+ * @return {@code batch:{batch_id};policy:{policy_id}}
+ */
+ public static String forCronBatch(long batchId, long policyId) {
+ return BATCH_PAIR_PREFIX + batchId + POLICY_PAIR_SUFFIX + policyId;
+ }
+
+ /**
+ * @param tableId table entity id
+ * @return {@code table:{table_id}}
+ */
+ public static String forCommitTable(long tableId) {
+ return TABLE_PAIR_PREFIX + tableId;
+ }
+
+ /**
+ * @param instanceId db-scheduler task instance id
+ * @return policy id when {@code policy:{policyId}}
+ */
+ public static Optional<Long> parseExpandPolicy(String instanceId) {
+ return parseSingleValue(instanceId, POLICY_PAIR_PREFIX);
+ }
+
+ /**
+ * @param instanceId db-scheduler task instance id
+ * @return {@code [tableId, policyId]} when {@code table:{tableId};policy:{policyId}}
+ */
+ public static Optional<long[]> parseCronTable(String instanceId) {
+ return parseLeftThenPolicy(instanceId, TABLE_PAIR_PREFIX);
+ }
+
+ /**
+ * @param instanceId db-scheduler task instance id
+ * @return {@code [batchId, policyId]} when {@code batch:{batchId};policy:{policyId}}
+ */
+ public static Optional<long[]> parseCronBatch(String instanceId) {
+ return parseLeftThenPolicy(instanceId, BATCH_PAIR_PREFIX);
+ }
+
+ /**
+ * @param instanceId db-scheduler task instance id
+ * @return table id when {@code table:{tableId}} (no {@link #PAIR_SEP})
+ */
+ public static Optional<Long> parseCommitTable(String instanceId) {
+ return parseSingleValue(instanceId, TABLE_PAIR_PREFIX);
+ }
+
+ private static Optional<Long> parseSingleValue(String instanceId, String pairPrefix) {
+ if (instanceId == null || !instanceId.startsWith(pairPrefix)) {
+ return Optional.empty();
+ }
+ String value = instanceId.substring(pairPrefix.length());
+ if (value.isEmpty() || value.indexOf(KV_SEP) >= 0 || value.indexOf(PAIR_SEP) >= 0) {
+ return Optional.empty();
+ }
+ try {
+ return Optional.of(Long.parseLong(value));
+ } catch (NumberFormatException e) {
+ return Optional.empty();
+ }
+ }
+
+ private static Optional<long[]> parseLeftThenPolicy(String instanceId, String leftPairPrefix) {
+ if (instanceId == null || !instanceId.startsWith(leftPairPrefix)) {
+ return Optional.empty();
+ }
+ String rest = instanceId.substring(leftPairPrefix.length());
+ int sep = rest.indexOf(POLICY_PAIR_SUFFIX);
+ if (sep <= 0 || sep + POLICY_PAIR_SUFFIX.length() >= rest.length()) {
+ return Optional.empty();
+ }
+ String leftValue = rest.substring(0, sep);
+ String policyValue = rest.substring(sep + POLICY_PAIR_SUFFIX.length());
+ if (leftValue.indexOf(KV_SEP) >= 0
+ || leftValue.indexOf(PAIR_SEP) >= 0
+ || policyValue.indexOf(KV_SEP) >= 0
+ || policyValue.indexOf(PAIR_SEP) >= 0) {
+ return Optional.empty();
+ }
+ try {
+ return Optional.of(new long[] {Long.parseLong(leftValue), Long.parseLong(policyValue)});
+ } catch (NumberFormatException e) {
+ return Optional.empty();
+ }
+ }
+}
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/TableMaintenanceSchedulerPools.java
index 1714706e82..0468cdc09e 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/TableMaintenanceSchedulerPools.java
@@ -38,11 +38,11 @@ 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.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.job.cron.RelationalCronJobScheduler;
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;
@@ -125,7 +125,7 @@ public class TableMaintenanceSchedulerPools implements AutoCloseable {
PolicyExpandPipeline pipeline =
new PolicyExpandPipeline(
new NearestPolicyTableEnumerator(),
- new RelationalCronJobScheduler(dataSource, gravitinoConfig),
+ new CronJobClient(dataSource, gravitinoConfig),
expandGate,
gravitinoConfig,
config.expandEnqueueBatchSize());
@@ -224,8 +224,13 @@ public class TableMaintenanceSchedulerPools implements AutoCloseable {
return Tasks.custom(POLICY_EXPAND, Void.class)
.execute(
(taskInstance, executionContext) -> {
- long policyId = Long.parseLong(taskInstance.getId());
- Optional<Instant> nextDue = EXPAND_PIPELINE.get().get().expand(policyId);
+ Optional<Long> policyId = MaintenanceTaskIds.parseExpandPolicy(taskInstance.getId());
+ if (policyId.isEmpty()) {
+ LOG.warn(
+ "Removing policy-expand with unparseable instance id {}", taskInstance.getId());
+ return (executionComplete, executionOperations) -> executionOperations.remove();
+ }
+ Optional<Instant> nextDue = EXPAND_PIPELINE.get().get().expand(policyId.get());
return (executionComplete, executionOperations) -> {
if (nextDue.isEmpty()) {
executionOperations.remove();
diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/RelationalCommitJobScheduler.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobClient.java
similarity index 80%
rename from plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/RelationalCommitJobScheduler.java
rename to plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobClient.java
index cbe8b5c6ad..c05c532def 100644
--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/RelationalCommitJobScheduler.java
+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobClient.java
@@ -38,6 +38,7 @@ 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.MaintenanceTaskIds;
import org.apache.gravitino.maintenance.scheduler.TableMaintenanceSchedulerPools;
import org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService;
import org.apache.gravitino.policy.ExecutablePolicyContent;
@@ -46,16 +47,17 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * Schedules {@code commit-job} rows through a db-scheduler {@link SchedulerClient} on the
- * entity-store DataSource.
+ * Enqueues one-shot {@code commit-job} rows through a db-scheduler {@link SchedulerClient} on the
+ * entity-store DataSource (§5.2.3).
*
- * <p>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>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.
*/
-public final class RelationalCommitJobScheduler implements CommitJobScheduler {
+public class CommitJobClient {
- private static final Logger LOG = LoggerFactory.getLogger(RelationalCommitJobScheduler.class);
+ private static final Logger LOG = LoggerFactory.getLogger(CommitJobClient.class);
private final DataSource dataSource;
private final Config gravitinoConfig;
@@ -67,7 +69,7 @@ public final class RelationalCommitJobScheduler implements CommitJobScheduler {
* @param dataSource relational JDBC pool shared with the entity store
* @param gravitinoConfig server config for auth overlay and minInterval fallbacks
*/
- public RelationalCommitJobScheduler(DataSource dataSource, Config gravitinoConfig) {
+ public CommitJobClient(DataSource dataSource, Config gravitinoConfig) {
this(
dataSource,
gravitinoConfig,
@@ -87,7 +89,7 @@ public final class RelationalCommitJobScheduler implements CommitJobScheduler {
* @param occupancyGate cooldown / in-flight checks for enqueue gating
*/
@VisibleForTesting
- public RelationalCommitJobScheduler(
+ public CommitJobClient(
DataSource dataSource,
Config gravitinoConfig,
Function<Long, Optional<CollectedCommitChain>> chainCollector,
@@ -99,36 +101,43 @@ public final class RelationalCommitJobScheduler implements CommitJobScheduler {
this.specFactory = new CommitJobSpecFactory(gravitinoConfig);
}
- @Override
- public CommitJobUpsertResult upsertDueNow(long tableId) {
+ /**
+ * 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 = client(dataSource);
- String id = Long.toString(tableId);
+ 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 CommitJobUpsertResult.ALREADY_QUEUED;
+ return CommitJobEnqueueResult.ALREADY_QUEUED;
}
Optional<MaintenanceJobSpec> spec = buildSpec(tableId);
if (spec.isEmpty()) {
- return CommitJobUpsertResult.SKIPPED;
+ return CommitJobEnqueueResult.SKIPPED;
}
boolean inserted =
client.scheduleIfNotExists(
new TaskInstance<>(TableMaintenanceSchedulerPools.COMMIT_JOB, id, spec.get()),
Instant.now());
- return inserted ? CommitJobUpsertResult.INSERTED : CommitJobUpsertResult.ALREADY_QUEUED;
+ return inserted ? CommitJobEnqueueResult.INSERTED : CommitJobEnqueueResult.ALREADY_QUEUED;
}
/**
- * Builds a SchedulerClient that can commit against the entity-store DataSource.
+ * 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}
*/
@VisibleForTesting
- public static SchedulerClient client(DataSource dataSource) {
+ public static SchedulerClient schedulerClient(DataSource dataSource) {
return SchedulerClient.Builder.create(
AutocommitDataSources.wrap(dataSource), TableMaintenanceSchedulerPools.commitJobTask())
.serializer(new JacksonSerializer(JsonUtils.anyFieldMapper()))
@@ -148,7 +157,7 @@ public final class RelationalCommitJobScheduler implements CommitJobScheduler {
}
long nowMs = System.currentTimeMillis();
- List<CommitChainMember> chain = filterDueToMinInterval(tableId, members, nowMs);
+ List<CommitChainMember> chain = filterByMinInterval(tableId, members, nowMs);
if (chain.isEmpty()) {
LOG.debug(
"Skipping commit-job enqueue for table {}: all onCommit types within minIntervalMs",
@@ -174,7 +183,7 @@ public final class RelationalCommitJobScheduler implements CommitJobScheduler {
}
}
- private List<CommitChainMember> filterDueToMinInterval(
+ private List<CommitChainMember> filterByMinInterval(
long tableId, List<CommitChainMember> collected, long nowMs) {
List<CommitChainMember> due = new ArrayList<>();
for (CommitChainMember member : collected) {
diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobUpsertResult.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobEnqueueResult.java
similarity index 87%
rename from plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobUpsertResult.java
rename to plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobEnqueueResult.java
index 3370c88eac..71ad00a569 100644
--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobUpsertResult.java
+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobEnqueueResult.java
@@ -19,14 +19,14 @@
package org.apache.gravitino.maintenance.scheduler.job.commit;
/**
- * Outcome of {@link CommitJobScheduler#upsertDueNow(long)}.
+ * 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 CommitJobUpsertResult {
+public enum CommitJobEnqueueResult {
- /** A new due-now {@code commit-job} row was inserted with a MaintenanceJobSpec. */
+ /** 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). */
diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobScheduler.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobScheduler.java
deleted file mode 100644
index 7d1d564c56..0000000000
--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/commit/CommitJobScheduler.java
+++ /dev/null
@@ -1,39 +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;
-
-/**
- * Upserts one-shot {@code commit-job} rows for IRC table updates (§5.2.3).
- *
- * <p>Instance id is {@code {table_id}}; bursts of commits on the same table coalesce via {@code
- * scheduleIfNotExists}. Enqueue builds a {@link
- * org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec} when at least one onCommit type is
- * due; an existing row's {@code task_data} is left untouched.
- */
-public interface CommitJobScheduler {
-
- /**
- * Builds an enqueue-time spec (chain + jobConf) and schedules a due-now {@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
- */
- CommitJobUpsertResult upsertDueNow(long tableId);
-}
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.java
index 42136cc14d..1675579dad 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
@@ -28,6 +28,7 @@ import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;
import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.Operation;
import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.TableTarget;
import org.apache.gravitino.maintenance.scheduler.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;
@@ -42,8 +43,8 @@ import org.slf4j.LoggerFactory;
* runJob} → bind the same job id on every claim.
*
* <p>Chain collection, cooldown filtering, auth consistency, and jobConf merge happen at enqueue
- * (see {@link RelationalCommitJobScheduler}). The caller always deletes the one-shot {@code
- * commit-job} row after this method returns.
+ * (see {@link CommitJobClient}). The caller always deletes the one-shot {@code commit-job} row
+ * after this method returns.
*/
public final class MaintenanceCommitSubmitPipeline {
@@ -77,19 +78,18 @@ public final class MaintenanceCommitSubmitPipeline {
}
/**
- * Runs one commit-job pick for {@code instanceId} ({@code {table_id}}).
+ * 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
*/
public void submit(String instanceId, @Nullable MaintenanceJobSpec spec) {
- long tableId;
- try {
- tableId = Long.parseLong(instanceId);
- } catch (NumberFormatException e) {
+ Optional<Long> parsed = MaintenanceTaskIds.parseCommitTable(instanceId);
+ if (parsed.isEmpty()) {
LOG.warn("Skipping commit-job submit for unparseable instance id {}", instanceId);
return;
}
+ long tableId = parsed.get();
if (tableId <= 0) {
LOG.warn("Skipping commit-job submit for non-positive table id {}", instanceId);
return;
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.java
new file mode 100644
index 0000000000..db78566ed9
--- /dev/null
+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/CronJobClient.java
@@ -0,0 +1,692 @@
+/*
+ * 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.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.scheduler.AutocommitDataSources;
+import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;
+import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.TableTarget;
+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.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.
+ *
+ * <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()}.
+ */
+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;
+
+ /**
+ * @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);
+ }
+
+ /**
+ * Visible for tests that inject table-id resolution without a JDBC catalog store.
+ *
+ * @param dataSource relational JDBC pool
+ * @param gravitinoConfig server config
+ * @param tableRefResolver resolves entity ids to catalog + schema.table
+ */
+ @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);
+ }
+
+ /**
+ * 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)
+ */
+ 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;
+ }
+
+ /**
+ * 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}
+ */
+ 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;
+ }
+
+ /**
+ * 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, TableTarget> byId = new LinkedHashMap<>();
+ for (TableTarget target : open.spec.getTables()) {
+ byId.put(target.getTableId(), target);
+ }
+ if (byId.size() + extraTableIds.stream().filter(id -> !byId.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;
+ }
+ String metalake = open.spec.metalake();
+ if (metalake == null) {
+ LOG.warn(
+ "Could not merge tables into cron-job {}: missing metalake on open spec",
+ open.instanceId.getId());
+ return false;
+ }
+ 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 (!byId.containsKey(ref.tableId())) {
+ byId.put(ref.tableId(), MaintenanceJobSpecFactory.toTarget(metalake, ref));
+ added = true;
+ }
+ }
+ if (!added) {
+ return true;
+ }
+ if (byId.size() > batchCapacity) {
+ return false;
+ }
+ MaintenanceJobSpec merged =
+ new MaintenanceJobSpec(
+ new ArrayList<>(byId.values()), open.spec.getOperations(), open.spec.getJobConf());
+ 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.getTables().isEmpty() ? null : data.getTables().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.getOperations().stream().anyMatch(op -> expireType.equals(op.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.
+ */
+ 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;
+ }
+ }
+}
diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/CronJobIds.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/CronJobIds.java
deleted file mode 100644
index bc976e0920..0000000000
--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/CronJobIds.java
+++ /dev/null
@@ -1,206 +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.Objects;
-import java.util.Optional;
-import javax.annotation.Nullable;
-
-/**
- * Builds and parses db-scheduler instance ids for one-shot {@code cron-job} rows (§5.2.2).
- *
- * <p>Most types use {@code table:{table_id}:{policy_id}}. Batched snapshot-expiry uses {@code
- * batch:{batch_id}:{policy_id}} where {@code batch_id} is a per-policy sequence ({@code 0}, {@code
- * 1}, …) so concurrent batch names stay distinct under one {@code policy_id}.
- */
-public final class CronJobIds {
-
- private static final String TABLE_PREFIX = "table:";
- private static final String BATCH_PREFIX = "batch:";
-
- private CronJobIds() {}
-
- /**
- * @param tableId table entity id
- * @param policyId policy entity id
- * @return cron-job instance id
- */
- public static String forTable(long tableId, long policyId) {
- return TABLE_PREFIX + tableId + ":" + policyId;
- }
-
- /**
- * @param batchId per-policy batch sequence id ({@code 0}, {@code 1}, …)
- * @param policyId policy entity id
- * @return cron-job instance id {@code batch:{batch_id}:{policy_id}}
- */
- public static String forBatch(long batchId, long policyId) {
- return BATCH_PREFIX + batchId + ":" + policyId;
- }
-
- /**
- * Parses a single-table cron-job instance id.
- *
- * @param instanceId db-scheduler task instance id
- * @return table and policy ids when the id matches {@code table:{tableId}:{policyId}}
- */
- public static Optional<TablePolicyIds> parseTable(String instanceId) {
- if (instanceId == null || !instanceId.startsWith(TABLE_PREFIX)) {
- return Optional.empty();
- }
- String rest = instanceId.substring(TABLE_PREFIX.length());
- int sep = rest.indexOf(':');
- if (sep <= 0 || sep == rest.length() - 1) {
- return Optional.empty();
- }
- try {
- long tableId = Long.parseLong(rest.substring(0, sep));
- long policyId = Long.parseLong(rest.substring(sep + 1));
- return Optional.of(new TablePolicyIds(tableId, policyId));
- } catch (NumberFormatException e) {
- return Optional.empty();
- }
- }
-
- /**
- * Parses a batched snapshot-expiry cron-job instance id.
- *
- * @param instanceId db-scheduler task instance id
- * @return batch and policy ids when the id matches {@code batch:{batchId}:{policyId}}
- */
- public static Optional<BatchPolicyIds> parseBatch(String instanceId) {
- if (instanceId == null || !instanceId.startsWith(BATCH_PREFIX)) {
- return Optional.empty();
- }
- String rest = instanceId.substring(BATCH_PREFIX.length());
- int sep = rest.indexOf(':');
- if (sep <= 0 || sep == rest.length() - 1) {
- return Optional.empty();
- }
- try {
- long batchId = Long.parseLong(rest.substring(0, sep));
- long policyId = Long.parseLong(rest.substring(sep + 1));
- return Optional.of(new BatchPolicyIds(batchId, policyId));
- } catch (NumberFormatException e) {
- return Optional.empty();
- }
- }
-
- /** Parsed {@code table:{tableId}:{policyId}} ids. */
- public static final class TablePolicyIds {
- private final long tableId;
- private final long policyId;
-
- /**
- * @param tableId table entity id
- * @param policyId policy entity id
- */
- public TablePolicyIds(long tableId, long policyId) {
- this.tableId = tableId;
- this.policyId = policyId;
- }
-
- /**
- * @return table entity id
- */
- public long tableId() {
- return tableId;
- }
-
- /**
- * @return policy entity id
- */
- public long policyId() {
- return policyId;
- }
-
- @Override
- public boolean equals(@Nullable Object o) {
- if (this == o) {
- return true;
- }
- if (!(o instanceof TablePolicyIds)) {
- return false;
- }
- TablePolicyIds that = (TablePolicyIds) o;
- return tableId == that.tableId && policyId == that.policyId;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(tableId, policyId);
- }
-
- @Override
- public String toString() {
- return forTable(tableId, policyId);
- }
- }
-
- /** Parsed {@code batch:{batchId}:{policyId}} ids. */
- public static final class BatchPolicyIds {
- private final long batchId;
- private final long policyId;
-
- /**
- * @param batchId per-policy batch sequence id
- * @param policyId policy entity id
- */
- public BatchPolicyIds(long batchId, long policyId) {
- this.batchId = batchId;
- this.policyId = policyId;
- }
-
- /**
- * @return batch sequence id
- */
- public long batchId() {
- return batchId;
- }
-
- /**
- * @return policy entity id
- */
- public long policyId() {
- return policyId;
- }
-
- @Override
- public boolean equals(@Nullable Object o) {
- if (this == o) {
- return true;
- }
- if (!(o instanceof BatchPolicyIds)) {
- return false;
- }
- BatchPolicyIds that = (BatchPolicyIds) o;
- return batchId == that.batchId && policyId == that.policyId;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(batchId, policyId);
- }
-
- @Override
- public String toString() {
- return forBatch(batchId, policyId);
- }
- }
-}
diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/CronJobScheduler.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/CronJobScheduler.java
deleted file mode 100644
index dfd6b2ca12..0000000000
--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/CronJobScheduler.java
+++ /dev/null
@@ -1,49 +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.List;
-import org.apache.gravitino.maintenance.scheduler.policy.expand.ExpandTableCandidate;
-import org.apache.gravitino.meta.PolicyEntity;
-
-/**
- * Inserts one-shot {@code cron-job} rows into the cron-pool db-scheduler table.
- *
- * <p>Existing instance ids should be 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_id}} rows; incomplete batches are filled via {@code
- * SchedulerClient#getScheduledExecution} / {@code reschedule} before a new {@code batch_id} is
- * allocated (§5.2.2).
- *
- * <p>Enqueue builds a {@link org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec} once
- * (policy → jobConf) into {@code task_data}; pick consumes that spec.
- */
-@FunctionalInterface
-public interface CronJobScheduler {
-
- /**
- * 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 max tables per snapshot-expiry batch row (and max candidates considered)
- * @return number of newly inserted cron-job rows (merges into existing batches do not count)
- */
- int enqueueDueNow(PolicyEntity policy, List<ExpandTableCandidate> candidates, int batchCapacity);
-}
diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceSparkSubmitPipeline.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceSparkSubmitPipeline.java
index fd1a790ab9..b4f960f8f4 100644
--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceSparkSubmitPipeline.java
+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/MaintenanceSparkSubmitPipeline.java
@@ -26,6 +26,7 @@ import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;
import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.Operation;
import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.TableTarget;
import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpecFactory;
+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.slf4j.Logger;
@@ -86,8 +87,8 @@ public final class MaintenanceSparkSubmitPipeline {
return;
}
- Optional<CronJobIds.TablePolicyIds> tableIds = CronJobIds.parseTable(instanceId);
- Optional<CronJobIds.BatchPolicyIds> batchIds = CronJobIds.parseBatch(instanceId);
+ Optional<long[]> tableIds = MaintenanceTaskIds.parseCronTable(instanceId);
+ Optional<long[]> batchIds = MaintenanceTaskIds.parseCronBatch(instanceId);
if (tableIds.isEmpty() && batchIds.isEmpty()) {
LOG.warn("Skipping cron-job submit for unparseable instance id {}", instanceId);
return;
@@ -95,8 +96,8 @@ public final class MaintenanceSparkSubmitPipeline {
Operation step = spec.getOperations().get(0);
long policyId = step.getPolicyId();
- long expectedPolicyId =
- tableIds.isPresent() ? tableIds.get().policyId() : batchIds.get().policyId();
+ // 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 {}",
@@ -106,7 +107,7 @@ public final class MaintenanceSparkSubmitPipeline {
return;
}
if (tableIds.isPresent()) {
- long expectedTableId = tableIds.get().tableId();
+ long expectedTableId = tableIds.get()[0];
if (spec.getTables().size() != 1 || spec.getTables().get(0).getTableId() != expectedTableId) {
LOG.warn(
"Skipping cron-job submit for {}: spec tables {} do not match instance tableId {}",
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.java
index cb9fd6a65a..27923359c5 100644
--- 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.java
@@ -45,7 +45,7 @@ public final class PendingCronExpandOccupancyGate implements ExpandOccupancyGate
if (delegate.shouldSkip(tableId, policyId, minIntervalMs, nowMs)) {
return true;
}
- return RelationalCronJobScheduler.isQueuedForPolicy(
- RelationalCronJobScheduler.client(dataSource), tableId, policyId);
+ return CronJobClient.isTableAlreadyQueued(
+ CronJobClient.schedulerClient(dataSource), tableId, policyId);
}
}
diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/RelationalCronJobScheduler.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/RelationalCronJobScheduler.java
deleted file mode 100644
index 538724e47e..0000000000
--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/cron/RelationalCronJobScheduler.java
+++ /dev/null
@@ -1,427 +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.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.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-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.scheduler.AutocommitDataSources;
-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;
-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.TableTarget;
-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpecFactory;
-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.PolicyEntity;
-import org.apache.gravitino.policy.Policy;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Schedules {@code cron-job} rows through a db-scheduler {@link SchedulerClient} on the
- * entity-store DataSource.
- *
- * <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 (same due time, new table list + shared jobConf).
- *
- * <p>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()}.
- */
-public final class RelationalCronJobScheduler implements CronJobScheduler {
-
- private static final Logger LOG = LoggerFactory.getLogger(RelationalCronJobScheduler.class);
-
- private final DataSource dataSource;
- private final MaintenanceJobSpecFactory specFactory;
- private final Function<List<Long>, List<ResolvedTableRef>> tableRefResolver;
-
- /**
- * @param dataSource relational JDBC pool shared with the entity store
- * @param gravitinoConfig server config for jobConf overlay
- */
- public RelationalCronJobScheduler(DataSource dataSource, Config gravitinoConfig) {
- this(dataSource, gravitinoConfig, MaintenanceTableRefs::resolve);
- }
-
- /**
- * Visible for tests that inject table-id resolution without a JDBC catalog store.
- *
- * @param dataSource relational JDBC pool
- * @param gravitinoConfig server config
- * @param tableRefResolver resolves entity ids to catalog + schema.table
- */
- RelationalCronJobScheduler(
- 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);
- }
-
- @Override
- public int enqueueDueNow(
- 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 capacity = Math.max(1, batchCapacity);
- SchedulerClient client = client(dataSource);
- Instant due = Instant.now();
-
- if (policy.policyType() == Policy.BuiltInType.ICEBERG_SNAPSHOT_EXPIRATION) {
- return enqueueSnapshotExpiry(client, policy, candidates, capacity, due);
- }
- int scheduled = 0;
- int limit = Math.min(candidates.size(), capacity);
- for (ExpandTableCandidate candidate : candidates.subList(0, limit)) {
- if (scheduleTable(client, policy, candidate.tableId(), due)) {
- scheduled++;
- }
- }
- return scheduled;
- }
-
- /**
- * Builds a SchedulerClient that can commit against the entity-store DataSource.
- *
- * @param dataSource entity-store pool
- * @return client bound to {@link TableMaintenanceSchedulerPools#CRON_TASKS_TABLE}
- */
- @VisibleForTesting
- public static SchedulerClient client(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<>();
- int scheduled = 0;
- for (ExpandTableCandidate candidate : slice) {
- if (candidate.batchableForSnapshotExpiry()) {
- if (!isQueuedForPolicy(client, candidate.tableId(), policy.id())) {
- batchable.add(candidate.tableId());
- }
- } else if (scheduleTable(client, policy, candidate.tableId(), due)) {
- scheduled++;
- }
- }
- scheduled += packIntoBatches(client, policy, batchable, batchCapacity, due);
- return scheduled;
- }
-
- private int packIntoBatches(
- SchedulerClient client,
- PolicyEntity policy,
- List<Long> tableIds,
- int batchCapacity,
- Instant due) {
- if (tableIds.isEmpty()) {
- return 0;
- }
- // Same-catalog batches only: mixed catalogs would reuse wrong spark.sql.catalog.* props.
- Map<String, List<Long>> byCatalog = groupByCatalog(tableIds);
- int newRows = 0;
- for (Map.Entry<String, List<Long>> entry : byCatalog.entrySet()) {
- newRows +=
- packSameCatalog(client, policy, entry.getKey(), entry.getValue(), batchCapacity, due);
- }
- return newRows;
- }
-
- 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 packing", tableId);
- continue;
- }
- byCatalog.computeIfAbsent(ref.catalogName(), ignored -> new ArrayList<>()).add(tableId);
- }
- return byCatalog;
- }
-
- private int packSameCatalog(
- 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<OpenBatch> incomplete =
- findIncompleteBatch(client, policy.id(), batchCapacity, catalogName);
- if (incomplete.isPresent()) {
- OpenBatch open = incomplete.get();
- int room = batchCapacity - open.spec.tableIds().size();
- List<Long> chunk = new ArrayList<>(remaining.subList(0, Math.min(room, remaining.size())));
- if (mergeIntoBatch(client, open, chunk)) {
- remaining.subList(0, chunk.size()).clear();
- continue;
- }
- }
- int end = Math.min(batchCapacity, remaining.size());
- List<Long> chunk = new ArrayList<>(remaining.subList(0, end));
- if (scheduleBatch(client, policy, chunk, due)) {
- newRows++;
- remaining.subList(0, end).clear();
- continue;
- }
- // Fail-closed: do not drop a whole multi-table chunk on build failure — peel one id.
- Long first = remaining.remove(0);
- if (chunk.size() > 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;
- }
-
- 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 = CronJobIds.forTable(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 = CronJobIds.forBatch(batchId, policy.id());
- return client.scheduleIfNotExists(
- new TaskInstance<>(TableMaintenanceSchedulerPools.CRON_JOB, id, spec.get()), due);
- }
-
- private boolean mergeIntoBatch(SchedulerClient client, OpenBatch open, List<Long> extraTableIds) {
- Map<Long, TableTarget> byId = new LinkedHashMap<>();
- for (TableTarget target : open.spec.getTables()) {
- byId.put(target.getTableId(), target);
- }
- String openCatalog = open.spec.getTables().get(0).catalogName();
- if (openCatalog == null || openCatalog.isEmpty()) {
- LOG.warn(
- "Could not merge tables into cron-job {}: open batch missing catalog name",
- open.instanceId.getId());
- return false;
- }
- List<ResolvedTableRef> resolved = tableRefResolver.apply(extraTableIds);
- // Require every requested id so packIntoBatches does not drop unresolved tables from
- // remaining after a partial merge.
- 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;
- }
- String metalake = open.spec.metalake();
- if (metalake == null) {
- LOG.warn(
- "Could not merge tables into cron-job {}: missing metalake on open spec",
- open.instanceId.getId());
- return false;
- }
- boolean added = false;
- for (ResolvedTableRef ref : resolved) {
- if (!openCatalog.equals(ref.catalogName())) {
- LOG.warn(
- "Could not merge table {} into cron-job {}: catalog {} != open batch catalog {}",
- ref.tableId(),
- open.instanceId.getId(),
- ref.catalogName(),
- openCatalog);
- return false;
- }
- if (!byId.containsKey(ref.tableId())) {
- byId.put(ref.tableId(), MaintenanceJobSpecFactory.toTarget(metalake, ref));
- added = true;
- }
- }
- if (!added) {
- return true;
- }
- MaintenanceJobSpec merged =
- new MaintenanceJobSpec(
- new ArrayList<>(byId.values()), open.spec.getOperations(), open.spec.getJobConf());
- 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 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<OpenBatch> findIncompleteBatch(
- SchedulerClient client, long policyId, int batchCapacity, String catalogName) {
- return listOpenBatches(client, policyId).stream()
- .filter(b -> !b.picked && b.spec.tableIds().size() < batchCapacity)
- .filter(b -> catalogName.equals(b.spec.getTables().get(0).catalogName()))
- .min(Comparator.comparingLong(b -> b.batchId));
- }
-
- private static List<OpenBatch> listOpenBatches(SchedulerClient client, long policyId) {
- List<OpenBatch> open = new ArrayList<>();
- for (ScheduledExecution<MaintenanceJobSpec> execution :
- client.getScheduledExecutionsForTask(
- TableMaintenanceSchedulerPools.CRON_JOB, MaintenanceJobSpec.class)) {
- Optional<CronJobIds.BatchPolicyIds> parsed =
- CronJobIds.parseBatch(execution.getTaskInstance().getId());
- if (parsed.isEmpty() || parsed.get().policyId() != policyId) {
- continue;
- }
- MaintenanceJobSpec data = execution.getData();
- if (data == null || !data.isValid()) {
- continue;
- }
- open.add(
- new OpenBatch(
- TaskInstanceId.of(
- TableMaintenanceSchedulerPools.CRON_JOB, execution.getTaskInstance().getId()),
- parsed.get().batchId(),
- execution.getExecutionTime(),
- data,
- execution.isPicked()));
- }
- return open;
- }
-
- static long nextBatchId(SchedulerClient client, long policyId) {
- long max = -1L;
- for (OpenBatch batch : listOpenBatches(client, policyId)) {
- max = Math.max(max, batch.batchId);
- }
- return max + 1L;
- }
-
- /** True when a table already has a queued {@code table:} or {@code batch:} cron-job. */
- static boolean isQueuedForPolicy(SchedulerClient client, long tableId, long policyId) {
- if (client
- .getScheduledExecution(
- TaskInstanceId.of(
- TableMaintenanceSchedulerPools.CRON_JOB, CronJobIds.forTable(tableId, policyId)))
- .isPresent()) {
- return true;
- }
- for (OpenBatch batch : listOpenBatches(client, policyId)) {
- if (batch.spec.tableIds().contains(tableId)) {
- return true;
- }
- }
- return false;
- }
-
- private static final class OpenBatch {
- private final TaskInstanceId instanceId;
- private final long batchId;
- private final Instant executionTime;
- private final MaintenanceJobSpec spec;
- private final boolean picked;
-
- private OpenBatch(
- TaskInstanceId instanceId,
- long batchId,
- Instant executionTime,
- MaintenanceJobSpec spec,
- boolean picked) {
- this.instanceId = instanceId;
- this.batchId = batchId;
- this.executionTime = executionTime;
- this.spec = spec;
- this.picked = picked;
- }
- }
-}
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.java
index bc879a71ac..dfe57ac7d0 100644
--- 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.java
@@ -27,7 +27,7 @@ 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.CronJobScheduler;
+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;
@@ -52,7 +52,7 @@ public final class PolicyExpandPipeline {
private final Function<Long, Optional<PolicyEntity>> policyLoader;
private final PolicyTableEnumerator tableEnumerator;
- private final CronJobScheduler cronJobScheduler;
+ private final CronJobClient cronJobClient;
private final ExpandOccupancyGate occupancyGate;
private final Config config;
private final int enqueueBatchSize;
@@ -61,21 +61,21 @@ public final class PolicyExpandPipeline {
* Loads policies through {@link PolicyMetaService}.
*
* @param tableEnumerator lists attached table ids
- * @param cronJobScheduler writes cron-job rows
+ * @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,
- CronJobScheduler cronJobScheduler,
+ CronJobClient cronJobClient,
ExpandOccupancyGate occupancyGate,
Config config,
int enqueueBatchSize) {
this(
PolicyExpandPipeline::loadPolicy,
tableEnumerator,
- cronJobScheduler,
+ cronJobClient,
occupancyGate,
config,
enqueueBatchSize);
@@ -84,7 +84,7 @@ public final class PolicyExpandPipeline {
/**
* @param policyLoader loads the policy for the expand instance id
* @param tableEnumerator lists attached table ids
- * @param cronJobScheduler writes cron-job rows
+ * @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
@@ -92,13 +92,13 @@ public final class PolicyExpandPipeline {
PolicyExpandPipeline(
Function<Long, Optional<PolicyEntity>> policyLoader,
PolicyTableEnumerator tableEnumerator,
- CronJobScheduler cronJobScheduler,
+ CronJobClient cronJobClient,
ExpandOccupancyGate occupancyGate,
Config config,
int enqueueBatchSize) {
this.policyLoader = Preconditions.checkNotNull(policyLoader);
this.tableEnumerator = tableEnumerator;
- this.cronJobScheduler = cronJobScheduler;
+ this.cronJobClient = cronJobClient;
this.occupancyGate = occupancyGate;
this.config = config;
this.enqueueBatchSize = enqueueBatchSize;
@@ -149,7 +149,7 @@ public final class PolicyExpandPipeline {
config, policy.policyType(), policyMinIntervalMs(policy.content()));
List<ExpandTableCandidate> toEnqueue =
tableEnumerator.listTableIds(policy, enqueueBatchSize, occupancyGate, minIntervalMs);
- int scheduled = cronJobScheduler.enqueueDueNow(policy, toEnqueue, enqueueBatchSize);
+ int scheduled = cronJobClient.enqueueNow(policy, toEnqueue, enqueueBatchSize);
LOG.info(
"Expanded policy {}: scheduled {} cron-job rows for {} tables (type={}, minIntervalMs={}); next expand due {}",
policyId,
diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/integration/test/IrcToCommitEnqueueIT.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/integration/test/IrcToCommitEnqueueIT.java
index 3eb15ac84d..cacc011b41 100644
--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/integration/test/IrcToCommitEnqueueIT.java
+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/integration/test/IrcToCommitEnqueueIT.java
@@ -48,6 +48,7 @@ import org.apache.gravitino.maintenance.integration.test.MaintenanceSchedulerITS
import org.apache.gravitino.maintenance.listener.PostCommitMaintenanceListener;
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.SchedulerPoolTestHooks;
import org.apache.gravitino.maintenance.web.rest.feature.TableMaintenanceRESTFeature;
import org.apache.iceberg.PartitionSpec;
@@ -131,7 +132,7 @@ public class IrcToCommitEnqueueIT extends BaseIT {
NameIdentifier.of(metalake, seeded.catalogName, seeded.schemaName, seeded.tableName);
GravitinoEnv.getInstance().eventBus().dispatchEvent(icebergUpdateTableEvent(tableId));
- awaitCommitCapture(Long.toString(seeded.tableId), 30L);
+ awaitCommitCapture(MaintenanceTaskIds.forCommitTable(seeded.tableId), 30L);
MaintenanceJobSpec spec = CAPTURED_COMMIT_SPEC.get();
assertNotNull(spec);
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.java
index e2700be835..5aef4eaa81 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
@@ -41,8 +41,8 @@ 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.job.cron.CronJobIds;
import org.apache.gravitino.maintenance.scheduler.policy.expand.ExpandTableCandidate;
import org.apache.gravitino.maintenance.scheduler.policy.expand.NearestPolicyTableEnumerator;
import org.apache.gravitino.maintenance.web.rest.feature.TableMaintenanceRESTFeature;
@@ -125,7 +125,7 @@ public class PolicyExpandToCronIT extends BaseIT {
// tomorrow 02:00 for TIME_TRIGGER).
PolicyExpandRegistrar.forReads(ds).scheduleAt(seeded.policyId, Instant.now().minusSeconds(5));
- awaitCronCapture(CronJobIds.forTable(seeded.tableId, seeded.policyId), 30L);
+ awaitCronCapture(MaintenanceTaskIds.forCronTable(seeded.tableId, seeded.policyId), 30L);
MaintenanceJobSpec spec = CAPTURED_CRON_SPEC.get();
assertNotNull(spec);
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.java
index e635ce66f7..496e9a0182 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
@@ -30,8 +30,8 @@ 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.CommitJobScheduler;
-import org.apache.gravitino.maintenance.scheduler.job.commit.CommitJobUpsertResult;
+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;
@@ -50,20 +50,20 @@ class TestPostCommitMaintenanceListener {
@Test
void testIgnoresUnrelatedEvents() {
PostCommitMaintenanceListener listener = new PostCommitMaintenanceListener();
- CommitJobScheduler scheduler = mock(CommitJobScheduler.class);
- listener.setCommitJobScheduler(scheduler);
+ CommitJobClient scheduler = mock(CommitJobClient.class);
+ listener.setCommitJobClient(scheduler);
listener.onPostEvent(new OtherEvent("u", NameIdentifier.of("ml", "c", "s", "t")));
- verify(scheduler, never()).upsertDueNow(anyLong());
+ verify(scheduler, never()).enqueueNow(anyLong());
}
@Test
void testEnqueueUpsertsCommitJob() {
PostCommitMaintenanceListener listener = new PostCommitMaintenanceListener();
- CommitJobScheduler scheduler = mock(CommitJobScheduler.class);
- when(scheduler.upsertDueNow(eq(42L))).thenReturn(CommitJobUpsertResult.INSERTED);
- listener.setCommitJobScheduler(scheduler);
+ CommitJobClient scheduler = mock(CommitJobClient.class);
+ when(scheduler.enqueueNow(eq(42L))).thenReturn(CommitJobEnqueueResult.INSERTED);
+ listener.setCommitJobClient(scheduler);
listener.setTableLookup(
ident ->
TableEntity.builder()
@@ -76,7 +76,7 @@ class TestPostCommitMaintenanceListener {
listener.enqueueCommitJob(NameIdentifier.of("ml", "c", "s", "t"));
- verify(scheduler).upsertDueNow(42L);
+ verify(scheduler).enqueueNow(42L);
}
@Test
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.java
index a2931aafe1..a3018ae46f 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
@@ -207,7 +207,7 @@ class TestPolicyExpandReconciler extends TestJDBCBackend {
ExecutionOperations<Void> operations = Mockito.mock(ExecutionOperations.class);
ExecutionComplete complete = ExecutionComplete.simulatedSuccess(Instant.now());
- PolicyExpandLifecycleHook.completePick(Long.toString(policy.id()), complete, operations);
+ PolicyExpandLifecycleHook.completePick("policy:" + policy.id(), complete, operations);
Mockito.verify(operations)
.reschedule(Mockito.eq(complete), Mockito.argThat(due -> due.isAfter(Instant.now())));
@@ -218,7 +218,7 @@ class TestPolicyExpandReconciler extends TestJDBCBackend {
void testCompletePickRemovesMissingPolicy() {
ExecutionOperations<Void> operations = Mockito.mock(ExecutionOperations.class);
ExecutionComplete complete = ExecutionComplete.simulatedSuccess(Instant.now());
- PolicyExpandLifecycleHook.completePick("424242", complete, operations);
+ PolicyExpandLifecycleHook.completePick("policy:424242", complete, operations);
Mockito.verify(operations).remove();
}
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.java
index 3bcc0e41b9..b3d6fc10ae 100644
--- 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.java
@@ -106,7 +106,7 @@ class TestPolicyExpandRegistrar extends TestJDBCBackend {
.tableName(TableMaintenanceSchedulerPools.EXPAND_TASKS_TABLE)
.build();
TaskInstanceId instanceId =
- TaskInstanceId.of(TableMaintenanceSchedulerPools.POLICY_EXPAND, "11");
+ TaskInstanceId.of(TableMaintenanceSchedulerPools.POLICY_EXPAND, "policy:11");
Assertions.assertTrue(client.getScheduledExecution(instanceId).isPresent());
TableMaintenanceSchedulerPools pools = new TableMaintenanceSchedulerPools();
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.java
new file mode 100644
index 0000000000..a98ddaaeb4
--- /dev/null
+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/TestMaintenanceTaskIds.java
@@ -0,0 +1,92 @@
+/*
+ * 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 java.util.Optional;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class TestMaintenanceTaskIds {
+
+ @Test
+ void testSeparators() {
+ 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());
+ }
+
+ @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());
+ }
+
+ @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());
+ Assertions.assertTrue(MaintenanceTaskIds.parseExpandPolicy("policy:a").isEmpty());
+ Assertions.assertTrue(MaintenanceTaskIds.parseExpandPolicy("policy:1:2").isEmpty());
+ Assertions.assertTrue(MaintenanceTaskIds.parseExpandPolicy("table:1").isEmpty());
+
+ Assertions.assertTrue(MaintenanceTaskIds.parseCronTable(null).isEmpty());
+ Assertions.assertTrue(MaintenanceTaskIds.parseCronTable("batch:1;policy:2").isEmpty());
+ Assertions.assertTrue(MaintenanceTaskIds.parseCronTable("table:").isEmpty());
+ Assertions.assertTrue(MaintenanceTaskIds.parseCronTable("table:1").isEmpty());
+ Assertions.assertTrue(MaintenanceTaskIds.parseCronTable("table:1:2").isEmpty());
+ Assertions.assertTrue(MaintenanceTaskIds.parseCronTable("table:1:policy:2").isEmpty());
+ Assertions.assertTrue(MaintenanceTaskIds.parseCronTable("table:a;policy:2").isEmpty());
+
+ Assertions.assertTrue(MaintenanceTaskIds.parseCronBatch(null).isEmpty());
+ Assertions.assertTrue(MaintenanceTaskIds.parseCronBatch("table:1;policy:2").isEmpty());
+ Assertions.assertTrue(MaintenanceTaskIds.parseCronBatch("batch:1:2").isEmpty());
+ Assertions.assertTrue(MaintenanceTaskIds.parseCronBatch("batch:pending;policy:9").isEmpty());
+
+ Assertions.assertTrue(MaintenanceTaskIds.parseCommitTable(null).isEmpty());
+ Assertions.assertTrue(MaintenanceTaskIds.parseCommitTable("99").isEmpty());
+ Assertions.assertTrue(MaintenanceTaskIds.parseCommitTable("table:").isEmpty());
+ Assertions.assertTrue(MaintenanceTaskIds.parseCommitTable("table:a").isEmpty());
+ Assertions.assertTrue(MaintenanceTaskIds.parseCommitTable("table:1;policy:2").isEmpty());
+ Assertions.assertTrue(MaintenanceTaskIds.parseCommitTable("policy:1").isEmpty());
+ }
+}
diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestRelationalCommitJobScheduler.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestCommitJobClient.java
similarity index 88%
rename from plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestRelationalCommitJobScheduler.java
rename to plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestCommitJobClient.java
index 6c6797c898..75be3da9b5 100644
--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestRelationalCommitJobScheduler.java
+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/commit/TestCommitJobClient.java
@@ -31,6 +31,7 @@ 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;
@@ -44,7 +45,7 @@ import org.apache.gravitino.utils.NamespaceUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.TestTemplate;
-class TestRelationalCommitJobScheduler extends TestJDBCBackend {
+class TestCommitJobClient extends TestJDBCBackend {
private static final long TABLE_ID = 101L;
private static final long POLICY_ID = 202L;
@@ -52,40 +53,42 @@ class TestRelationalCommitJobScheduler extends TestJDBCBackend {
@TestTemplate
void testEnqueueSkipsWhenAllWithinMinInterval() {
- RelationalCommitJobScheduler scheduler =
- new RelationalCommitJobScheduler(
+ CommitJobClient scheduler =
+ new CommitJobClient(
dataSource(),
configWithUri(),
fixedCollector(List.of(member(POLICY_ID))),
coolingGate(POLICY_ID));
- Assertions.assertEquals(CommitJobUpsertResult.SKIPPED, scheduler.upsertDueNow(TABLE_ID));
+ Assertions.assertEquals(CommitJobEnqueueResult.SKIPPED, scheduler.enqueueNow(TABLE_ID));
Assertions.assertTrue(
- RelationalCommitJobScheduler.client(dataSource())
+ CommitJobClient.schedulerClient(dataSource())
.getScheduledExecution(
TaskInstanceId.of(
- TableMaintenanceSchedulerPools.COMMIT_JOB, Long.toString(TABLE_ID)))
+ TableMaintenanceSchedulerPools.COMMIT_JOB,
+ MaintenanceTaskIds.forCommitTable(TABLE_ID)))
.isEmpty());
}
@TestTemplate
void testEnqueueWritesSpecAndIsIdempotent() {
- RelationalCommitJobScheduler scheduler =
- new RelationalCommitJobScheduler(
+ CommitJobClient scheduler =
+ new CommitJobClient(
dataSource(),
configWithUri(),
fixedCollector(List.of(member(POLICY_ID))),
allowAllGate());
- Assertions.assertEquals(CommitJobUpsertResult.INSERTED, scheduler.upsertDueNow(TABLE_ID));
- Assertions.assertEquals(CommitJobUpsertResult.ALREADY_QUEUED, scheduler.upsertDueNow(TABLE_ID));
+ Assertions.assertEquals(CommitJobEnqueueResult.INSERTED, scheduler.enqueueNow(TABLE_ID));
+ Assertions.assertEquals(CommitJobEnqueueResult.ALREADY_QUEUED, scheduler.enqueueNow(TABLE_ID));
- SchedulerClient client = RelationalCommitJobScheduler.client(dataSource());
+ SchedulerClient client = CommitJobClient.schedulerClient(dataSource());
MaintenanceJobSpec spec =
(MaintenanceJobSpec)
client
.getScheduledExecution(
TaskInstanceId.of(
- TableMaintenanceSchedulerPools.COMMIT_JOB, Long.toString(TABLE_ID)))
+ TableMaintenanceSchedulerPools.COMMIT_JOB,
+ MaintenanceTaskIds.forCommitTable(TABLE_ID)))
.get()
.getData();
Assertions.assertTrue(spec.isValid());
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.java
index b6efefad75..b6b84c123c 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
@@ -38,6 +38,7 @@ import org.apache.gravitino.Config;
import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;
import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.Operation;
import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.TableTarget;
+import org.apache.gravitino.maintenance.scheduler.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;
@@ -66,7 +67,8 @@ class TestMaintenanceCommitSubmitPipeline {
void testNullSpecSkipsSubmit() {
MaintenanceJobSubmitter submitter = mock(MaintenanceJobSubmitter.class);
TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);
- pipeline(allowAllGate(), actions, submitter).submit(Long.toString(TABLE_ID), null);
+ pipeline(allowAllGate(), actions, submitter)
+ .submit(MaintenanceTaskIds.forCommitTable(TABLE_ID), null);
verify(submitter, never()).runJob(anyString(), anyString(), anyMap());
verify(actions, never()).tryAcquireInFlightBatch(anyLong(), anyList(), anyLong());
}
@@ -75,7 +77,8 @@ class TestMaintenanceCommitSubmitPipeline {
void testInFlightRemainingMemberSkipsSubmit() {
MaintenanceJobSubmitter submitter = mock(MaintenanceJobSubmitter.class);
TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);
- pipeline(inFlightGate(POLICY_ID), actions, submitter).submit(Long.toString(TABLE_ID), spec());
+ 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());
}
@@ -103,7 +106,8 @@ class TestMaintenanceCommitSubmitPipeline {
new Operation(EXPIRE_POLICY_ID, "expire_snapshots")),
jobConf);
- pipeline(allowAllGate(), actions, submitter).submit(Long.toString(TABLE_ID), spec);
+ pipeline(allowAllGate(), actions, submitter)
+ .submit(MaintenanceTaskIds.forCommitTable(TABLE_ID), spec);
@SuppressWarnings("unchecked")
ArgumentCaptor<Map<String, String>> confCaptor = ArgumentCaptor.forClass(Map.class);
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.java
new file mode 100644
index 0000000000..6229fd776f
--- /dev/null
+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestCronJobClient.java
@@ -0,0 +1,547 @@
+/*
+ * 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.Scheduler;
+import com.github.kagkarlsson.scheduler.SchedulerClient;
+import com.github.kagkarlsson.scheduler.serializer.JacksonSerializer;
+import com.github.kagkarlsson.scheduler.task.TaskInstanceId;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+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.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.maintenance.scheduler.policy.expand.ExpandTableCandidate;
+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 TestCronJobClient extends TestJDBCBackend {
+
+ private static final String GRAVITINO_URI = "http://localhost:8090";
+
+ @TestTemplate
+ void testEnqueueIsIdempotentAndRespectsBatchSize() {
+ 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));
+ Assertions.assertEquals(
+ 0,
+ scheduler.enqueueNow(
+ policy,
+ List.of(
+ candidate(1L, MetadataObject.Type.TABLE), candidate(2L, MetadataObject.Type.TABLE)),
+ 2));
+
+ SchedulerClient client = CronJobClient.schedulerClient(dataSource);
+ Assertions.assertTrue(
+ client
+ .getScheduledExecution(
+ TaskInstanceId.of(
+ TableMaintenanceSchedulerPools.CRON_JOB,
+ MaintenanceTaskIds.forCronTable(1L, 7L)))
+ .isPresent());
+ Assertions.assertTrue(
+ client
+ .getScheduledExecution(
+ TaskInstanceId.of(
+ TableMaintenanceSchedulerPools.CRON_JOB,
+ MaintenanceTaskIds.forCronTable(2L, 7L)))
+ .isPresent());
+ Assertions.assertTrue(
+ client
+ .getScheduledExecution(
+ TaskInstanceId.of(
+ TableMaintenanceSchedulerPools.CRON_JOB,
+ MaintenanceTaskIds.forCronTable(3L, 7L)))
+ .isEmpty());
+
+ MaintenanceJobSpec spec =
+ (MaintenanceJobSpec)
+ client
+ .getScheduledExecution(
+ TaskInstanceId.of(
+ TableMaintenanceSchedulerPools.CRON_JOB,
+ MaintenanceTaskIds.forCronTable(1L, 7L)))
+ .get()
+ .getData();
+ Assertions.assertTrue(spec.isValid());
+ Assertions.assertTrue(spec.getJobConf().containsKey("updater_options"));
+ Assertions.assertEquals(List.of(1L), spec.tableIds());
+ }
+
+ @TestTemplate
+ void testSnapshotExpiryFillsIncompleteBatchBeforeAllocatingNextId() {
+ DataSource dataSource = dataSource();
+ CronJobClient scheduler = scheduler(dataSource);
+ PolicyEntity policy = expirePolicy(9L);
+
+ Assertions.assertEquals(
+ 1,
+ scheduler.enqueueNow(
+ policy,
+ List.of(
+ candidate(10L, MetadataObject.Type.SCHEMA),
+ candidate(11L, MetadataObject.Type.SCHEMA)),
+ 10));
+
+ Assertions.assertEquals(
+ 0,
+ scheduler.enqueueNow(
+ policy,
+ List.of(
+ candidate(10L, MetadataObject.Type.SCHEMA),
+ candidate(11L, MetadataObject.Type.SCHEMA),
+ candidate(12L, MetadataObject.Type.CATALOG),
+ candidate(13L, MetadataObject.Type.SCHEMA)),
+ 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 =
+ (MaintenanceJobSpec) client.getScheduledExecution(batch0).get().getData();
+ Assertions.assertEquals(List.of(10L, 11L, 12L, 13L), data.tableIds());
+ Assertions.assertEquals(1, data.getOperations().size());
+ Assertions.assertTrue(data.getJobConf().containsKey("updater_options"));
+ }
+
+ @TestTemplate
+ void testSnapshotExpiryAllocatesNextBatchWhenCapacityFull() {
+ DataSource dataSource = dataSource();
+ CronJobClient scheduler = scheduler(dataSource);
+ 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));
+
+ SchedulerClient client = CronJobClient.schedulerClient(dataSource);
+ MaintenanceJobSpec batch0 =
+ (MaintenanceJobSpec)
+ client
+ .getScheduledExecution(
+ TaskInstanceId.of(
+ TableMaintenanceSchedulerPools.CRON_JOB,
+ MaintenanceTaskIds.forCronBatch(0L, 9L)))
+ .get()
+ .getData();
+ MaintenanceJobSpec batch1 =
+ (MaintenanceJobSpec)
+ client
+ .getScheduledExecution(
+ TaskInstanceId.of(
+ TableMaintenanceSchedulerPools.CRON_JOB,
+ MaintenanceTaskIds.forCronBatch(1L, 9L)))
+ .get()
+ .getData();
+ Assertions.assertEquals(cap, batch0.tableIds().size());
+ Assertions.assertEquals(List.of(cap + 1L), batch1.tableIds());
+ }
+
+ @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() {
+ DataSource dataSource = dataSource();
+ CronJobClient scheduler = scheduler(dataSource);
+ PolicyEntity policy = expirePolicy(9L);
+
+ Assertions.assertEquals(
+ 1, scheduler.enqueueNow(policy, List.of(candidate(21L, MetadataObject.Type.TABLE)), 10));
+ Assertions.assertEquals(
+ 1, scheduler.enqueueNow(policy, List.of(candidate(22L, MetadataObject.Type.TABLE)), 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());
+ Assertions.assertTrue(client.getScheduledExecution(batch0).isPresent());
+ MaintenanceJobSpec data =
+ (MaintenanceJobSpec) client.getScheduledExecution(batch0).get().getData();
+ Assertions.assertEquals(List.of(22L, 21L), data.tableIds());
+ }
+
+ @TestTemplate
+ void testSnapshotExpiryTableMergesIntoExistingIncompleteBatch() {
+ DataSource dataSource = dataSource();
+ CronJobClient scheduler = scheduler(dataSource);
+ PolicyEntity policy = expirePolicy(9L);
+
+ Assertions.assertEquals(
+ 1,
+ scheduler.enqueueNow(
+ policy,
+ List.of(
+ candidate(10L, MetadataObject.Type.SCHEMA),
+ candidate(11L, MetadataObject.Type.SCHEMA)),
+ 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));
+
+ 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 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());
+ }
+
+ @TestTemplate
+ void testSnapshotExpiryDoesNotMergeDifferentCatalogs() {
+ DataSource dataSource = dataSource();
+ CronJobClient scheduler = multiCatalogScheduler(dataSource);
+
+ 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));
+
+ SchedulerClient client = CronJobClient.schedulerClient(dataSource);
+ Assertions.assertTrue(
+ client
+ .getScheduledExecution(
+ TaskInstanceId.of(
+ TableMaintenanceSchedulerPools.CRON_JOB,
+ MaintenanceTaskIds.forCronTable(1L, 9L)))
+ .isPresent());
+ Assertions.assertTrue(
+ client
+ .getScheduledExecution(
+ TaskInstanceId.of(
+ TableMaintenanceSchedulerPools.CRON_JOB,
+ MaintenanceTaskIds.forCronTable(1001L, 9L)))
+ .isPresent());
+ }
+
+ @TestTemplate
+ void testSnapshotExpirySkipsPeerWhenMergeWouldExceedCapacity() {
+ DataSource dataSource = dataSource();
+ CronJobClient scheduler = scheduler(dataSource);
+ 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));
+ Assertions.assertEquals(
+ 1,
+ scheduler.enqueueNow(
+ policy,
+ List.of(
+ candidate(100L, MetadataObject.Type.SCHEMA),
+ candidate(101L, MetadataObject.Type.SCHEMA)),
+ 100));
+
+ SchedulerClient client = CronJobClient.schedulerClient(dataSource);
+ MaintenanceJobSpec batch0 =
+ (MaintenanceJobSpec)
+ client
+ .getScheduledExecution(
+ TaskInstanceId.of(
+ TableMaintenanceSchedulerPools.CRON_JOB,
+ MaintenanceTaskIds.forCronBatch(0L, 9L)))
+ .get()
+ .getData();
+ MaintenanceJobSpec batch1 =
+ (MaintenanceJobSpec)
+ client
+ .getScheduledExecution(
+ TaskInstanceId.of(
+ TableMaintenanceSchedulerPools.CRON_JOB,
+ MaintenanceTaskIds.forCronBatch(1L, 9L)))
+ .get()
+ .getData();
+ Assertions.assertEquals(cap, batch0.tableIds().size());
+ Assertions.assertEquals(List.of(100L, 101L), batch1.tableIds());
+ }
+
+ @TestTemplate
+ void testPendingCronGateSkipsQueuedTables() {
+ DataSource dataSource = dataSource();
+ CronJobClient scheduler = scheduler(dataSource);
+ Assertions.assertEquals(
+ 1,
+ scheduler.enqueueNow(
+ expirePolicy(9L),
+ List.of(
+ candidate(10L, MetadataObject.Type.SCHEMA),
+ candidate(11L, MetadataObject.Type.SCHEMA)),
+ 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()));
+ }
+
+ @TestTemplate
+ void testCronJobTaskRemovesRowAfterPick() throws Exception {
+ DataSource dataSource = dataSource();
+ CronJobClient enqueue = scheduler(dataSource);
+ Assertions.assertEquals(
+ 1,
+ enqueue.enqueueNow(
+ compactionPolicy(9L), List.of(candidate(99L, MetadataObject.Type.TABLE)), 1));
+
+ TaskInstanceId instanceId =
+ TaskInstanceId.of(
+ TableMaintenanceSchedulerPools.CRON_JOB, MaintenanceTaskIds.forCronTable(99L, 9L));
+ SchedulerClient client = CronJobClient.schedulerClient(dataSource);
+ Assertions.assertTrue(client.getScheduledExecution(instanceId).isPresent());
+
+ Scheduler cronPool =
+ Scheduler.create(dataSource, TableMaintenanceSchedulerPools.cronJobTask())
+ .threads(1)
+ .pollingInterval(Duration.ofMillis(100))
+ .serializer(new JacksonSerializer(JsonUtils.anyFieldMapper()))
+ .tableName(TableMaintenanceSchedulerPools.CRON_TASKS_TABLE)
+ .commitWhenAutocommitDisabled(true)
+ .build();
+ cronPool.start();
+ try {
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
+ while (client.getScheduledExecution(instanceId).isPresent()) {
+ Assertions.assertTrue(
+ System.nanoTime() < deadline, "cron-job row was not removed after pick");
+ Thread.sleep(100L);
+ }
+ } finally {
+ cronPool.stop();
+ }
+
+ Assertions.assertEquals(
+ 1,
+ enqueue.enqueueNow(
+ compactionPolicy(9L), List.of(candidate(99L, MetadataObject.Type.TABLE)), 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 &gt;= 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()));
+ }
+
+ 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 ExpandTableCandidate candidate(long tableId, MetadataObject.Type level) {
+ return new ExpandTableCandidate(tableId, level);
+ }
+
+ private static List<ExpandTableCandidate> schemaCandidates(long fromInclusive, long toInclusive) {
+ return LongStream.rangeClosed(fromInclusive, toInclusive)
+ .mapToObj(id -> candidate(id, MetadataObject.Type.SCHEMA))
+ .collect(Collectors.toList());
+ }
+
+ private static PolicyEntity compactionPolicy(long id) {
+ return PolicyEntity.builder()
+ .withId(id)
+ .withName("p-" + id)
+ .withNamespace(NamespaceUtil.ofPolicy("ml"))
+ .withPolicyType(Policy.BuiltInType.ICEBERG_COMPACTION)
+ .withEnabled(true)
+ .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()))
+ .withAuditInfo(
+ AuditInfo.builder().withCreator("test").withCreateTime(Instant.EPOCH).build())
+ .build();
+ }
+
+ 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/job/cron/TestCronJobIds.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestCronJobIds.java
deleted file mode 100644
index 57f89116af..0000000000
--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestCronJobIds.java
+++ /dev/null
@@ -1,58 +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.Optional;
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.Test;
-
-class TestCronJobIds {
-
- @Test
- void testForTableAndParseRoundTrip() {
- String id = CronJobIds.forTable(10L, 20L);
- Assertions.assertEquals("table:10:20", id);
- Optional<CronJobIds.TablePolicyIds> parsed = CronJobIds.parseTable(id);
- Assertions.assertTrue(parsed.isPresent());
- Assertions.assertEquals(10L, parsed.get().tableId());
- Assertions.assertEquals(20L, parsed.get().policyId());
- }
-
- @Test
- void testForBatchAndParseRoundTrip() {
- Assertions.assertEquals("batch:0:9", CronJobIds.forBatch(0L, 9L));
- Assertions.assertEquals("batch:12:9", CronJobIds.forBatch(12L, 9L));
- Optional<CronJobIds.BatchPolicyIds> parsed = CronJobIds.parseBatch("batch:12:9");
- Assertions.assertTrue(parsed.isPresent());
- Assertions.assertEquals(12L, parsed.get().batchId());
- Assertions.assertEquals(9L, parsed.get().policyId());
- }
-
- @Test
- void testParseRejectsInvalid() {
- Assertions.assertTrue(CronJobIds.parseTable(null).isEmpty());
- Assertions.assertTrue(CronJobIds.parseTable("batch:1:2").isEmpty());
- Assertions.assertTrue(CronJobIds.parseTable("table:").isEmpty());
- Assertions.assertTrue(CronJobIds.parseTable("table:1").isEmpty());
- Assertions.assertTrue(CronJobIds.parseTable("table:a:2").isEmpty());
- Assertions.assertTrue(CronJobIds.parseBatch(null).isEmpty());
- Assertions.assertTrue(CronJobIds.parseBatch("table:1:2").isEmpty());
- Assertions.assertTrue(CronJobIds.parseBatch("batch:pending:9").isEmpty());
- }
-}
diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestCronJobScheduler.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestCronJobScheduler.java
deleted file mode 100644
index 417a3cefcb..0000000000
--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestCronJobScheduler.java
+++ /dev/null
@@ -1,324 +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.github.kagkarlsson.scheduler.Scheduler;
-import com.github.kagkarlsson.scheduler.SchedulerClient;
-import com.github.kagkarlsson.scheduler.serializer.JacksonSerializer;
-import com.github.kagkarlsson.scheduler.task.TaskInstanceId;
-import java.time.Duration;
-import java.time.Instant;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
-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.policy.MaintenanceAuthConfigs;
-import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;
-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;
-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 TestCronJobScheduler extends TestJDBCBackend {
-
- private static final String GRAVITINO_URI = "http://localhost:8090";
-
- @TestTemplate
- void testEnqueueIsIdempotentAndRespectsBatchSize() {
- DataSource dataSource = dataSource();
- CronJobScheduler 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.enqueueDueNow(policy, three, 2));
- Assertions.assertEquals(
- 0,
- scheduler.enqueueDueNow(
- policy,
- List.of(
- candidate(1L, MetadataObject.Type.TABLE), candidate(2L, MetadataObject.Type.TABLE)),
- 2));
-
- SchedulerClient client = RelationalCronJobScheduler.client(dataSource);
- Assertions.assertTrue(
- client
- .getScheduledExecution(
- TaskInstanceId.of(
- TableMaintenanceSchedulerPools.CRON_JOB, CronJobIds.forTable(1L, 7L)))
- .isPresent());
- Assertions.assertTrue(
- client
- .getScheduledExecution(
- TaskInstanceId.of(
- TableMaintenanceSchedulerPools.CRON_JOB, CronJobIds.forTable(2L, 7L)))
- .isPresent());
- Assertions.assertTrue(
- client
- .getScheduledExecution(
- TaskInstanceId.of(
- TableMaintenanceSchedulerPools.CRON_JOB, CronJobIds.forTable(3L, 7L)))
- .isEmpty());
-
- MaintenanceJobSpec spec =
- (MaintenanceJobSpec)
- client
- .getScheduledExecution(
- TaskInstanceId.of(
- TableMaintenanceSchedulerPools.CRON_JOB, CronJobIds.forTable(1L, 7L)))
- .get()
- .getData();
- Assertions.assertTrue(spec.isValid());
- Assertions.assertTrue(spec.getJobConf().containsKey("updater_options"));
- Assertions.assertEquals(List.of(1L), spec.tableIds());
- }
-
- @TestTemplate
- void testSnapshotExpiryFillsIncompleteBatchBeforeAllocatingNextId() {
- DataSource dataSource = dataSource();
- CronJobScheduler scheduler = scheduler(dataSource);
- PolicyEntity policy = expirePolicy(9L);
-
- Assertions.assertEquals(
- 1,
- scheduler.enqueueDueNow(
- policy,
- List.of(
- candidate(10L, MetadataObject.Type.SCHEMA),
- candidate(11L, MetadataObject.Type.SCHEMA)),
- 10));
-
- Assertions.assertEquals(
- 0,
- scheduler.enqueueDueNow(
- policy,
- List.of(
- candidate(10L, MetadataObject.Type.SCHEMA),
- candidate(11L, MetadataObject.Type.SCHEMA),
- candidate(12L, MetadataObject.Type.CATALOG),
- candidate(13L, MetadataObject.Type.SCHEMA)),
- 10));
-
- SchedulerClient client = RelationalCronJobScheduler.client(dataSource);
- TaskInstanceId batch0 =
- TaskInstanceId.of(TableMaintenanceSchedulerPools.CRON_JOB, CronJobIds.forBatch(0L, 9L));
- TaskInstanceId batch1 =
- TaskInstanceId.of(TableMaintenanceSchedulerPools.CRON_JOB, CronJobIds.forBatch(1L, 9L));
- Assertions.assertTrue(client.getScheduledExecution(batch0).isPresent());
- Assertions.assertTrue(client.getScheduledExecution(batch1).isEmpty());
- MaintenanceJobSpec data =
- (MaintenanceJobSpec) client.getScheduledExecution(batch0).get().getData();
- Assertions.assertEquals(List.of(10L, 11L, 12L, 13L), data.tableIds());
- Assertions.assertEquals(1, data.getOperations().size());
- Assertions.assertTrue(data.getJobConf().containsKey("updater_options"));
- }
-
- @TestTemplate
- void testSnapshotExpiryAllocatesNextBatchWhenCapacityFull() {
- DataSource dataSource = dataSource();
- CronJobScheduler scheduler = scheduler(dataSource);
- PolicyEntity policy = expirePolicy(9L);
-
- Assertions.assertEquals(
- 1,
- scheduler.enqueueDueNow(
- policy,
- List.of(
- candidate(1L, MetadataObject.Type.SCHEMA),
- candidate(2L, MetadataObject.Type.SCHEMA)),
- 2));
- Assertions.assertEquals(
- 1,
- scheduler.enqueueDueNow(
- policy,
- List.of(
- candidate(1L, MetadataObject.Type.SCHEMA),
- candidate(2L, MetadataObject.Type.SCHEMA),
- candidate(3L, MetadataObject.Type.SCHEMA)),
- 2));
-
- SchedulerClient client = RelationalCronJobScheduler.client(dataSource);
- MaintenanceJobSpec batch0 =
- (MaintenanceJobSpec)
- client
- .getScheduledExecution(
- TaskInstanceId.of(
- TableMaintenanceSchedulerPools.CRON_JOB, CronJobIds.forBatch(0L, 9L)))
- .get()
- .getData();
- MaintenanceJobSpec batch1 =
- (MaintenanceJobSpec)
- client
- .getScheduledExecution(
- TaskInstanceId.of(
- TableMaintenanceSchedulerPools.CRON_JOB, CronJobIds.forBatch(1L, 9L)))
- .get()
- .getData();
- Assertions.assertEquals(List.of(1L, 2L), batch0.tableIds());
- Assertions.assertEquals(List.of(3L), batch1.tableIds());
- }
-
- @TestTemplate
- void testPendingCronGateSkipsQueuedTables() {
- DataSource dataSource = dataSource();
- CronJobScheduler scheduler = scheduler(dataSource);
- Assertions.assertEquals(
- 1,
- scheduler.enqueueDueNow(
- expirePolicy(9L),
- List.of(
- candidate(10L, MetadataObject.Type.SCHEMA),
- candidate(11L, MetadataObject.Type.SCHEMA)),
- 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()));
- }
-
- @TestTemplate
- void testCronJobTaskRemovesRowAfterPick() throws Exception {
- DataSource dataSource = dataSource();
- CronJobScheduler enqueue = scheduler(dataSource);
- Assertions.assertEquals(
- 1,
- enqueue.enqueueDueNow(
- compactionPolicy(9L), List.of(candidate(99L, MetadataObject.Type.TABLE)), 1));
-
- TaskInstanceId instanceId =
- TaskInstanceId.of(TableMaintenanceSchedulerPools.CRON_JOB, CronJobIds.forTable(99L, 9L));
- SchedulerClient client = RelationalCronJobScheduler.client(dataSource);
- Assertions.assertTrue(client.getScheduledExecution(instanceId).isPresent());
-
- Scheduler cronPool =
- Scheduler.create(dataSource, TableMaintenanceSchedulerPools.cronJobTask())
- .threads(1)
- .pollingInterval(Duration.ofMillis(100))
- .serializer(new JacksonSerializer(JsonUtils.anyFieldMapper()))
- .tableName(TableMaintenanceSchedulerPools.CRON_TASKS_TABLE)
- .commitWhenAutocommitDisabled(true)
- .build();
- cronPool.start();
- try {
- long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
- while (client.getScheduledExecution(instanceId).isPresent()) {
- Assertions.assertTrue(
- System.nanoTime() < deadline, "cron-job row was not removed after pick");
- Thread.sleep(100L);
- }
- } finally {
- cronPool.stop();
- }
-
- Assertions.assertEquals(
- 1,
- enqueue.enqueueDueNow(
- compactionPolicy(9L), List.of(candidate(99L, MetadataObject.Type.TABLE)), 1));
- Assertions.assertTrue(client.getScheduledExecution(instanceId).isPresent());
- }
-
- private static CronJobScheduler scheduler(DataSource dataSource) {
- return new RelationalCronJobScheduler(
- 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 ExpandTableCandidate candidate(long tableId, MetadataObject.Type level) {
- return new ExpandTableCandidate(tableId, level);
- }
-
- private static PolicyEntity compactionPolicy(long id) {
- return PolicyEntity.builder()
- .withId(id)
- .withName("p-" + id)
- .withNamespace(NamespaceUtil.ofPolicy("ml"))
- .withPolicyType(Policy.BuiltInType.ICEBERG_COMPACTION)
- .withEnabled(true)
- .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()))
- .withAuditInfo(
- AuditInfo.builder().withCreator("test").withCreateTime(Instant.EPOCH).build())
- .build();
- }
-
- 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/job/cron/TestMaintenanceSparkSubmitPipeline.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestMaintenanceSparkSubmitPipeline.java
index 0c2d19ab7c..d46a603f1f 100644
--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestMaintenanceSparkSubmitPipeline.java
+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/cron/TestMaintenanceSparkSubmitPipeline.java
@@ -38,6 +38,7 @@ import org.apache.gravitino.Config;
import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec;
import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.Operation;
import org.apache.gravitino.maintenance.scheduler.MaintenanceJobSpec.TableTarget;
+import org.apache.gravitino.maintenance.scheduler.MaintenanceTaskIds;
import org.apache.gravitino.maintenance.storage.service.OccupancyClaim;
import org.apache.gravitino.maintenance.storage.service.TableMaintenanceActionMetaService;
import org.junit.jupiter.api.Assertions;
@@ -48,7 +49,7 @@ class TestMaintenanceSparkSubmitPipeline {
private static final long TABLE_ID = 101L;
private static final long POLICY_ID = 202L;
- private static final String INSTANCE = CronJobIds.forTable(TABLE_ID, POLICY_ID);
+ private static final String INSTANCE = MaintenanceTaskIds.forCronTable(TABLE_ID, POLICY_ID);
private static final long CLAIM_TIMEOUT_MS = 60_000L;
@Test
@@ -94,7 +95,8 @@ class TestMaintenanceSparkSubmitPipeline {
List.of(new Operation(POLICY_ID, "expire_snapshots")),
shared);
- pipeline(gate, actions, submitter).submit(CronJobIds.forBatch(0L, POLICY_ID), batch);
+ 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());
@@ -216,7 +218,8 @@ class TestMaintenanceSparkSubmitPipeline {
List.of(new Operation(POLICY_ID, "expire_snapshots")),
shared);
- pipeline(mockGate(false), actions, submitter).submit(CronJobIds.forBatch(0L, POLICY_ID), batch);
+ pipeline(mockGate(false), actions, submitter)
+ .submit(MaintenanceTaskIds.forCronBatch(0L, POLICY_ID), batch);
@SuppressWarnings("unchecked")
ArgumentCaptor<Map<String, String>> confCaptor = ArgumentCaptor.forClass(Map.class);
@@ -285,7 +288,7 @@ class TestMaintenanceSparkSubmitPipeline {
MaintenanceJobSubmitter submitter = mock(MaintenanceJobSubmitter.class);
TableMaintenanceActionMetaService actions = mock(TableMaintenanceActionMetaService.class);
pipeline(mockGate(false), actions, submitter)
- .submit(CronJobIds.forTable(TABLE_ID, POLICY_ID + 1), spec());
+ .submit(MaintenanceTaskIds.forCronTable(TABLE_ID, POLICY_ID + 1), spec());
verify(submitter, never()).runJob(anyString(), anyString(), anyMap());
}
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.java
index bd5e7509a1..80ebab9a55 100644
--- 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.java
@@ -35,7 +35,7 @@ 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.CronJobScheduler;
+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;
@@ -51,17 +51,17 @@ class TestPolicyExpandPipeline {
@Test
void testMissingPolicyRemovesExpandRow() {
- CronJobScheduler cronJobs = mock(CronJobScheduler.class);
+ 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()).enqueueDueNow(any(), any(), anyInt());
+ verify(cronJobs, never()).enqueueNow(any(), any(), anyInt());
}
@Test
void testDisabledPolicyRemovesExpandRow() {
- CronJobScheduler cronJobs = mock(CronJobScheduler.class);
+ CronJobClient cronJobs = mock(CronJobClient.class);
PolicyExpandPipeline pipeline =
pipeline(
lookup(2L, policy(false, CRON, null)),
@@ -70,12 +70,12 @@ class TestPolicyExpandPipeline {
allowAll());
Assertions.assertTrue(pipeline.expand(2L).isEmpty());
- verify(cronJobs, never()).enqueueDueNow(any(), any(), anyInt());
+ verify(cronJobs, never()).enqueueNow(any(), any(), anyInt());
}
@Test
void testBlankTimeTriggerRemovesExpandRow() {
- CronJobScheduler cronJobs = mock(CronJobScheduler.class);
+ CronJobClient cronJobs = mock(CronJobClient.class);
PolicyExpandPipeline pipeline =
pipeline(
lookup(3L, policy(true, " ", null)),
@@ -84,19 +84,19 @@ class TestPolicyExpandPipeline {
allowAll());
Assertions.assertTrue(pipeline.expand(3L).isEmpty());
- verify(cronJobs, never()).enqueueDueNow(any(), any(), anyInt());
+ verify(cronJobs, never()).enqueueNow(any(), any(), anyInt());
}
@Test
void testInvalidTimeTriggerRemovesExpandRowWithoutEnqueue() {
PolicyTableEnumerator tables = mock(PolicyTableEnumerator.class);
- CronJobScheduler cronJobs = mock(CronJobScheduler.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()).enqueueDueNow(any(), any(), anyInt());
+ verify(cronJobs, never()).enqueueNow(any(), any(), anyInt());
}
@Test
@@ -110,14 +110,14 @@ class TestPolicyExpandPipeline {
eq(gate),
eq(MaintenanceMinIntervalConfigs.DEFAULT_HOURLY_MIN_INTERVAL_MS)))
.thenReturn(List.of(c(10L), c(11L)));
- CronJobScheduler cronJobs = mock(CronJobScheduler.class);
- when(cronJobs.enqueueDueNow(eq(policy), eq(List.of(c(10L), c(11L))), eq(2))).thenReturn(2);
+ 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).enqueueDueNow(policy, List.of(c(10L), c(11L)), 2);
+ verify(cronJobs).enqueueNow(policy, List.of(c(10L), c(11L)), 2);
}
@Test
@@ -127,13 +127,13 @@ class TestPolicyExpandPipeline {
PolicyTableEnumerator tables = mock(PolicyTableEnumerator.class);
when(tables.listTableIds(eq(policy), eq(10), eq(gate), eq(60_000L)))
.thenReturn(List.of(c(11L)));
- CronJobScheduler cronJobs = mock(CronJobScheduler.class);
- when(cronJobs.enqueueDueNow(eq(policy), eq(List.of(c(11L))), eq(10))).thenReturn(1);
+ 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).enqueueDueNow(policy, List.of(c(11L)), 10);
+ verify(cronJobs).enqueueNow(policy, List.of(c(11L)), 10);
}
@Test
@@ -147,8 +147,8 @@ class TestPolicyExpandPipeline {
eq(gate),
eq(MaintenanceMinIntervalConfigs.DEFAULT_HOURLY_MIN_INTERVAL_MS)))
.thenReturn(List.of(c(10L)));
- CronJobScheduler cronJobs = mock(CronJobScheduler.class);
- when(cronJobs.enqueueDueNow(eq(policy), eq(List.of(c(10L))), eq(10))).thenReturn(1);
+ 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());
@@ -160,10 +160,33 @@ class TestPolicyExpandPipeline {
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,
- CronJobScheduler cronJobs,
+ CronJobClient cronJobs,
ExpandOccupancyGate gate) {
return pipeline(policyLoader, tables, cronJobs, gate, 100);
}
@@ -171,7 +194,7 @@ class TestPolicyExpandPipeline {
private static PolicyExpandPipeline pipeline(
Function<Long, Optional<PolicyEntity>> policyLoader,
PolicyTableEnumerator tables,
- CronJobScheduler cronJobs,
+ CronJobClient cronJobs,
ExpandOccupancyGate gate,
int batchSize) {
return new PolicyExpandPipeline(
@@ -217,4 +240,17 @@ class TestPolicyExpandPipeline {
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.java
new file mode 100644
index 0000000000..5ee2a2fb5f
--- /dev/null
+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/policy/expand/TestPolicyExpandSnapshotEnqueue.java
@@ -0,0 +1,204 @@
+/*
+ * 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();
+ }
+}