World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#13180] improvement(core): Register a job before submitting it to the job executor (#14278)
Qi Yu717c466c61d1
diff --git a/core/src/main/java/org/apache/gravitino/connector/job/JobExecutor.java b/core/src/main/java/org/apache/gravitino/connector/job/JobExecutor.javaindex c15389e738..5d127cbeb0 100644--- a/core/src/main/java/org/apache/gravitino/connector/job/JobExecutor.java+++ b/core/src/main/java/org/apache/gravitino/connector/job/JobExecutor.java@@ -23,6 +23,7 @@ import java.io.Closeable;import java.util.Collections;import java.util.List;import java.util.Map;+import java.util.Optional;import org.apache.gravitino.annotation.DeveloperApi;import org.apache.gravitino.exceptions.NoSuchJobException;import org.apache.gravitino.job.JobHandle;@@ -48,7 +49,28 @@ public interface JobExecutor extends Closeable {* Submit a job to the external job runner.** <p>The returned job identifier is unique in the external job runner, and can be used to track- * the job status or cancel it later.+ * the job status or cancel it later. It must not start with {@code pending-submission:}, which+ * Gravitino reserves for a job being submitted.+ *+ * <p>Throw {@link IllegalArgumentException} for invalid input, or {@link+ * JobSubmissionRejectedException} for a confirmed rejection that left no execution. Gravitino+ * removes the registration for these failures. Any other exception means that the outcome is+ * unknown, for example when the response of the job runner was lost:+ *+ * <ul>+ * <li>If the job executor implements {@link #findSubmittedJob(JobContext, JobTemplate)},+ * Gravitino retains the registration, marks the job as cancelling, and uses that method to+ * find and cancel any execution once the job runner is available again. Do not classify a+ * lost response as a confirmed rejection.+ * <li>Otherwise Gravitino can't find such an execution, so it removes the registration. The job+ * executor must remove what it may have created before throwing.+ * </ul>+ *+ * <p>Gravitino registers the job before calling this method. On a deployment with several+ * Gravitino servers, the registration-to-recording phase should finish within three {@code+ * gravitino.job.statusPullIntervalInMs}: otherwise another server may settle the job, see {@link+ * #findSubmittedJob(JobContext, JobTemplate)}, and the server submitting it then cancels the+ * returned execution and fails the request.** <p>The placeholders in the job template have already been replaced with the actual values, but* its resources, that is its executable, scripts, jars, files and archives, are still the URIs@@ -65,7 +87,15 @@ public interface JobExecutor extends Closeable {* @return A unique identifier for the submitted job.*/default String submitJob(JobContext context, JobTemplate jobTemplate) {- return submitJob(JobResourceUtils.localizeJobTemplate(jobTemplate, context.stagingDir()));+ JobTemplate localized;+ try {+ localized = JobResourceUtils.localizeJobTemplate(jobTemplate, context.stagingDir());+ } catch (IllegalArgumentException e) {+ throw e;+ } catch (RuntimeException e) {+ throw new JobSubmissionRejectedException("Failed to localize the job before submission", e);+ }+ return submitJob(localized);}/**@@ -89,6 +119,53 @@ public interface JobExecutor extends Closeable {getClass().getName() + " doesn't support submitJob(JobTemplate)");}+ /**+ * Find the execution of a job that was submitted to this job executor, but whose execution id+ * Gravitino didn't record, for example because the Gravitino server submitting it exited right+ * after the submission.+ *+ * <p>Gravitino registers a job before submitting it, and records the execution id that {@link+ * #submitJob(JobContext, JobTemplate)} returns afterwards. If another Gravitino server doesn't+ * record it within three {@code gravitino.job.statusPullIntervalInMs}, Gravitino calls this+ * method and settles the job by the result:+ *+ * <ul>+ * <li>An execution id is recorded, and the job is tracked like any other one. It must be the+ * same string as {@link #submitJob(JobContext, JobTemplate)} returns for the job: if that+ * submission returns later with another one, the server submitting the job cancels that+ * execution as an unrecorded one.+ * <li>Empty means that the job has no execution. The job is marked as {@link+ * JobHandle.Status#FAILED}, or {@link JobHandle.Status#CANCELLED} if it is being cancelled.+ * Only return empty when the job runner confirms that it has no execution of the job,+ * unless the job executor can't look up an execution at all, see the default implementation+ * below.+ * <li>An exception means that the lookup failed. The job stays as it is, and the lookup is+ * retried in the next status pull.+ * </ul>+ *+ * <p>The submission may still be running on the server submitting the job, for example when it+ * takes longer than expected, so this method may be called while {@link #submitJob(JobContext,+ * JobTemplate)} is running for the same job, possibly in another process. If no execution is+ * found then, the job is marked as failed, and the execution that the submission returns is+ * cancelled.+ *+ * <p>The default implementation returns empty, for a job executor that can't look up an+ * execution, or whose job state is lost with the server submitting the job. Such a job executor+ * must not leave an execution behind when {@link #submitJob(JobContext, JobTemplate)} throws, see+ * there. A job executor that can look up an execution by {@link JobContext#jobId()} should+ * implement this method, so Gravitino recovers the jobs whose submission outcome is unknown.+ *+ * @param context The context of the job, with the same job id and metalake as the submission. Its+ * staging directory is the one of the calling server, which may not exist, rather than the+ * one the job was submitted with.+ * @param jobTemplate The runtime job template the job was submitted with, whose resources are+ * URIs.+ * @return The unique identifier of the execution of the job, or empty if there is none.+ */+ default Optional<String> findSubmittedJob(JobContext context, JobTemplate jobTemplate) {+ return Optional.empty();+ }+/*** Get a snapshot of the job's execution state by its unique identifier, including its status and* when the job actually started and finished. The implementors should query the external job@@ -138,6 +215,11 @@ public interface JobExecutor extends Closeable {* <p>This method should not be blocked on the job cancellation, it should return immediately, and* Gravitino can further query the job status to check if the job is cancelled successfully.*+ * <p>Gravitino may repeat this call after a failure, or while the runner still reports {@link+ * JobHandle.Status#QUEUED} or {@link JobHandle.Status#STARTED}. Cancellation must be idempotent.+ * Report {@link JobHandle.Status#CANCELLING} once asynchronous cancellation is acknowledged, so+ * Gravitino can monitor it without reissuing the request.+ ** @param jobId The unique identifier of the job to cancel.* @throws NoSuchJobException If the job with the given identifier does not exist.*/diff --git a/core/src/main/java/org/apache/gravitino/connector/job/JobSubmissionRejectedException.java b/core/src/main/java/org/apache/gravitino/connector/job/JobSubmissionRejectedException.javanew file mode 100644index 0000000000..15f4919c89--- /dev/null+++ b/core/src/main/java/org/apache/gravitino/connector/job/JobSubmissionRejectedException.java@@ -0,0 +1,48 @@+/*+ * 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.connector.job;++/**+ * Signals that a job submission failed without leaving any execution in the job runner.+ *+ * <p>Only throw this exception when no execution was created, or its removal is confirmed.+ * Transport failures with an unknown outcome must use another exception so Gravitino retains the+ * registration for recovery.+ */+public class JobSubmissionRejectedException extends RuntimeException {+ /**+ * Creates a confirmed rejection.+ *+ * @param message the reason the job was not submitted+ */+ public JobSubmissionRejectedException(String message) {+ super(message);+ }++ /**+ * Creates a confirmed rejection with its original failure.+ *+ * @param message the reason the job was not submitted+ * @param cause the original failure+ */+ public JobSubmissionRejectedException(String message, Throwable cause) {+ super(message, cause);+ }+}diff --git a/core/src/main/java/org/apache/gravitino/hook/JobHookDispatcher.java b/core/src/main/java/org/apache/gravitino/hook/JobHookDispatcher.javaindex 320ab0ec0e..aa58b6a2e4 100644--- a/core/src/main/java/org/apache/gravitino/hook/JobHookDispatcher.java+++ b/core/src/main/java/org/apache/gravitino/hook/JobHookDispatcher.java@@ -118,19 +118,8 @@ public class JobHookDispatcher implements JobOperationDispatcher {@Overridepublic JobEntity runJob(String metalake, String jobTemplateName, Map<String, String> jobConf)throws NoSuchJobTemplateException {- JobEntity jobEntity = jobOperationDispatcher.runJob(metalake, jobTemplateName, jobConf);-- // Set the creator as the owner of the job.- OwnerDispatcher ownerManager = GravitinoEnv.getInstance().internalOwnerDispatcher();- if (ownerManager != null) {- ownerManager.setOwner(- metalake,- NameIdentifierUtil.toMetadataObject(jobEntity.nameIdentifier(), Entity.EntityType.JOB),- PrincipalUtils.getCurrentUserName(),- Owner.Type.USER);- }-- return jobEntity;+ // The manager persists the initial owner before submission, so recovery preserves it too.+ return jobOperationDispatcher.runJob(metalake, jobTemplateName, jobConf);}@Overridediff --git a/core/src/main/java/org/apache/gravitino/job/JobExecutorFactory.java b/core/src/main/java/org/apache/gravitino/job/JobExecutorFactory.javaindex fa96348dcd..2db7e5a7eb 100644--- a/core/src/main/java/org/apache/gravitino/job/JobExecutorFactory.java+++ b/core/src/main/java/org/apache/gravitino/job/JobExecutorFactory.java@@ -169,6 +169,12 @@ public class JobExecutorFactory {jobExecutorClass.getName());}+ static boolean implementsMethod(+ Class<?> jobExecutorClass, String name, Class<?>... parameterTypes) {+ // An inherited default method of the interface is declared by the interface itself.+ return declaringClassOf(jobExecutorClass, name, parameterTypes) != JobExecutor.class;+ }+private static Class<?> loadJobExecutorClass(String jobExecutorName, String clzName) {try {return Class.forName(clzName);@@ -192,12 +198,6 @@ public class JobExecutorFactory {}}- private static boolean implementsMethod(- Class<?> jobExecutorClass, String name, Class<?>... parameterTypes) {- // An inherited default method of the interface is declared by the interface itself.- return declaringClassOf(jobExecutorClass, name, parameterTypes) != JobExecutor.class;- }-private static Class<?> declaringClassOf(Class<?> jobExecutorClass, String name, Class<?>... parameterTypes) {try {diff --git a/core/src/main/java/org/apache/gravitino/job/JobManager.java b/core/src/main/java/org/apache/gravitino/job/JobManager.javaindex 2ad5a3b1a3..48f689f8e6 100644--- a/core/src/main/java/org/apache/gravitino/job/JobManager.java+++ b/core/src/main/java/org/apache/gravitino/job/JobManager.java@@ -37,7 +37,10 @@ import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.Map;+import java.util.Objects;import java.util.Optional;+import java.util.Set;+import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;@@ -53,11 +56,15 @@ import org.apache.gravitino.Configs;import org.apache.gravitino.Entity;import org.apache.gravitino.EntityAlreadyExistsException;import org.apache.gravitino.EntityStore;+import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;+import org.apache.gravitino.authorization.Owner;+import org.apache.gravitino.authorization.OwnerDispatcher;import org.apache.gravitino.connector.job.JobContext;import org.apache.gravitino.connector.job.JobExecutionInfo;import org.apache.gravitino.connector.job.JobExecutor;+import org.apache.gravitino.connector.job.JobSubmissionRejectedException;import org.apache.gravitino.dto.job.JobTemplateDTO;import org.apache.gravitino.dto.util.DTOConverters;import org.apache.gravitino.exceptions.InUseException;@@ -124,6 +131,18 @@ public class JobManager implements JobOperationDispatcher {// How many of the jobs whose status pull failed are named in the log of a poll.private static final int MAX_LOGGED_FAILED_JOBS = 5;+ // A job is registered with this placeholder execution id before it is handed to the job+ // executor, and gets the real one once the submission returns. The placeholder is unique per job,+ // as the execution id is part of a unique key, and is never handed to the job executor.+ private static final String PENDING_SUBMISSION_EXECUTION_ID_PREFIX = "pending-submission:";++ // A submission normally returns in seconds. A job whose submission is still not recorded after+ // this many pull intervals is considered left behind, e.g. by a server that exited while+ // submitting it, and is reconciled with the job executor.+ private static final int SUBMISSION_TIMEOUT_IN_PULL_INTERVALS = 3;++ private static final int SUBMISSION_WRITE_MAX_ATTEMPTS = 3;+private final EntityStore entityStore;private final File stagingDir;@@ -140,6 +159,16 @@ public class JobManager implements JobOperationDispatcher {private final long cancellationTimeoutInMs;+ private final long submissionTimeoutInMs;++ // Whether the job executor implements findSubmittedJob(), so a job whose submission outcome is+ // unknown can be recovered rather than removed.+ private final boolean findsSubmittedJobs;++ // The ids of the jobs this server is submitting. The status pull of this server leaves them to+ // their submission however long it takes, only the other servers settle them once it times out.+ private final Set<Long> jobsBeingSubmitted = ConcurrentHashMap.newKeySet();+@VisibleForTesting final ScheduledExecutorService cleanUpExecutor;@VisibleForTesting final ScheduledExecutorService statusPullExecutor;@@ -153,6 +182,9 @@ public class JobManager implements JobOperationDispatcher {Config config, EntityStore entityStore, IdGenerator idGenerator, JobExecutor jobExecutor) {this.entityStore = entityStore;this.jobExecutor = jobExecutor;+ this.findsSubmittedJobs =+ JobExecutorFactory.implementsMethod(+ jobExecutor.getClass(), "findSubmittedJob", JobContext.class, JobTemplate.class);this.idGenerator = idGenerator;String stagingDirPath = config.get(Configs.JOB_STAGING_DIR);@@ -218,6 +250,7 @@ public class JobManager implements JobOperationDispatcher {}this.cancellationTimeoutInMs =jobStatusPullIntervalInMs * CANCELLATION_TIMEOUT_IN_PULL_INTERVALS;+ this.submissionTimeoutInMs = jobStatusPullIntervalInMs * SUBMISSION_TIMEOUT_IN_PULL_INTERVALS;this.statusPullExecutor =Executors.newSingleThreadScheduledExecutor(runnable -> {@@ -478,7 +511,8 @@ public class JobManager implements JobOperationDispatcher {}});- if (!includeOutput) {+ // A job whose submission is not recorded yet has no execution, so no output either.+ if (!includeOutput || isPendingSubmission(entity)) {return entity;}@@ -569,35 +603,19 @@ public class JobManager implements JobOperationDispatcher {throw new RuntimeException("Failed to serialize the runtime job template", e);}- // The job is queued once it is submitted. Take the time before the submission, so that it is+ // The job is queued once it is registered. Take the time before the submission, so that it is// never later than the time the job executor reports the job started, which can happen right// after the job is submitted.Instant queuedAt = Instant.now();- // Submit the job template to the job executor- String jobExecutionId;- try {- jobExecutionId =- jobExecutor.submitJob(new JobContext(jobId, metalake, jobStagingDir), jobTemplate);- } catch (IllegalArgumentException e) {- // The job executor rejects the job because it cannot be launched, for example, a required- // configuration is missing. Rethrow it as is so the caller gets the original reason.- deleteStagingDirOfUnsubmittedJob(jobStagingDir, jobId);- throw e;- } catch (Exception e) {- deleteStagingDirOfUnsubmittedJob(jobStagingDir, jobId);- throw new RuntimeException(- String.format(- "Failed to submit job %s of job template %s for execution: %s",- jobId, jobTemplateName, e.getMessage()),- e);- }-- // Create a new JobEntity to represent the job- JobEntity jobEntity =+ // Register the job before handing it to the job executor, so that an execution is never left+ // running without a job, e.g. when the server exits right after the submission. Until the+ // submission is recorded, the job carries a placeholder execution id, and the status pull+ // settles it if the submission is not recorded in time.+ JobEntity pendingJobEntity =JobEntity.builder().withId(jobId)- .withJobExecutionId(jobExecutionId)+ .withJobExecutionId(pendingSubmissionExecutionId(jobId)).withJobTemplateName(jobTemplateName).withStatus(JobHandle.Status.QUEUED).withNamespace(NamespaceUtil.ofJob(metalake))@@ -612,52 +630,316 @@ public class JobManager implements JobOperationDispatcher {.withRuntimeJobTemplate(runtimeJobTemplateJson).build();+ jobsBeingSubmitted.add(jobId);try {- entityStore.put(jobEntity, false /* overwrite */);+ return registerAndSubmit(metalake, pendingJobEntity, jobTemplate, jobStagingDir);+ } finally {+ jobsBeingSubmitted.remove(jobId);+ }+ }++ private JobEntity registerAndSubmit(+ String metalake, JobEntity pendingJobEntity, JobTemplate jobTemplate, File jobStagingDir) {+ long jobId = pendingJobEntity.id();+ String jobTemplateName = pendingJobEntity.jobTemplateName();+ try {+ entityStore.put(pendingJobEntity, false /* overwrite */);} catch (NoSuchEntityException e) {- LOG.error(- "Job {} was submitted as execution {} but could not be registered because its template "- + "{} or metalake {} no longer exists",- jobEntity.name(),- jobExecutionId,- jobTemplateName,- metalake,- e);+ deleteStagingDirOfUnsubmittedJob(jobStagingDir, jobId);throw new NoSuchJobTemplateException(e,"Job template with name %s under metalake %s does not exist",jobTemplateName,metalake);- } catch (OptimisticLockException e) {- // Cancellation is asynchronous and cannot undo work that already finished. Request it- // best-effort, but do not expose a retryable conflict after submitting an execution.- LOG.warn(- "Job {} was submitted as execution {} but could not be registered because of a "- + "concurrent operation, cancelling the execution",- jobEntity.name(),- jobExecutionId,- e);+ } catch (RuntimeException e) {+ // Nothing is submitted yet, so a conflict is reported as is and the caller can retry.+ deleteStagingDirOfUnsubmittedJob(jobStagingDir, jobId);+ throw e;+ } catch (IOException e) {+ deleteStagingDirOfUnsubmittedJob(jobStagingDir, jobId);+ throw new RuntimeException("Failed to register the job entity " + pendingJobEntity, e);+ }++ // Ownership must be durable before the external submission: recovery does not run the+ // original request's post hook. A failure here has no external side effect to recover.+ try {+ OwnerDispatcher owners = GravitinoEnv.getInstance().internalOwnerDispatcher();+ if (owners != null) {+ owners.setOwner(+ metalake,+ NameIdentifierUtil.toMetadataObject(+ pendingJobEntity.nameIdentifier(), Entity.EntityType.JOB),+ PrincipalUtils.getCurrentUserName(),+ Owner.Type.USER);+ }+ } catch (RuntimeException e) {+ deleteUnsubmittedJob(metalake, pendingJobEntity, jobStagingDir, e);+ throw e;+ }++ // Submit the job template to the job executor+ String jobExecutionId;+ try {+ jobExecutionId =+ jobExecutor.submitJob(new JobContext(jobId, metalake, jobStagingDir), jobTemplate);+ } catch (IllegalArgumentException | JobSubmissionRejectedException e) {+ // The job executor rejects the job because it cannot be launched, for example, a required+ // configuration is missing. Rethrow it as is so the caller gets the original reason.+ deleteUnsubmittedJob(metalake, pendingJobEntity, jobStagingDir, e);+ throw e;+ } catch (Exception e) {+ if (!findsSubmittedJobs) {+ // The job executor can't find an execution the submission may have left, so the+ // registration couldn't recover it. The job executor removes what it created instead.+ RuntimeException failure =+ new RuntimeException(+ String.format(+ "Failed to submit job %s of job template %s for execution: %s",+ pendingJobEntity.name(), jobTemplateName, e.getMessage()),+ e);+ deleteUnsubmittedJob(metalake, pendingJobEntity, jobStagingDir, failure);+ throw failure;+ }++ RuntimeException failure =+ new RuntimeException(+ String.format(+ "Failed to submit job %s of job template %s for execution: %s. The outcome is"+ + " unknown, so the job is kept and cancelled, and any execution found for it"+ + " in the job executor is cancelled too. Check the job before retrying",+ pendingJobEntity.name(), jobTemplateName, e.getMessage()),+ e);+ // A failed request is not proof that nothing was submitted. Keep the recovery anchor+ // and persist cancellation before returning the failure. Never replay the submission.+ markFailedSubmissionForCancellation(metalake, pendingJobEntity, null, failure);+ throw failure;+ }++ return recordSubmission(metalake, pendingJobEntity, jobExecutionId);+ }++ // Persists the cancellation of a job whose submission failed. The execution id, if the job+ // executor returned one, is recorded along with it, so the status pull keeps cancelling that+ // execution rather than settling the job when a lookup doesn't find it.+ private void markFailedSubmissionForCancellation(+ String metalake, JobEntity job, @Nullable String jobExecutionId, Exception failure) {+ NameIdentifier jobIdent = NameIdentifierUtil.ofJob(metalake, job.name());+ String execution =+ jobExecutionId == null+ ? "an execution of job id " + job.id()+ : "execution " + jobExecutionId;+ for (int attempt = 1; attempt <= SUBMISSION_WRITE_MAX_ATTEMPTS; attempt++) {try {- jobExecutor.cancelJob(jobExecutionId);- } catch (Exception cancelFailure) {+ TreeLockUtils.doWithTreeLock(+ jobIdent,+ LockType.WRITE,+ () ->+ entityStore.update(+ jobIdent,+ JobEntity.class,+ Entity.EntityType.JOB,+ latest ->+ toCancellingJobEntity(+ jobExecutionId == null+ ? latest+ : withSubmittedExecution(latest, jobExecutionId))));+ return;+ } catch (OptimisticLockException e) {+ failure.addSuppressed(e);+ } catch (NoSuchEntityException e) {+ // E.g. its metalake was dropped. Nothing is left to recover the execution with.LOG.error(- "Failed to cancel the unregistered execution {} of job {}",- jobExecutionId,- jobEntity.name(),- cancelFailure);- e.addSuppressed(cancelFailure);+ "Job {} under metalake {} failed to be submitted or recorded and no longer exists, so"+ + " its cancellation can't be retried. Check the job executor for {}",+ job.name(),+ metalake,+ execution,+ failure);+ return;+ } catch (Exception e) {+ failure.addSuppressed(e);+ break;}- throw new RuntimeException(+ }+ // The registration is still retained if the store cannot record the cancellation. Recovery+ // can at least track a found execution instead of leaving it unknown to Gravitino.+ LOG.error(+ "Job {} under metalake {} failed to be submitted or recorded and its cancellation could"+ + " not be recorded. The job registration is retained; check the job and {} before"+ + " retrying",+ job.name(),+ metalake,+ execution,+ failure);+ }++ private JobEntity recordSubmission(+ String metalake, JobEntity pendingJobEntity, String jobExecutionId) {+ NameIdentifier jobIdent = NameIdentifierUtil.ofJob(metalake, pendingJobEntity.name());+ Exception failure = null;+ JobEntity recorded = null;+ // entityStore.update() re-reads the job, so a conflict with a concurrent write, e.g. a+ // cancellation, succeeds when retried. The retries are bounded, a job that still can't be+ // recorded is settled by the status pull.+ for (int attempt = 1; attempt <= SUBMISSION_WRITE_MAX_ATTEMPTS; attempt++) {+ try {+ recorded =+ TreeLockUtils.doWithTreeLock(+ jobIdent,+ LockType.WRITE,+ () ->+ entityStore.update(+ jobIdent,+ JobEntity.class,+ Entity.EntityType.JOB,+ latest -> withSubmittedExecution(latest, jobExecutionId)));+ break;+ } catch (OptimisticLockException e) {+ if (failure == null) {+ failure = e;+ } else if (failure != e) {+ failure.addSuppressed(e);+ }+ } catch (Exception e) {+ // The job is gone, e.g. its metalake was dropped, or the store failed.+ if (failure != null && failure != e) {+ e.addSuppressed(failure);+ }+ failure = e;+ break;+ }+ }++ if (recorded != null && jobExecutionId.equals(recorded.jobExecutionId())) {+ if (recorded.status() == JobHandle.Status.CANCELLING) {+ // The job was cancelled while it was being submitted, before it could be cancelled in the+ // job executor.+ cancelSubmittedExecution(recorded, jobExecutionId, null);+ }+ return recorded;+ }++ // The submission could not be recorded, or another server settled the job as its submission+ // took too long. Cancellation is asynchronous and cannot undo work that already finished, so+ // request it best-effort, but do not expose a retryable conflict after submitting an execution.+ String reason;+ if (recorded == null) {+ reason = "the submission could not be recorded";+ } else {+ String settledAs =+ isPendingSubmission(recorded)+ ? "marked it as " + recorded.status()+ : "recorded execution " + recorded.jobExecutionId() + " for it";+ reason =String.format(- "Failed to register job %s after submitting execution %s; cancellation was attempted "- + "but the execution may already have run. Check the execution before retrying",- jobEntity.name(), jobExecutionId),+ "another Gravitino server %s, as its submission took longer than %d ms. Make sure"+ + " the job executor submits a job within three"+ + " gravitino.job.statusPullIntervalInMs, and that all servers use the same"+ + " interval and have their clocks in sync",+ settledAs, submissionTimeoutInMs);+ }+ RuntimeException registrationFailure =+ new RuntimeException(+ String.format(+ "Failed to register job %s after submitting execution %s: %s. Cancellation was"+ + " attempted but the execution may already have run. Check the execution"+ + " before retrying",+ pendingJobEntity.name(), jobExecutionId, reason),+ failure);+ LOG.warn(+ "Job {} was submitted as execution {} but {}, cancelling the execution",+ pendingJobEntity.name(),+ jobExecutionId,+ reason,+ failure);+ if (recorded == null && !(failure instanceof NoSuchEntityException)) {+ // The registration still anchors recovery even when recording the id conflicted. Persist+ // the cancellation intent with the known execution id, so a failed immediate cancellation is+ // retried even if the job executor can't look up the submission.+ markFailedSubmissionForCancellation(+ metalake, pendingJobEntity, jobExecutionId, registrationFailure);+ }+ cancelSubmittedExecution(pendingJobEntity, jobExecutionId, registrationFailure);+ throw registrationFailure;+ }++ // Records the execution of a job whose submission is still pending. A job whose submission was+ // settled by the status pull in the meantime, which keeps the placeholder execution id, is left+ // as is.+ private JobEntity withSubmittedExecution(JobEntity latestJobEntity, String jobExecutionId) {+ if (!isPendingSubmission(latestJobEntity) || isFinishedStatus(latestJobEntity.status())) {+ return latestJobEntity;+ }++ return JobEntity.builder()+ .withId(latestJobEntity.id())+ .withJobExecutionId(jobExecutionId)+ .withJobTemplateName(latestJobEntity.jobTemplateName())+ // The job stays QUEUED, or CANCELLING if it was cancelled while being submitted.+ .withStatus(latestJobEntity.status())+ .withNamespace(latestJobEntity.namespace())+ .withAuditInfo(latestJobEntity.auditInfo())+ .withStartedAt(latestJobEntity.startedAt())+ .withFinishedAt(latestJobEntity.finishedAt())+ .withRuntimeJobTemplate(latestJobEntity.runtimeJobTemplate())+ .build();+ }++ private void cancelSubmittedExecution(+ JobEntity job, String jobExecutionId, @Nullable Exception failure) {+ try {+ jobExecutor.cancelJob(jobExecutionId);+ } catch (NoSuchJobException e) {+ // Both the server submitting the job and the one reconciling it may cancel the execution.+ LOG.info("The execution {} of job {} is already gone", jobExecutionId, job.name());+ } catch (Exception cancelFailure) {+ LOG.error(+ "Failed to cancel the execution {} of job {}", jobExecutionId, job.name(), cancelFailure);+ if (failure != null) {+ failure.addSuppressed(cancelFailure);+ }+ }+ }++ // Only used when no execution was submitted, including owner-registration failure, or when the+ // job executor can't look up submissions. Never remove this recovery anchor for a submission+ // whose outcome is unknown if findSubmittedJob() could recover its execution.+ private void deleteUnsubmittedJob(+ String metalake, JobEntity pendingJobEntity, File jobStagingDir, Exception failure) {+ try {+ entityStore.delete(+ NameIdentifierUtil.ofJob(metalake, pendingJobEntity.name()), Entity.EntityType.JOB);+ } catch (Exception e) {+ failure.addSuppressed(e);+ LOG.warn(+ "Failed to delete unsubmitted job {}, settling its registration as FAILED",+ pendingJobEntity.name(),e);- } catch (IOException e) {- throw new RuntimeException("Failed to register the job entity " + jobEntity, e);+ try {+ updateJobEntity(+ metalake,+ pendingJobEntity,+ latest ->+ toUpdatedStatusJobEntity(latest, JobExecutionInfo.of(JobHandle.Status.FAILED)));+ } catch (RuntimeException settleFailure) {+ failure.addSuppressed(settleFailure);+ LOG.warn(+ "Failed to settle unsubmitted job {}; its registration is retained",+ pendingJobEntity.name(),+ settleFailure);+ }}+ deleteStagingDirOfUnsubmittedJob(jobStagingDir, pendingJobEntity.id());+ }++ @VisibleForTesting+ static String pendingSubmissionExecutionId(long jobId) {+ return PENDING_SUBMISSION_EXECUTION_ID_PREFIX + jobId;+ }- return jobEntity;+ private static boolean isPendingSubmission(JobEntity job) {+ return job.jobExecutionId() != null+ && job.jobExecutionId().startsWith(PENDING_SUBMISSION_EXECUTION_ID_PREFIX);}@Override@@ -667,19 +949,24 @@ public class JobManager implements JobOperationDispatcher {// Retrieve the job entity, will throw NoSuchJobException if the job does not exist.JobEntity jobEntity = getJob(metalake, jobId, false);- if (jobEntity.status() == JobHandle.Status.CANCELLING- || jobEntity.status() == JobHandle.Status.CANCELLED+ if (jobEntity.status() == JobHandle.Status.CANCELLED|| jobEntity.status() == JobHandle.Status.SUCCEEDED|| jobEntity.status() == JobHandle.Status.FAILED) {- // If the job is already cancelling, cancelled, succeeded, or failed, we do not need to cancel- // it again.+ // Never change a terminal job or request its cancellation again.return jobEntity;}// Cancel the job using the job executor if this server owns the job. Otherwise, the job runs// on another server, so only mark it as CANCELLING below, and the owning server cancels it- // when it pulls the job status next time.- if (jobExecutor.ownsJob(jobEntity.jobExecutionId())) {+ // when it pulls the job status next time. A job whose submission is not recorded yet is only+ // marked as CANCELLING, and its execution is cancelled once the submission is recorded.+ if (isPendingSubmission(jobEntity)) {+ LOG.info(+ "Job {} under metalake {} is being submitted, marking it as CANCELLING for its execution "+ + "to be cancelled once it is submitted",+ jobId,+ metalake);+ } else if (jobExecutor.ownsJob(jobEntity.jobExecutionId())) {try {jobExecutor.cancelJob(jobEntity.jobExecutionId());} catch (NoSuchJobException e) {@@ -704,33 +991,68 @@ public class JobManager implements JobOperationDispatcher {metalake);}+ if (jobEntity.status() == JobHandle.Status.CANCELLING) {+ // The cancellation above is retried, but its durable intent and timeout must not be reset.+ return jobEntity;+ }+// Update the job status to CANCELING- return TreeLockUtils.doWithTreeLock(- NameIdentifierUtil.ofJob(metalake, jobId),- LockType.WRITE,- () -> {- try {- // entityStore.update() re-fetches the latest entity itself right before applying the- // updater, rather than reusing the snapshot taken before the (potentially slow)- // external cancel call above - a concurrent status poll could have persisted a real- // startedAt/finishedAt in that gap, and carrying forward the stale snapshot would- // clobber it back to the sentinel.- return entityStore.update(- NameIdentifierUtil.ofJob(metalake, jobId),- JobEntity.class,- Entity.EntityType.JOB,- this::toCancellingJobEntity);- } catch (NoSuchEntityException e) {- throw new NoSuchJobException(- "Job with ID %s under metalake %s does not exist, this could be due to the job "- + "not existing or being deleted concurrently.",- jobId, metalake);- } catch (IOException e) {- throw new RuntimeException(- String.format("Failed to update job entity for job %s to CANCELING status", jobId),- e);- }- });+ JobEntity cancellingJobEntity =+ TreeLockUtils.doWithTreeLock(+ NameIdentifierUtil.ofJob(metalake, jobId),+ LockType.WRITE,+ () -> {+ try {+ // entityStore.update() re-fetches the latest entity itself right before applying+ // the updater, rather than reusing the snapshot taken before the (potentially+ // slow) external cancel call above - a concurrent status poll could have persisted+ // a real startedAt/finishedAt in that gap, and carrying forward the stale snapshot+ // would clobber it back to the sentinel.+ return entityStore.update(+ NameIdentifierUtil.ofJob(metalake, jobId),+ JobEntity.class,+ Entity.EntityType.JOB,+ this::toCancellingJobEntity);+ } catch (NoSuchEntityException e) {+ throw new NoSuchJobException(+ "Job with ID %s under metalake %s does not exist, this could be due to the job "+ + "not existing or being deleted concurrently.",+ jobId, metalake);+ } catch (IOException e) {+ throw new RuntimeException(+ String.format(+ "Failed to update job entity for job %s to CANCELING status", jobId),+ e);+ }+ });++ // The submission was recorded after the job was read above, so the server submitting it has+ // seen it QUEUED and won't cancel it. Cancel it here, as nobody else would cancel it in a job+ // executor whose job state is not node local.+ if (isPendingSubmission(jobEntity)+ && !isPendingSubmission(cancellingJobEntity)+ && cancellingJobEntity.status() == JobHandle.Status.CANCELLING+ && jobExecutor.ownsJob(cancellingJobEntity.jobExecutionId())) {+ try {+ jobExecutor.cancelJob(cancellingJobEntity.jobExecutionId());+ } catch (NoSuchJobException e) {+ // The status pull settles it as CANCELLED.+ LOG.info(+ "The execution {} of job {} is already gone",+ cancellingJobEntity.jobExecutionId(),+ jobId);+ } catch (Exception e) {+ // The intent is durable, so the status pull retries this cancellation after a failure.+ throw new RuntimeException(+ String.format(+ "Job %s under metalake %s is marked as CANCELLING, but failed to cancel its"+ + " execution %s, which was submitted meanwhile. The status pull will retry"+ + " the cancellation; the cancel request can also be retried",+ jobId, metalake, cancellingJobEntity.jobExecutionId()),+ e);+ }+ }+ return cancellingJobEntity;}private JobEntity toCancellingJobEntity(JobEntity latestJobEntity) {@@ -1058,6 +1380,16 @@ public class JobManager implements JobOperationDispatcher {for (JobEntity job : activeJobs) {// A failure on one job must never stop the status pull of the others.try {+ // A job whose submission is not recorded yet has no execution to query. It is left to the+ // server submitting it, unless another server is submitting it and doesn't record it in+ // time, e.g. because that server has exited.+ if (isPendingSubmission(job)) {+ if (!jobsBeingSubmitted.contains(job.id()) && isSubmissionUnanswered(job, now)) {+ reconcilePendingSubmission(metalake, job, now);+ }+ continue;+ }+// Only the job executor instance owning the job can query its status. The jobs owned by// other servers are skipped, except a node local job whose cancellation its owner has not// answered in time: the owner has likely exited, e.g. the server restarted, so nobody else@@ -1096,12 +1428,10 @@ public class JobManager implements JobOperationDispatcher {JobExecutionInfo observed;try {observed = jobExecutor.getJobExecutionInfo(job.jobExecutionId());- // The job was marked as CANCELLING by another server, which can't cancel it itself, so- // cancel it here as the owner. This only applies to node local job state, other job- // executors are cancelled directly by the server handling the request, and they may keep- // reporting the job as running while cancelling it asynchronously.- if (jobExecutor.isJobStateNodeLocal()- && job.status() == JobHandle.Status.CANCELLING+ // CANCELLING is a durable intent, including for shared runners. Retry until the runner+ // acknowledges cancellation or reports a terminal result. An acknowledged asynchronous+ // cancellation is left alone while it reports CANCELLING.+ if (job.status() == JobHandle.Status.CANCELLING&& (observed.status() == JobHandle.Status.QUEUED|| observed.status() == JobHandle.Status.STARTED)) {observed = cancelOwnedJob(metalake, job);@@ -1502,6 +1832,81 @@ public class JobManager implements JobOperationDispatcher {settledJob.status()));}+ // Settles a job whose submission was not recorded in time, with the job executor as the source of+ // truth: an execution found for the job is recorded, so the job is tracked like any other one.+ // Otherwise the job is marked as FAILED, or CANCELLED if it was cancelled. If the submission+ // returns after that, the server submitting the job cancels the execution.+ private void reconcilePendingSubmission(String metalake, JobEntity job, long now) {+ Optional<String> found = findSubmittedExecution(metalake, job);+ AtomicBoolean settled = new AtomicBoolean(false);+ Optional<JobEntity> settledJob =+ updateJobEntity(+ metalake,+ job,+ latestJobEntity -> {+ // The submission may have been recorded since the listJobs() snapshot.+ if (!isPendingSubmission(latestJobEntity)+ || isFinishedStatus(latestJobEntity.status())+ || !isSubmissionUnanswered(latestJobEntity, now)) {+ return latestJobEntity;+ }+ settled.set(true);+ if (found.isPresent()) {+ return withSubmittedExecution(latestJobEntity, found.get());+ }+ return toUpdatedStatusJobEntity(+ latestJobEntity,+ JobExecutionInfo.of(+ latestJobEntity.status() == JobHandle.Status.CANCELLING+ ? JobHandle.Status.CANCELLED+ : JobHandle.Status.FAILED));+ })+ .filter(updated -> settled.get());+ if (settledJob.isEmpty()) {+ return;+ }++ JobEntity updated = settledJob.get();+ if (found.isPresent()) {+ LOG.warn(+ "The submission of job {} under metalake {} was not recorded within {} ms, found its "+ + "execution {} in the job executor and recorded it",+ job.name(),+ metalake,+ submissionTimeoutInMs,+ found.get());+ if (updated.status() == JobHandle.Status.CANCELLING) {+ cancelSubmittedExecution(updated, found.get(), null);+ }+ } else {+ LOG.warn(+ "The submission of job {} under metalake {} was not recorded within {} ms and the job "+ + "executor has no execution of it, marking it as {}. This could be due to the "+ + "Gravitino server submitting the job having exited.",+ job.name(),+ metalake,+ submissionTimeoutInMs,+ updated.status());+ }+ }++ private Optional<String> findSubmittedExecution(String metalake, JobEntity job) {+ if (job.runtimeJobTemplate() == null) {+ return Optional.empty();+ }+ JobTemplate jobTemplate =+ DTOConverters.fromDTO(+ DTOConverters.fromRuntimeJobTemplateJson(job.runtimeJobTemplate(), job.name()));+ Optional<String> found =+ jobExecutor.findSubmittedJob(+ new JobContext(job.id(), metalake, jobStagingDir(job.id())), jobTemplate);+ return Objects.requireNonNull(found, "findSubmittedJob must return an Optional");+ }++ private boolean isSubmissionUnanswered(JobEntity job, long now) {+ return now - lastUpdatedTimeInMs(job) > submissionTimeoutInMs;+ }+private boolean isCancellationUnanswered(JobEntity job, long now) {return job.status() == JobHandle.Status.CANCELLING&& now - lastUpdatedTimeInMs(job) > cancellationTimeoutInMs;diff --git a/core/src/main/java/org/apache/gravitino/job/local/LocalJobExecutor.java b/core/src/main/java/org/apache/gravitino/job/local/LocalJobExecutor.javaindex 1b1a7cf37d..4e952360cd 100644--- a/core/src/main/java/org/apache/gravitino/job/local/LocalJobExecutor.java+++ b/core/src/main/java/org/apache/gravitino/job/local/LocalJobExecutor.java@@ -73,6 +73,7 @@ import org.apache.gravitino.connector.job.JobContext;import org.apache.gravitino.connector.job.JobExecutionInfo;import org.apache.gravitino.connector.job.JobExecutor;import org.apache.gravitino.connector.job.JobResourceUtils;+import org.apache.gravitino.connector.job.JobSubmissionRejectedException;import org.apache.gravitino.exceptions.NoSuchJobException;import org.apache.gravitino.job.JobHandle;import org.apache.gravitino.job.JobTemplate;@@ -326,28 +327,28 @@ public class LocalJobExecutor implements JobExecutor {@Overridepublic String submitJob(JobContext context, JobTemplate jobTemplate) {- // Validate the job can be launched before fetching its resources and queueing it, so that a- // misconfiguration is reported to the caller directly instead of only failing the job- // asynchronously in the worker thread.- if (jobTemplate instanceof SparkJobTemplate) {- SparkProcessBuilder.resolveSparkSubmit(configs);- }-- // The job runs in its staging directory, next to its localized resources.File workingDir = context.stagingDir();- JobTemplate localizedJobTemplate =- JobResourceUtils.localizeJobTemplate(jobTemplate, workingDir);+ JobTemplate localizedJobTemplate;+ try {+ // All preparation happens before accepting any work, so these failures are definitive.+ if (jobTemplate instanceof SparkJobTemplate) {+ SparkProcessBuilder.resolveSparkSubmit(configs);+ }+ localizedJobTemplate = JobResourceUtils.localizeJobTemplate(jobTemplate, workingDir);+ } catch (IllegalArgumentException e) {+ throw e;+ } catch (RuntimeException e) {+ throw new JobSubmissionRejectedException(+ "Failed to prepare the local job before queueing", e);+ }String newJobId = ownedJobIdPrefix + UUID.randomUUID();QueuedJob queuedJob = new QueuedJob(newJobId, localizedJobTemplate, workingDir);-synchronized (lock) {- // Add the job to the waiting queueif (!waitingQueue.offer(queuedJob)) {- throw new IllegalStateException(+ throw new JobSubmissionRejectedException("Waiting queue is full, cannot submit job: " + localizedJobTemplate);}-jobInfos.put(newJobId, JobExecutionInfo.of(JobHandle.Status.QUEUED));}diff --git a/core/src/test/java/org/apache/gravitino/connector/job/TestJobExecutor.java b/core/src/test/java/org/apache/gravitino/connector/job/TestJobExecutor.javaindex c967eacb33..191247cf40 100644--- a/core/src/test/java/org/apache/gravitino/connector/job/TestJobExecutor.java+++ b/core/src/test/java/org/apache/gravitino/connector/job/TestJobExecutor.java@@ -25,12 +25,15 @@ import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.Map;+import java.util.Optional;import org.apache.gravitino.exceptions.NoSuchJobException;import org.apache.gravitino.job.JobTemplate;import org.apache.gravitino.job.ShellJobTemplate;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.io.TempDir;+import org.mockito.MockedStatic;+import org.mockito.Mockito;public class TestJobExecutor {@@ -122,4 +125,33 @@ public class TestJobExecutor {IllegalArgumentException.class, () -> new JobContext(1L, " ", stagingDir));Assertions.assertThrows(IllegalArgumentException.class, () -> new JobContext(1L, "m", null));}++ @Test+ public void testSubmissionLookupFindsNothingByDefault() {+ JobExecutor executor = new UriJobExecutor();+ ShellJobTemplate template =+ ShellJobTemplate.builder().withName("shell_job").withExecutable("/bin/echo").build();+ Assertions.assertEquals(+ Optional.empty(),+ executor.findSubmittedJob(new JobContext(1L, "metalake", tempDir.toFile()), template));+ }++ @Test+ public void testLocalizationFailureIsConfirmedRejection() {+ JobContext context = new JobContext(1L, "metalake", tempDir.toFile());+ ShellJobTemplate template =+ ShellJobTemplate.builder().withName("shell_job").withExecutable("/bin/echo").build();+ RuntimeException downloadFailure = new RuntimeException("download failed");+ LocalPathJobExecutor executor = new LocalPathJobExecutor();+ try (MockedStatic<JobResourceUtils> resources = Mockito.mockStatic(JobResourceUtils.class)) {+ resources+ .when(() -> JobResourceUtils.localizeJobTemplate(template, context.stagingDir()))+ .thenThrow(downloadFailure);+ JobSubmissionRejectedException failure =+ Assertions.assertThrows(+ JobSubmissionRejectedException.class, () -> executor.submitJob(context, template));+ Assertions.assertSame(downloadFailure, failure.getCause());+ Assertions.assertNull(executor.submitted);+ }+ }}diff --git a/core/src/test/java/org/apache/gravitino/hook/TestJobHookDispatcher.java b/core/src/test/java/org/apache/gravitino/hook/TestJobHookDispatcher.javaindex d1f95b1a0b..13bc335811 100644--- a/core/src/test/java/org/apache/gravitino/hook/TestJobHookDispatcher.java+++ b/core/src/test/java/org/apache/gravitino/hook/TestJobHookDispatcher.java@@ -97,23 +97,12 @@ public class TestJobHookDispatcher {}@Test- public void testRunJobThrowsWhenSetOwnerFails() {- JobEntity mockJob = mock(JobEntity.class);- when(mockJob.nameIdentifier())- .thenReturn(NameIdentifier.of(NamespaceUtil.ofJob("test_metalake"), "test_job"));- when(mockJob.name()).thenReturn("test_job");- when(mockDispatcher.runJob(any(), any(), any())).thenReturn(mockJob);-- doThrow(new RuntimeException("Set owner failed"))- .when(mockOwnerDispatcher)- .setOwner(any(), any(), any(), any());-- RuntimeException thrown =- Assertions.assertThrows(- RuntimeException.class,- () -> hookDispatcher.runJob("test_metalake", "test_template", Collections.emptyMap()));- Assertions.assertEquals("Set owner failed", thrown.getMessage());- verify(mockDispatcher).runJob(any(), any(), any());+ public void testRunJobDoesNotResetTheOwnerAssignedBeforeSubmission() {+ JobEntity job = mock(JobEntity.class);+ when(mockDispatcher.runJob(any(), any(), any())).thenReturn(job);+ Assertions.assertSame(+ job, hookDispatcher.runJob("test_metalake", "test_template", Collections.emptyMap()));+ verify(mockOwnerDispatcher, never()).setOwner(any(), any(), any(), any());}@Testdiff --git a/core/src/test/java/org/apache/gravitino/job/LookupJobExecutor.java b/core/src/test/java/org/apache/gravitino/job/LookupJobExecutor.javanew file mode 100644index 0000000000..bd92d3f8e8--- /dev/null+++ b/core/src/test/java/org/apache/gravitino/job/LookupJobExecutor.java@@ -0,0 +1,30 @@+/*+ * 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.job;++import java.util.Optional;+import org.apache.gravitino.connector.job.JobContext;+import org.apache.gravitino.connector.job.JobExecutor;++// A job executor that implements findSubmittedJob(), for mocks: JobManager only keeps a job whose+// submission outcome is unknown if the job executor can find its execution.+interface LookupJobExecutor extends JobExecutor {+ @Override+ Optional<String> findSubmittedJob(JobContext context, JobTemplate jobTemplate);+}diff --git a/core/src/test/java/org/apache/gravitino/job/TestJobManager.java b/core/src/test/java/org/apache/gravitino/job/TestJobManager.javaindex e908f9f2a2..dba814d277 100644--- a/core/src/test/java/org/apache/gravitino/job/TestJobManager.java+++ b/core/src/test/java/org/apache/gravitino/job/TestJobManager.java@@ -22,6 +22,7 @@ import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyBoolean;import static org.mockito.ArgumentMatchers.anyInt;import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.doAnswer;import static org.mockito.Mockito.doNothing;import static org.mockito.Mockito.doReturn;import static org.mockito.Mockito.doThrow;@@ -31,6 +32,7 @@ import static org.mockito.Mockito.times;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;+import com.fasterxml.jackson.core.JsonProcessingException;import com.google.common.collect.ImmutableList;import com.google.common.collect.ImmutableMap;import com.google.common.collect.ImmutableSet;@@ -51,6 +53,7 @@ import java.util.UUID;import java.util.concurrent.CopyOnWriteArrayList;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.atomic.AtomicReference;import java.util.function.Function;import java.util.stream.Collectors;@@ -66,11 +69,14 @@ import org.apache.gravitino.EntityStore;import org.apache.gravitino.GravitinoEnv;import org.apache.gravitino.NameIdentifier;import org.apache.gravitino.Namespace;+import org.apache.gravitino.authorization.OwnerDispatcher;import org.apache.gravitino.connector.job.JobContext;import org.apache.gravitino.connector.job.JobExecutionInfo;import org.apache.gravitino.connector.job.JobExecutor;+import org.apache.gravitino.connector.job.JobSubmissionRejectedException;import org.apache.gravitino.dto.job.JobTemplateDTO;import org.apache.gravitino.dto.job.ShellJobTemplateDTO;+import org.apache.gravitino.dto.util.DTOConverters;import org.apache.gravitino.exceptions.InUseException;import org.apache.gravitino.exceptions.JobTemplateAlreadyExistsException;import org.apache.gravitino.exceptions.MetalakeInUseException;@@ -107,8 +113,10 @@ import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.mockito.ArgumentCaptor;+import org.mockito.InOrder;import org.mockito.MockedStatic;import org.mockito.Mockito;+import org.mockito.invocation.Invocation;public class TestJobManager {@@ -143,8 +151,12 @@ public class TestJobManager {private IdGenerator idGenerator;+ private OwnerDispatcher savedOwnerDispatcher;+@BeforeEach- public void setUp() throws IllegalAccessException {+ public void setUp() throws IllegalAccessException, IOException {+ savedOwnerDispatcher = GravitinoEnv.getInstance().internalOwnerDispatcher();+ FieldUtils.writeField(GravitinoEnv.getInstance(), "internalOwnerDispatcher", null, true);config = new Config(false) {};testStagingDir = "test_staging_dir_" + UUID.randomUUID().toString();config.set(Configs.JOB_STAGING_DIR, testStagingDir);@@ -153,9 +165,10 @@ public class TestJobManager {FieldUtils.writeField(GravitinoEnv.getInstance(), "lockManager", new LockManager(config), true);entityStore = Mockito.mock(EntityStore.class);- jobExecutor = Mockito.mock(JobExecutor.class);+ jobExecutor = Mockito.mock(LookupJobExecutor.class);// Mocks don't call the default interface methods, so stub the defaults explicitly.when(jobExecutor.ownsJob(any())).thenReturn(true);+ stubEntityStoreUpdateToApplyToRegisteredJob();idGenerator = new RandomIdGenerator();JobManager jm = new JobManager(config, entityStore, idGenerator, jobExecutor);jobManager = Mockito.spy(jm);@@ -199,6 +212,8 @@ public class TestJobManager {Mockito.reset(entityStore, jobManager);// Clean up resources if necessaryjobManager.close();+ FieldUtils.writeField(+ GravitinoEnv.getInstance(), "internalOwnerDispatcher", savedOwnerDispatcher, true);FileUtils.deleteDirectory(new File(testStagingDir));if (mockedMetalake != null) {mockedMetalake.close();@@ -225,8 +240,6 @@ public class TestJobManager {for (Entity.EntityType parent :List.of(Entity.EntityType.METALAKE, Entity.EntityType.JOB_TEMPLATE)) {Mockito.reset(entityStore, jobExecutor);- String executionId = "submitted_" + parent.name();- when(jobExecutor.submitJob(any(), any())).thenReturn(executionId);NoSuchEntityException missing = new NoSuchEntityException("Parent was deleted: %s", parent);doThrow(missing).when(entityStore).put(any(JobEntity.class), eq(false));@@ -235,21 +248,90 @@ public class TestJobManager {NoSuchJobTemplateException.class,() -> jobManager.runJob(metalake, template.name(), Collections.emptyMap()));Assertions.assertSame(missing, failure.getCause());- verify(jobExecutor, times(1)).submitJob(any(), any());- verify(jobExecutor, never()).cancelJob(any());+ // The job is registered before it is submitted, so nothing runs for it.+ verify(jobExecutor, never()).submitJob(any(), any());verify(entityStore, times(1)).put(any(JobEntity.class), eq(false));+ assertNoJobStagingDir();}}@Test- public void testRunJobCancelsExecutionWhenRegistrationConflicts() throws Exception {+ public void testRunJobReportsRegistrationConflictBeforeSubmission() throws Exception {JobTemplateEntity template = newShellJobTemplateEntity("shell_job", "A shell job template");doReturn(template).when(jobManager).getJobTemplate(metalake, template.name());- Mockito.reset(entityStore, jobExecutor);- when(jobExecutor.submitJob(any(), any())).thenReturn("submitted_conflict");OptimisticLockException conflict = new OptimisticLockException("lock wait timeout");doThrow(conflict).when(entityStore).put(any(JobEntity.class), eq(false));+ // Nothing has been submitted, so the conflict is reported as is and the caller can retry.+ Assertions.assertSame(+ conflict,+ Assertions.assertThrows(+ OptimisticLockException.class,+ () -> jobManager.runJob(metalake, template.name(), Collections.emptyMap())));+ verify(jobExecutor, never()).submitJob(any(), any());+ assertNoJobStagingDir();+ }++ @Test+ public void testRunJobRegistersJobBeforeSubmission() throws Exception {+ JobTemplateEntity template = newShellJobTemplateEntity("shell_job", "A shell job template");+ doReturn(template).when(jobManager).getJobTemplate(metalake, template.name());+ AtomicReference<JobEntity> registeredAtSubmission = new AtomicReference<>();+ when(jobExecutor.submitJob(any(), any()))+ .thenAnswer(+ invocation -> {+ registeredAtSubmission.set(lastRegisteredJob());+ return "submitted_execution";+ });++ JobEntity job = jobManager.runJob(metalake, template.name(), Collections.emptyMap());++ JobEntity registered = registeredAtSubmission.get();+ Assertions.assertNotNull(registered, "The job must be registered before it is submitted");+ Assertions.assertEquals(job.id(), registered.id());+ Assertions.assertEquals(JobHandle.Status.QUEUED, registered.status());+ Assertions.assertEquals(+ JobManager.pendingSubmissionExecutionId(job.id()), registered.jobExecutionId());+ Assertions.assertEquals(registered.runtimeJobTemplate(), job.runtimeJobTemplate());+ // The submission is recorded on the registered job.+ Assertions.assertEquals("submitted_execution", job.jobExecutionId());+ Assertions.assertEquals(JobHandle.Status.QUEUED, job.status());+ Assertions.assertEquals(registered.auditInfo(), job.auditInfo());+ verify(jobExecutor, never()).cancelJob(any());+ }++ @Test+ public void testRunJobRetriesRecordingSubmissionOnConflict() throws Exception {+ JobTemplateEntity template = newShellJobTemplateEntity("shell_job", "A shell job template");+ doReturn(template).when(jobManager).getJobTemplate(metalake, template.name());+ when(jobExecutor.submitJob(any(), any())).thenReturn("submitted_execution");+ AtomicInteger attempts = new AtomicInteger();+ when(entityStore.update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any()))+ .thenAnswer(+ invocation -> {+ if (attempts.incrementAndGet() == 1) {+ throw new OptimisticLockException("job changed");+ }+ Function<JobEntity, JobEntity> updater = invocation.getArgument(3);+ return updater.apply(lastRegisteredJob());+ });++ JobEntity job = jobManager.runJob(metalake, template.name(), Collections.emptyMap());++ Assertions.assertEquals("submitted_execution", job.jobExecutionId());+ Assertions.assertEquals(2, attempts.get());+ verify(jobExecutor, never()).cancelJob(any());+ }++ @Test+ public void testRunJobCancelsExecutionWhenSubmissionCannotBeRecorded() throws Exception {+ JobTemplateEntity template = newShellJobTemplateEntity("shell_job", "A shell job template");+ doReturn(template).when(jobManager).getJobTemplate(metalake, template.name());+ when(jobExecutor.submitJob(any(), any())).thenReturn("submitted_conflict");+ OptimisticLockException conflict = new OptimisticLockException("lock wait timeout");+ when(entityStore.update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any()))+ .thenThrow(conflict);+// Cancellation cannot guarantee that the execution has not already performed work.RuntimeException failure =Assertions.assertThrows(@@ -259,9 +341,12 @@ public class TestJobManager {Assertions.assertSame(conflict, failure.getCause());Assertions.assertTrue(failure.getMessage().contains("submitted_conflict"));Assertions.assertTrue(failure.getMessage().contains("Check the execution before retrying"));+ // Three recording attempts and three attempts to retain cancellation intent are bounded.+ verify(entityStore, times(6))+ .update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any());verify(jobExecutor, times(1)).cancelJob("submitted_conflict");- // A failed cancellation is kept on the cause for diagnosis and is not a retryable conflict.+ // A failed cancellation is kept for diagnosis and is not a retryable conflict.Mockito.reset(jobExecutor);when(jobExecutor.submitJob(any(), any())).thenReturn("submitted_conflict_2");RuntimeException cancelFailure = new RuntimeException("executor unavailable");@@ -273,7 +358,216 @@ public class TestJobManager {Assertions.assertFalse(second instanceof OptimisticLockException);Assertions.assertSame(conflict, second.getCause());Assertions.assertTrue(second.getMessage().contains("submitted_conflict_2"));- Assertions.assertTrue(List.of(second.getCause().getSuppressed()).contains(cancelFailure));+ Assertions.assertTrue(List.of(second.getSuppressed()).contains(cancelFailure));+ }++ @Test+ public void testRunJobKeepsExecutionIdWithCancellationAfterRecordingConflicts() throws Exception {+ JobTemplateEntity template = newShellJobTemplateEntity("shell_job", "A shell job template");+ doReturn(template).when(jobManager).getJobTemplate(metalake, template.name());+ when(jobExecutor.submitJob(any(), any())).thenReturn("submitted_conflict");+ AtomicInteger attempts = new AtomicInteger();+ AtomicReference<JobHandle.Status> latestStatus =+ new AtomicReference<>(JobHandle.Status.CANCELLING);+ AtomicReference<JobEntity> written = new AtomicReference<>();+ when(entityStore.update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any()))+ .thenAnswer(+ invocation -> {+ if (attempts.incrementAndGet() <= 3) {+ throw new OptimisticLockException("job changed");+ }+ Function<JobEntity, JobEntity> updater = invocation.getArgument(3);+ written.set(updater.apply(withStatus(lastRegisteredJob(), latestStatus.get())));+ return written.get();+ });++ // The job was cancelled while its execution id was being recorded. The execution id is kept+ // with the cancellation, so the status pull retries cancelling that execution.+ Assertions.assertThrows(+ RuntimeException.class,+ () -> jobManager.runJob(metalake, template.name(), Collections.emptyMap()));+ Assertions.assertEquals("submitted_conflict", written.get().jobExecutionId());+ Assertions.assertEquals(JobHandle.Status.CANCELLING, written.get().status());+ verify(jobExecutor, times(1)).cancelJob("submitted_conflict");++ // Another server settled the job meanwhile, which is left as is.+ attempts.set(0);+ latestStatus.set(JobHandle.Status.FAILED);+ Assertions.assertThrows(+ RuntimeException.class,+ () -> jobManager.runJob(metalake, template.name(), Collections.emptyMap()));+ Assertions.assertEquals(JobHandle.Status.FAILED, written.get().status());+ Assertions.assertEquals(+ JobManager.pendingSubmissionExecutionId(written.get().id()),+ written.get().jobExecutionId());+ verify(jobExecutor, times(2)).cancelJob("submitted_conflict");+ }++ @Test+ public void testRunJobCancelsExecutionOfJobSettledDuringSubmission() throws Exception {+ JobTemplateEntity template = newShellJobTemplateEntity("shell_job", "A shell job template");+ doReturn(template).when(jobManager).getJobTemplate(metalake, template.name());+ when(jobExecutor.submitJob(any(), any())).thenReturn("submitted_late");+ // The submission took so long that the status pull marked the job as FAILED meanwhile.+ when(entityStore.update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any()))+ .thenAnswer(+ invocation -> {+ Function<JobEntity, JobEntity> updater = invocation.getArgument(3);+ return updater.apply(withStatus(lastRegisteredJob(), JobHandle.Status.FAILED));+ });++ RuntimeException failure =+ Assertions.assertThrows(+ RuntimeException.class,+ () -> jobManager.runJob(metalake, template.name(), Collections.emptyMap()));+ Assertions.assertTrue(failure.getMessage().contains("submitted_late"));+ // The message tells why the job was settled and how to avoid it.+ Assertions.assertTrue(failure.getMessage().contains("marked it as FAILED"));+ Assertions.assertTrue(failure.getMessage().contains("gravitino.job.statusPullIntervalInMs"));+ verify(jobExecutor, times(1)).cancelJob("submitted_late");++ // Another server found another execution for the job and recorded it meanwhile.+ Mockito.reset(jobExecutor);+ when(jobExecutor.submitJob(any(), any())).thenReturn("submitted_late_2");+ when(entityStore.update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any()))+ .thenAnswer(+ invocation -> {+ Function<JobEntity, JobEntity> updater = invocation.getArgument(3);+ return updater.apply(withExecutionId(lastRegisteredJob(), "found_execution"));+ });+ RuntimeException recordedElsewhere =+ Assertions.assertThrows(+ RuntimeException.class,+ () -> jobManager.runJob(metalake, template.name(), Collections.emptyMap()));+ Assertions.assertTrue(+ recordedElsewhere.getMessage().contains("recorded execution found_execution for it"));+ verify(jobExecutor, times(1)).cancelJob("submitted_late_2");+ verify(jobExecutor, never()).cancelJob("found_execution");+ }++ @Test+ public void testRunJobCancelsExecutionOfJobGoneBeforeRecording() throws Exception {+ JobTemplateEntity template = newShellJobTemplateEntity("shell_job", "A shell job template");+ doReturn(template).when(jobManager).getJobTemplate(metalake, template.name());+ when(jobExecutor.submitJob(any(), any())).thenReturn("submitted_orphan");+ // The job is gone by the time its submission is recorded, e.g. its metalake was dropped.+ NoSuchEntityException gone = new NoSuchEntityException("Job was deleted");+ when(entityStore.update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any()))+ .thenThrow(gone);++ RuntimeException failure =+ Assertions.assertThrows(+ RuntimeException.class,+ () -> jobManager.runJob(metalake, template.name(), Collections.emptyMap()));+ Assertions.assertSame(gone, failure.getCause());+ Assertions.assertTrue(failure.getMessage().contains("submitted_orphan"));+ Assertions.assertTrue(failure.getMessage().contains("could not be recorded"));+ // Only a conflict is retried.+ verify(entityStore, times(1))+ .update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any());+ verify(jobExecutor, times(1)).cancelJob("submitted_orphan");+ }++ @Test+ public void testRunJobDeletesJobWhoseSubmissionFails() throws Exception {+ JobTemplateEntity template = newShellJobTemplateEntity("shell_job", "A shell job template");+ doReturn(template).when(jobManager).getJobTemplate(metalake, template.name());+ RuntimeException executorFailure =+ new JobSubmissionRejectedException("executor rejected the job");+ when(jobExecutor.submitJob(any(), any())).thenThrow(executorFailure);++ RuntimeException failure =+ Assertions.assertThrows(+ RuntimeException.class,+ () -> jobManager.runJob(metalake, template.name(), Collections.emptyMap()));+ Assertions.assertSame(executorFailure, failure);+ JobEntity registered = lastRegisteredJob();+ verify(entityStore, times(1))+ .delete(NameIdentifierUtil.ofJob(metalake, registered.name()), Entity.EntityType.JOB);+ assertNoJobStagingDir();++ // A failed deletion keeps its original cause, and the known rejection is settled as FAILED+ // without a lookup in the job executor.+ IOException deleteFailure = new IOException("store unavailable");+ doThrow(deleteFailure).when(entityStore).delete(any(), eq(Entity.EntityType.JOB));+ RuntimeException second =+ Assertions.assertThrows(+ RuntimeException.class,+ () -> jobManager.runJob(metalake, template.name(), Collections.emptyMap()));+ Assertions.assertSame(executorFailure, second);+ Assertions.assertTrue(List.of(second.getSuppressed()).contains(deleteFailure));+ JobEntity rejected = lastRegisteredJob();+ Assertions.assertEquals(+ JobHandle.Status.FAILED, captureUpdatedJobEntity(rejected, rejected).status());+ assertNoJobStagingDir();+ verify(jobExecutor, never()).findSubmittedJob(any(), any());+ verify(jobExecutor, never()).cancelJob(any());+ }++ @Test+ public void testPullJobStatusLeavesSlowSubmissionToThisServer() throws Exception {+ JobTemplateEntity template = newShellJobTemplateEntity("shell_job", "A shell job template");+ doReturn(template).when(jobManager).getJobTemplate(metalake, template.name());+ long timeoutInMs = 3 * config.get(Configs.JOB_STATUS_PULL_INTERVAL_IN_MS);+ mockedMetalake+ .when(() -> MetalakeManager.listInUseMetalakes(entityStore))+ .thenReturn(ImmutableList.of(metalake));+ // The registered job, as if its submission took longer than the timeout.+ doAnswer(+ invocation ->+ ImmutableList.of(+ copyOf(lastRegisteredJob())+ .withAuditInfo(+ AuditInfo.builder()+ .withCreator("test")+ .withCreateTime(+ Instant.now().minusMillis(timeoutInMs).minusSeconds(10))+ .build())+ .build()))+ .when(jobManager)+ .listJobs(metalake, Optional.empty());+ when(jobExecutor.submitJob(any(), any()))+ .thenAnswer(+ invocation -> {+ // This server's own status pull runs while it is still submitting the job.+ jobManager.pullAndUpdateJobStatus();+ return "slow_execution";+ });++ JobEntity job = jobManager.runJob(metalake, template.name(), Collections.emptyMap());++ // The status pull left the job to its submission, which recorded it.+ Assertions.assertEquals("slow_execution", job.jobExecutionId());+ verify(jobExecutor, never()).findSubmittedJob(any(), any());+ verify(jobExecutor, never()).cancelJob(any());+ verify(entityStore, times(1))+ .update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any());++ // Once the submission is over, a job left pending, e.g. as it couldn't be recorded, is settled+ // by the status pull of this server too.+ doReturn(Optional.empty()).when(jobExecutor).findSubmittedJob(any(), any());+ jobManager.pullAndUpdateJobStatus();+ verify(jobExecutor, times(1)).findSubmittedJob(any(), any());+ }++ @Test+ public void testRunJobCancelsExecutionOfJobCancelledDuringSubmission() throws Exception {+ JobTemplateEntity template = newShellJobTemplateEntity("shell_job", "A shell job template");+ doReturn(template).when(jobManager).getJobTemplate(metalake, template.name());+ when(jobExecutor.submitJob(any(), any())).thenReturn("submitted_cancelled");+ // The job was cancelled while it was being submitted.+ when(entityStore.update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any()))+ .thenAnswer(+ invocation -> {+ Function<JobEntity, JobEntity> updater = invocation.getArgument(3);+ return updater.apply(withStatus(lastRegisteredJob(), JobHandle.Status.CANCELLING));+ });++ JobEntity job = jobManager.runJob(metalake, template.name(), Collections.emptyMap());++ Assertions.assertEquals("submitted_cancelled", job.jobExecutionId());+ Assertions.assertEquals(JobHandle.Status.CANCELLING, job.status());+ verify(jobExecutor, times(1)).cancelJob("submitted_cancelled");}@Test@@ -869,10 +1163,13 @@ public class TestJobManager {doThrow(new IOException("Entity store error")).when(entityStore).put(any(JobEntity.class), anyBoolean());+ Mockito.clearInvocations(jobExecutor);Assertions.assertThrows(RuntimeException.class,() -> jobManager.runJob(metalake, "shell_job", Collections.emptyMap()));+ // A job that can't be registered is never submitted.+ verify(jobExecutor, never()).submitJob(any(), any());}@Test@@ -927,11 +1224,15 @@ public class TestJobManager {() -> jobManager.runJob(metalake, "shell_job", Collections.emptyMap()));Assertions.assertSame(rejection, e);- // No job entity is registered and the staging directory of the rejected job is removed.- verify(entityStore, never()).put(any(JobEntity.class), anyBoolean());- File jobRunsDir = jobManager.jobStagingDir(0L).getParentFile();- Assertions.assertTrue(jobRunsDir.isDirectory(), "The job staging directory was never created");- Assertions.assertArrayEquals(new String[0], jobRunsDir.list());+ // The job registered before the submission is removed, and so is the staging directory of+ // the rejected job.+ ArgumentCaptor<JobEntity> registered = ArgumentCaptor.forClass(JobEntity.class);+ verify(entityStore, times(1)).put(registered.capture(), anyBoolean());+ verify(entityStore, times(1))+ .delete(+ NameIdentifierUtil.ofJob(metalake, registered.getValue().name()),+ Entity.EntityType.JOB);+ assertNoJobStagingDir();}@Test@@ -2055,21 +2356,20 @@ public class TestJobManager {}@Test- public void testPullJobStatusDoesNotRecancelJobOfNonNodeLocalExecutor() throws IOException {- // An external job executor is cancelled directly by the server handling the cancel request,- // and may keep reporting the job as running while cancelling it asynchronously. The status- // pull must not cancel it again on every poll.+ public void testPullJobStatusDoesNotRepeatAcknowledgedCancellation() throws IOException {+ // Once the runner acknowledges the intent, monitor its asynchronous cancellation instead+ // of issuing the same request on every pull.JobEntity job =newJobEntity("external-job-1", JobHandle.Status.CANCELLING, Instant.now(), null);mockListActiveJobs(job);when(jobExecutor.getJobExecutionInfo(job.jobExecutionId()))- .thenReturn(JobExecutionInfo.of(JobHandle.Status.STARTED));+ .thenReturn(JobExecutionInfo.of(JobHandle.Status.CANCELLING));stubEntityStoreUpdateToApply(job);Assertions.assertDoesNotThrow(() -> jobManager.pullAndUpdateJobStatus());verify(jobExecutor, never()).cancelJob(any());- // The observed STARTED status never regresses the CANCELLING job, so nothing is written.+ // The acknowledged CANCELLING status is unchanged, so nothing is written.verify(entityStore, never()).update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any());}@@ -2109,6 +2409,244 @@ public class TestJobManager {verify(jobExecutor, never()).cancelJob(any());}+ @Test+ public void testCancelJobBeingSubmitted() throws IOException {+ JobEntity job =+ newJobEntity(+ JobManager.pendingSubmissionExecutionId(1L),+ JobHandle.Status.QUEUED,+ Instant.now(),+ null);+ when(jobManager.getJob(metalake, job.name(), false)).thenReturn(job);+ stubEntityStoreUpdateToApply(job);++ // The job has no execution yet, so it's only marked as CANCELLING, and the server submitting it+ // cancels the execution once it's submitted.+ JobEntity cancelling = jobManager.cancelJob(metalake, job.name());+ Assertions.assertEquals(JobHandle.Status.CANCELLING, cancelling.status());+ Assertions.assertEquals(job.jobExecutionId(), cancelling.jobExecutionId());+ verify(jobExecutor, never()).ownsJob(any());+ verify(jobExecutor, never()).cancelJob(any());+ }++ @Test+ public void testCancelJobWhoseSubmissionIsRecordedConcurrently() throws IOException {+ JobEntity job =+ newJobEntity(+ JobManager.pendingSubmissionExecutionId(1L),+ JobHandle.Status.QUEUED,+ Instant.now(),+ null);+ when(jobManager.getJob(metalake, job.name(), false)).thenReturn(job);+ // The submission is recorded after the job is read, while it's still QUEUED, so the server+ // submitting it won't cancel it.+ JobEntity submitted = withExecutionId(job, "submitted_execution");+ stubEntityStoreUpdateToApply(submitted);++ JobEntity cancelling = jobManager.cancelJob(metalake, job.name());+ Assertions.assertEquals(JobHandle.Status.CANCELLING, cancelling.status());+ Assertions.assertEquals("submitted_execution", cancelling.jobExecutionId());+ verify(jobExecutor, times(1)).cancelJob("submitted_execution");++ // An execution that is already gone is settled by the status pull.+ doThrow(new NoSuchJobException("gone")).when(jobExecutor).cancelJob("submitted_execution");+ Assertions.assertEquals(+ JobHandle.Status.CANCELLING, jobManager.cancelJob(metalake, job.name()).status());++ // Nobody would cancel the execution again, so a failure to cancel it is reported.+ RuntimeException cancelFailure = new RuntimeException("executor unavailable");+ doThrow(cancelFailure).when(jobExecutor).cancelJob("submitted_execution");+ RuntimeException failure =+ Assertions.assertThrows(+ RuntimeException.class, () -> jobManager.cancelJob(metalake, job.name()));+ Assertions.assertSame(cancelFailure, failure.getCause());+ Assertions.assertTrue(failure.getMessage().contains("submitted_execution"));+ Assertions.assertTrue(failure.getMessage().contains("The status pull will retry"));++ // A repeated request retries the durable cancellation without resetting its metadata.+ Mockito.clearInvocations(jobExecutor);+ when(jobManager.getJob(metalake, job.name(), false))+ .thenReturn(withStatus(submitted, JobHandle.Status.CANCELLING));+ Assertions.assertThrows(+ RuntimeException.class, () -> jobManager.cancelJob(metalake, job.name()));+ verify(jobExecutor, times(1)).cancelJob("submitted_execution");+ }++ @Test+ public void testGetJobOutputOfJobBeingSubmitted() {+ JobEntity job =+ newJobEntity(+ JobManager.pendingSubmissionExecutionId(1L),+ JobHandle.Status.QUEUED,+ Instant.now(),+ null);+ doReturn(job).when(jobManager).getJob(metalake, job.name(), false);+ mockedMetalake+ .when(() -> MetalakeManager.checkMetalake(metalakeIdent, entityStore))+ .thenAnswer(a -> null);+ Assertions.assertDoesNotThrow(+ () -> {+ when(entityStore.get(+ NameIdentifierUtil.ofJob(metalake, job.name()),+ Entity.EntityType.JOB,+ JobEntity.class))+ .thenReturn(job);+ });++ JobEntity withOutput = jobManager.getJob(metalake, job.name(), true, null, null);+ Assertions.assertSame(job, withOutput);+ verify(jobExecutor, never()).getJobStdout(any(), anyInt(), anyInt());+ verify(jobExecutor, never()).getJobStderr(any(), anyInt(), anyInt());+ }++ @Test+ public void testPullJobStatusLeavesRecentSubmissionToSubmitter() throws IOException {+ JobEntity job =+ newJobEntity(+ JobManager.pendingSubmissionExecutionId(1L),+ JobHandle.Status.QUEUED,+ Instant.now(),+ null);+ mockListActiveJobs(job);++ Assertions.assertDoesNotThrow(() -> jobManager.pullAndUpdateJobStatus());++ verify(entityStore, never())+ .update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any());+ verify(jobExecutor, never()).ownsJob(any());+ verify(jobExecutor, never()).getJobExecutionInfo(any());+ verify(jobExecutor, never()).findSubmittedJob(any(), any());+ }++ @Test+ public void testPullJobStatusRecordsExecutionFoundForUnansweredSubmission() throws IOException {+ JobEntity job = pendingSubmissionBeyondTimeout(JobHandle.Status.QUEUED);+ mockListActiveJobs(job);+ ArgumentCaptor<JobContext> context = ArgumentCaptor.forClass(JobContext.class);+ ArgumentCaptor<JobTemplate> template = ArgumentCaptor.forClass(JobTemplate.class);+ when(jobExecutor.findSubmittedJob(context.capture(), template.capture()))+ .thenReturn(Optional.of("found_execution"));+ stubEntityStoreUpdateToApply(job, job);++ Assertions.assertDoesNotThrow(() -> jobManager.pullAndUpdateJobStatus());++ // The job executor is the source of truth: the execution it has is recorded and tracked.+ JobEntity recorded = captureUpdatedJobEntity(job, job);+ Assertions.assertEquals("found_execution", recorded.jobExecutionId());+ Assertions.assertEquals(JobHandle.Status.QUEUED, recorded.status());+ // It's looked up with the same context and runtime job template as the submission.+ Assertions.assertEquals(job.id(), context.getValue().jobId());+ Assertions.assertEquals(metalake, context.getValue().metalake());+ Assertions.assertEquals(jobManager.jobStagingDir(job.id()), context.getValue().stagingDir());+ Assertions.assertEquals("shell_job", template.getValue().name());+ verify(jobExecutor, never()).cancelJob(any());+ }++ @Test+ public void testPullJobStatusCancelsExecutionFoundForCancelledSubmission() throws IOException {+ JobEntity job = pendingSubmissionBeyondTimeout(JobHandle.Status.CANCELLING);+ mockListActiveJobs(job);+ when(jobExecutor.findSubmittedJob(any(), any())).thenReturn(Optional.of("found_execution"));+ stubEntityStoreUpdateToApply(job, job);++ Assertions.assertDoesNotThrow(() -> jobManager.pullAndUpdateJobStatus());++ JobEntity recorded = captureUpdatedJobEntity(job, job);+ Assertions.assertEquals("found_execution", recorded.jobExecutionId());+ Assertions.assertEquals(JobHandle.Status.CANCELLING, recorded.status());+ verify(jobExecutor, times(1)).cancelJob("found_execution");+ }++ @Test+ public void testPullJobStatusSettlesUnansweredSubmissionWithoutExecution() throws IOException {+ for (JobHandle.Status status : List.of(JobHandle.Status.QUEUED, JobHandle.Status.CANCELLING)) {+ Mockito.clearInvocations(entityStore, jobExecutor);+ JobEntity job = pendingSubmissionBeyondTimeout(status);+ mockListActiveJobs(job);+ when(jobExecutor.findSubmittedJob(any(), any())).thenReturn(Optional.empty());+ stubEntityStoreUpdateToApply(job, job);++ long beforePull = System.currentTimeMillis();+ Assertions.assertDoesNotThrow(() -> jobManager.pullAndUpdateJobStatus());++ JobEntity settled = captureUpdatedJobEntity(job, job);+ Assertions.assertEquals(+ status == JobHandle.Status.CANCELLING+ ? JobHandle.Status.CANCELLED+ : JobHandle.Status.FAILED,+ settled.status());+ Assertions.assertTrue(settled.finishedAt() >= beforePull);+ verify(jobExecutor, never()).getJobExecutionInfo(any());+ verify(jobExecutor, never()).cancelJob(any());+ }+ }++ @Test+ public void testPullJobStatusDoesNotSettleSubmissionRecordedConcurrently() throws IOException {+ JobEntity job = pendingSubmissionBeyondTimeout(JobHandle.Status.QUEUED);+ mockListActiveJobs(job);+ when(jobExecutor.findSubmittedJob(any(), any())).thenReturn(Optional.empty());+ // The submitting server recorded the submission after the job was listed.+ JobEntity submitted = withExecutionId(job, "submitted_execution");+ stubEntityStoreUpdateToApply(job, submitted);++ Assertions.assertDoesNotThrow(() -> jobManager.pullAndUpdateJobStatus());++ Assertions.assertSame(submitted, captureUpdatedJobEntity(job, submitted));+ }++ @Test+ public void testPullJobStatusRetriesSubmissionLookupFailure() throws IOException {+ JobEntity job = pendingSubmissionBeyondTimeout(JobHandle.Status.QUEUED);+ JobEntity other = newJobEntity("other_execution", JobHandle.Status.QUEUED, Instant.now(), null);+ mockListActiveJobs(job, other);+ when(jobExecutor.findSubmittedJob(any(), any()))+ .thenThrow(new RuntimeException("executor unreachable"));+ when(jobExecutor.getJobExecutionInfo("other_execution"))+ .thenReturn(JobExecutionInfo.of(JobHandle.Status.STARTED));+ stubEntityStoreUpdateToApply(other, other);++ Assertions.assertDoesNotThrow(() -> jobManager.pullAndUpdateJobStatus());++ // The job is left for the next pull, and the other jobs are still pulled.+ verify(entityStore, never())+ .update(+ eq(NameIdentifierUtil.ofJob(metalake, job.name())),+ eq(JobEntity.class),+ eq(Entity.EntityType.JOB),+ any());+ Assertions.assertEquals(+ JobHandle.Status.STARTED, captureUpdatedJobEntity(other, other).status());+ }++ private JobEntity pendingSubmissionBeyondTimeout(JobHandle.Status status) {+ long timeoutInMs = 3 * config.get(Configs.JOB_STATUS_PULL_INTERVAL_IN_MS);+ long id = idGenerator.nextId();+ JobEntity job =+ newJobEntity(+ id,+ JobManager.pendingSubmissionExecutionId(id),+ status,+ Instant.now().minusMillis(timeoutInMs).minusSeconds(10),+ null);+ ShellJobTemplate runtimeTemplate =+ ShellJobTemplate.builder().withName("shell_job").withExecutable("/bin/echo").build();+ String runtimeJobTemplate;+ try {+ runtimeJobTemplate =+ JsonUtils.anyFieldMapper()+ .writeValueAsString(+ DTOConverters.toDTO(runtimeTemplate, DTOConverters.toDTO(job.auditInfo())));+ } catch (JsonProcessingException e) {+ throw new RuntimeException(e);+ }+ return copyOf(job).withRuntimeJobTemplate(runtimeJobTemplate).build();+ }++ private static JobEntity withExecutionId(JobEntity job, String jobExecutionId) {+ return copyOf(job).withJobExecutionId(jobExecutionId).build();+ }+@Testpublic void testCancelJobNotFoundInOwnedExecutor() throws IOException {mockedMetalake@@ -3520,6 +4058,55 @@ public class TestJobManager {});}+ // runJob registers the job with entityStore.put() and then records its submission with+ // entityStore.update(). This stubs that update to apply to the job registered last, mirroring+ // what the real JobMetaService.updateJob would read from storage.+ @SuppressWarnings("unchecked")+ private void stubEntityStoreUpdateToApplyToRegisteredJob() throws IOException {+ when(entityStore.update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any()))+ .thenAnswer(+ invocation -> {+ Function<JobEntity, JobEntity> updater = invocation.getArgument(3);+ JobEntity registeredJob = lastRegisteredJob();+ return registeredJob == null ? null : updater.apply(registeredJob);+ });+ }++ private void assertNoJobStagingDir() {+ File jobRunsDir = jobManager.jobStagingDir(0L).getParentFile();+ Assertions.assertTrue(jobRunsDir.isDirectory(), "The job staging directory was never created");+ Assertions.assertArrayEquals(new String[0], jobRunsDir.list());+ }++ private static JobEntity withStatus(JobEntity job, JobHandle.Status status) {+ return copyOf(job).withStatus(status).build();+ }++ private static JobEntity.Builder copyOf(JobEntity job) {+ return JobEntity.builder()+ .withId(job.id())+ .withJobExecutionId(job.jobExecutionId())+ .withNamespace(job.namespace())+ .withJobTemplateName(job.jobTemplateName())+ .withStatus(job.status())+ .withStartedAt(job.startedAt())+ .withFinishedAt(job.finishedAt())+ .withAuditInfo(job.auditInfo())+ .withRuntimeJobTemplate(job.runtimeJobTemplate());+ }++ @Nullable+ private JobEntity lastRegisteredJob() {+ JobEntity registeredJob = null;+ for (Invocation invocation : Mockito.mockingDetails(entityStore).getInvocations()) {+ if (invocation.getMethod().getName().equals("put")+ && invocation.getArgument(0) instanceof JobEntity) {+ registeredJob = invocation.getArgument(0);+ }+ }+ return registeredJob;+ }+@SuppressWarnings("unchecked")private JobEntity captureUpdatedJobEntity(JobEntity latestJobEntity) throws IOException {ArgumentCaptor<Function<JobEntity, JobEntity>> captor = ArgumentCaptor.forClass(Function.class);@@ -3571,4 +4158,187 @@ public class TestJobManager {manager.cleanUpExecutor.shutdownNow();}}++ @Test+ public void testUnknownSubmissionOutcomeKeepsRecoveryRecord() throws Exception {+ JobTemplateEntity template = newShellJobTemplateEntity("shell_job", "A shell job template");+ doReturn(template).when(jobManager).getJobTemplate(metalake, template.name());+ when(jobExecutor.submitJob(any(), any()))+ .thenThrow(+ new RuntimeException("runner accepted execution but response and cleanup failed"));+ Assertions.assertThrows(+ RuntimeException.class,+ () -> jobManager.runJob(metalake, template.name(), Collections.emptyMap()));+ verify(entityStore, never()).delete(any(), eq(Entity.EntityType.JOB));+ }++ @Test+ public void testUnknownSubmissionOutcomeOfJobGoneIsNotRetried() throws Exception {+ JobTemplateEntity template = newShellJobTemplateEntity("shell_job", "A shell job template");+ doReturn(template).when(jobManager).getJobTemplate(metalake, template.name());+ RuntimeException executorFailure = new RuntimeException("runner response lost");+ when(jobExecutor.submitJob(any(), any())).thenThrow(executorFailure);+ // The job is gone before its cancellation is recorded, e.g. its metalake was dropped.+ when(entityStore.update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any()))+ .thenThrow(new NoSuchEntityException("Job was deleted"));++ RuntimeException failure =+ Assertions.assertThrows(+ RuntimeException.class,+ () -> jobManager.runJob(metalake, template.name(), Collections.emptyMap()));+ Assertions.assertSame(executorFailure, failure.getCause());+ // A gone job is not a failure to record the cancellation.+ Assertions.assertEquals(0, failure.getSuppressed().length);+ // Only a conflict is retried.+ verify(entityStore, times(1))+ .update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any());+ verify(entityStore, never()).delete(any(), eq(Entity.EntityType.JOB));+ }++ @Test+ public void testRunJobDeletesJobWhenExecutorCannotFindSubmissions() throws Exception {+ // A job executor that doesn't implement findSubmittedJob() can't help recover an execution+ // the failed submission may have left, so the job is removed as before.+ RuntimeException executorFailure = new IllegalStateException("runner response lost");+ JobExecutor executor =+ new JobExecutor() {+ @Override+ public void initialize(Map<String, String> configs) {}++ @Override+ public String submitJob(JobContext context, JobTemplate jobTemplate) {+ throw executorFailure;+ }++ @Override+ public JobExecutionInfo getJobExecutionInfo(String jobId) {+ throw new NoSuchJobException("No job %s", jobId);+ }++ @Override+ public void cancelJob(String jobId) {}++ @Override+ public void close() {}+ };+ JobManager manager = Mockito.spy(new JobManager(config, entityStore, idGenerator, executor));+ try {+ JobTemplateEntity template = newShellJobTemplateEntity("shell_job", "A shell job template");+ doReturn(template).when(manager).getJobTemplate(metalake, template.name());++ RuntimeException failure =+ Assertions.assertThrows(+ RuntimeException.class,+ () -> manager.runJob(metalake, template.name(), Collections.emptyMap()));+ Assertions.assertSame(executorFailure, failure.getCause());+ Assertions.assertFalse(failure.getMessage().contains("unknown"), failure.getMessage());+ verify(entityStore, times(1))+ .delete(+ NameIdentifierUtil.ofJob(metalake, lastRegisteredJob().name()),+ Entity.EntityType.JOB);+ verify(entityStore, never())+ .update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any());+ } finally {+ manager.statusPullExecutor.shutdownNow();+ manager.cleanUpExecutor.shutdownNow();+ }+ }++ @Test+ public void testPendingCancellationRecoversAfterTransientFailure() throws Exception {+ JobTemplateEntity template = newShellJobTemplateEntity("shell_job", "A shell job template");+ doReturn(template).when(jobManager).getJobTemplate(metalake, template.name());+ when(jobExecutor.submitJob(any(), any())).thenReturn("shared_execution");+ when(entityStore.update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any()))+ .thenAnswer(+ invocation -> {+ Function<JobEntity, JobEntity> updater = invocation.getArgument(3);+ return updater.apply(withStatus(lastRegisteredJob(), JobHandle.Status.CANCELLING));+ });+ doThrow(new RuntimeException("transient runner outage"))+ .doNothing()+ .when(jobExecutor)+ .cancelJob("shared_execution");+ JobEntity recorded = jobManager.runJob(metalake, template.name(), Collections.emptyMap());+ Assertions.assertEquals(JobHandle.Status.CANCELLING, recorded.status());+ mockListActiveJobs(recorded);+ when(jobExecutor.isJobStateNodeLocal()).thenReturn(false);+ when(jobExecutor.getJobExecutionInfo("shared_execution"))+ .thenReturn(JobExecutionInfo.of(JobHandle.Status.STARTED));+ jobManager.pullAndUpdateJobStatus();+ jobManager.pullAndUpdateJobStatus();+ verify(jobExecutor, Mockito.atLeast(2)).cancelJob("shared_execution");+ }++ @Test+ public void testRunJobPersistsOwnerBeforeExecutorSubmission() throws Exception {+ JobTemplateEntity template = newShellJobTemplateEntity("shell_job", "A shell job template");+ doReturn(template).when(jobManager).getJobTemplate(metalake, template.name());+ OwnerDispatcher owners = Mockito.mock(OwnerDispatcher.class);+ FieldUtils.writeField(GravitinoEnv.getInstance(), "internalOwnerDispatcher", owners, true);+ when(jobExecutor.submitJob(any(), any())).thenReturn("execution-with-owner");+ jobManager.runJob(metalake, template.name(), Collections.emptyMap());+ InOrder order = Mockito.inOrder(entityStore, owners, jobExecutor);+ order.verify(entityStore).put(any(JobEntity.class), eq(false));+ order.verify(owners).setOwner(eq(metalake), any(), any(), any());+ order.verify(jobExecutor).submitJob(any(), any());+ }++ @Test+ public void testOwnerRegistrationFailureNeverSubmitsJob() throws Exception {+ JobTemplateEntity template = newShellJobTemplateEntity("shell_job", "A shell job template");+ doReturn(template).when(jobManager).getJobTemplate(metalake, template.name());+ OwnerDispatcher owners = Mockito.mock(OwnerDispatcher.class);+ FieldUtils.writeField(GravitinoEnv.getInstance(), "internalOwnerDispatcher", owners, true);+ RuntimeException failure = new RuntimeException("owner write failed");+ doThrow(failure).when(owners).setOwner(any(), any(), any(), any());+ Assertions.assertSame(+ failure,+ Assertions.assertThrows(+ RuntimeException.class,+ () -> jobManager.runJob(metalake, template.name(), Collections.emptyMap())));+ verify(jobExecutor, never()).submitJob(any(), any());+ verify(entityStore).delete(any(), eq(Entity.EntityType.JOB));+ assertNoJobStagingDir();+ }++ @Test+ public void testUnknownSubmissionRetainsRegistrationWhenCancellationWriteConflicts()+ throws Exception {+ JobTemplateEntity template = newShellJobTemplateEntity("shell_job", "A shell job template");+ doReturn(template).when(jobManager).getJobTemplate(metalake, template.name());+ RuntimeException submitFailure = new RuntimeException("response lost");+ when(jobExecutor.submitJob(any(), any())).thenThrow(submitFailure);+ when(entityStore.update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any()))+ .thenThrow(new OptimisticLockException("concurrent metadata update"));+ RuntimeException failure =+ Assertions.assertThrows(+ RuntimeException.class,+ () -> jobManager.runJob(metalake, template.name(), Collections.emptyMap()));+ Assertions.assertSame(submitFailure, failure.getCause());+ verify(entityStore, times(3))+ .update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any());+ verify(entityStore, never()).delete(any(), eq(Entity.EntityType.JOB));+ Assertions.assertTrue(jobManager.jobStagingDir(lastRegisteredJob().id()).isDirectory());+ }++ @Test+ public void testUnknownSubmissionRetainsOriginalFailureWhenStoreIsUnavailable() throws Exception {+ JobTemplateEntity template = newShellJobTemplateEntity("shell_job", "A shell job template");+ doReturn(template).when(jobManager).getJobTemplate(metalake, template.name());+ RuntimeException submitFailure = new RuntimeException("response lost");+ IOException storeFailure = new IOException("store unavailable");+ when(jobExecutor.submitJob(any(), any())).thenThrow(submitFailure);+ when(entityStore.update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any()))+ .thenThrow(storeFailure);+ RuntimeException failure =+ Assertions.assertThrows(+ RuntimeException.class,+ () -> jobManager.runJob(metalake, template.name(), Collections.emptyMap()));+ Assertions.assertSame(submitFailure, failure.getCause());+ Assertions.assertSame(storeFailure, failure.getSuppressed()[0]);+ verify(entityStore, times(1))+ .update(any(), eq(JobEntity.class), eq(Entity.EntityType.JOB), any());+ verify(entityStore, never()).delete(any(), eq(Entity.EntityType.JOB));+ }}diff --git a/core/src/test/java/org/apache/gravitino/job/TestJobManagerMultiNode.java b/core/src/test/java/org/apache/gravitino/job/TestJobManagerMultiNode.javaindex b696363999..00fa6798ac 100644--- a/core/src/test/java/org/apache/gravitino/job/TestJobManagerMultiNode.java+++ b/core/src/test/java/org/apache/gravitino/job/TestJobManagerMultiNode.java@@ -29,7 +29,10 @@ import java.time.Instant;import java.util.Collections;import java.util.EnumSet;import java.util.List;+import java.util.Optional;import java.util.concurrent.TimeUnit;+import java.util.concurrent.atomic.AtomicInteger;+import java.util.concurrent.atomic.AtomicReference;import java.util.stream.Collectors;import java.util.stream.Stream;import org.apache.commons.io.FileUtils;@@ -39,11 +42,18 @@ import org.apache.gravitino.Configs;import org.apache.gravitino.Entity;import org.apache.gravitino.EntityStore;import org.apache.gravitino.GravitinoEnv;+import org.apache.gravitino.authorization.AuthorizationUtils;+import org.apache.gravitino.authorization.OwnerDispatcher;+import org.apache.gravitino.authorization.OwnerManager;import org.apache.gravitino.cache.NoOpsCache;+import org.apache.gravitino.catalog.CatalogManager;+import org.apache.gravitino.connector.job.JobContext;import org.apache.gravitino.connector.job.JobExecutionInfo;import org.apache.gravitino.connector.job.JobExecutor;import org.apache.gravitino.exceptions.InUseException;import org.apache.gravitino.exceptions.NoSuchJobException;+import org.apache.gravitino.exceptions.OptimisticLockException;+import org.apache.gravitino.hook.JobHookDispatcher;import org.apache.gravitino.job.local.LocalJobExecutor;import org.apache.gravitino.job.local.LocalJobExecutorConfigs;import org.apache.gravitino.lock.LockManager;@@ -51,6 +61,7 @@ import org.apache.gravitino.meta.AuditInfo;import org.apache.gravitino.meta.BaseMetalake;import org.apache.gravitino.meta.JobEntity;import org.apache.gravitino.meta.JobTemplateEntity;+import org.apache.gravitino.meta.UserEntity;import org.apache.gravitino.storage.RandomIdGenerator;import org.apache.gravitino.storage.relational.DatabaseFixture;import org.apache.gravitino.storage.relational.RelationalEntityStore;@@ -58,11 +69,13 @@ import org.apache.gravitino.storage.relational.ResetStrategy;import org.apache.gravitino.storage.relational.TestJDBCBackend;import org.apache.gravitino.utils.NameIdentifierUtil;import org.apache.gravitino.utils.NamespaceUtil;+import org.apache.gravitino.utils.PrincipalUtils;import org.awaitility.Awaitility;import org.junit.jupiter.api.AfterEach;import org.junit.jupiter.api.Assertions;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.TestTemplate;+import org.mockito.Mockito;/*** Tests the job system in a multi-node deployment: two Gravitino servers, each with its own {@link@@ -85,8 +98,13 @@ public class TestJobManagerMultiNode extends TestJDBCBackend {// A cancellation of a local job is answered by its owner within a few pull intervals.private static final long JOB_STATUS_PULL_INTERVAL_IN_MS = TimeUnit.MINUTES.toMillis(1);+ // A submission not recorded within three pull intervals is reconciled with the job executor.+ private static final long SUBMISSION_TIMEOUT_IN_MS = 3 * JOB_STATUS_PULL_INTERVAL_IN_MS;+private File testDir;+ private Config config;+private LocalJobExecutor executorA;private LocalJobExecutor executorB;@@ -97,12 +115,16 @@ public class TestJobManagerMultiNode extends TestJDBCBackend {private EntityStore entityStore;+ private OwnerDispatcher savedOwnerDispatcher;+@BeforeEachpublic void setUpNodes() throws Exception {+ savedOwnerDispatcher = GravitinoEnv.getInstance().internalOwnerDispatcher();+ FieldUtils.writeField(GravitinoEnv.getInstance(), "internalOwnerDispatcher", null, true);testDir = Files.createTempDirectory("gravitino-test-job-multi-node").toFile();// Both nodes share the same staging directory, like a deployment on shared storage.- Config config = newConfig(new File(testDir, "staging"));+ config = newConfig(new File(testDir, "staging"));FieldUtils.writeField(GravitinoEnv.getInstance(), "lockManager", new LockManager(config), true);// Both nodes share the same metadata store, backed by the relational backend under test.@@ -122,7 +144,7 @@ public class TestJobManagerMultiNode extends TestJDBCBackend {}@AfterEach- public void tearDownNodes() throws IOException {+ public void tearDownNodes() throws Exception {// Closing a node also kills the job processes it runs.if (nodeA != null) {nodeA.close();@@ -131,6 +153,8 @@ public class TestJobManagerMultiNode extends TestJDBCBackend {nodeB.close();}FileUtils.deleteDirectory(testDir);+ FieldUtils.writeField(+ GravitinoEnv.getInstance(), "internalOwnerDispatcher", savedOwnerDispatcher, true);}@TestTemplate@@ -176,6 +200,166 @@ public class TestJobManagerMultiNode extends TestJDBCBackend {Assertions.assertTrue(finished.finishedAt() - finished.startedAt() >= 900, finished.toString());}+ @TestTemplate+ public void testSubmissionLeftByExitedNodeIsSettledByAnotherNode() throws Exception {+ // The server exits right after the job executor accepts the job, before it records the+ // submission. The job was registered before the submission, so it's not lost.+ AtomicReference<String> submitted = new AtomicReference<>();+ JobExecutor crashingExecutor = Mockito.spy(newLocalJobExecutor(config));+ Mockito.doAnswer(+ invocation -> {+ submitted.set((String) invocation.callRealMethod());+ throw new SimulatedServerExit();+ })+ .when(crashingExecutor)+ .submitJob(Mockito.any(JobContext.class), Mockito.any(JobTemplate.class));+ JobManager crashingNode = newJobManager(config, entityStore, crashingExecutor);+ try {+ Assertions.assertThrows(+ SimulatedServerExit.class,+ () -> crashingNode.runJob(METALAKE, TEMPLATE, ImmutableMap.of("seconds", "600")));+ JobEntity pending = onlyJob();+ Assertions.assertEquals(JobHandle.Status.QUEUED, pending.status());+ Assertions.assertEquals(+ JobManager.pendingSubmissionExecutionId(pending.id()), pending.jobExecutionId());++ // Within the submission timeout, the job is left to the server submitting it.+ nodeB.pullAndUpdateJobStatus();+ Assertions.assertEquals(pending, getJob(pending.name()));++ // Beyond it, the job is reconciled with the job executor, which has no execution of it on+ // node B, so it's marked as FAILED.+ moveJobTimestampsBack(pending.name(), SUBMISSION_TIMEOUT_IN_MS + 60_000L);+ nodeB.pullAndUpdateJobStatus();+ JobEntity settled = getJob(pending.name());+ Assertions.assertEquals(JobHandle.Status.FAILED, settled.status());+ Assertions.assertTrue(settled.finishedAt() > 0);+ Assertions.assertNotNull(submitted.get());+ } finally {+ // Closing the node kills the job process it launched.+ crashingNode.close();+ }+ }++ @TestTemplate+ public void testSubmissionLeftByExitedNodeIsRecordedWhenExecutorHasIt() throws Exception {+ AtomicReference<String> submitted = new AtomicReference<>();+ JobExecutor crashingExecutor = Mockito.spy(newLocalJobExecutor(config));+ Mockito.doAnswer(+ invocation -> {+ submitted.set((String) invocation.callRealMethod());+ throw new SimulatedServerExit();+ })+ .when(crashingExecutor)+ .submitJob(Mockito.any(JobContext.class), Mockito.any(JobTemplate.class));+ JobManager crashingNode = newJobManager(config, entityStore, crashingExecutor);+ // A job executor that can look up a job by its Gravitino job id finds the execution.+ JobExecutor lookupExecutor = Mockito.spy(newLocalJobExecutor(config));+ Mockito.doAnswer(invocation -> Optional.ofNullable(submitted.get()))+ .when(lookupExecutor)+ .findSubmittedJob(Mockito.any(JobContext.class), Mockito.any(JobTemplate.class));+ JobManager lookupNode = newJobManager(config, entityStore, lookupExecutor);+ try {+ Assertions.assertThrows(+ SimulatedServerExit.class,+ () -> crashingNode.runJob(METALAKE, TEMPLATE, ImmutableMap.of("seconds", "0")));+ JobEntity pending = onlyJob();+ moveJobTimestampsBack(pending.name(), SUBMISSION_TIMEOUT_IN_MS + 60_000L);++ lookupNode.pullAndUpdateJobStatus();+ JobEntity recorded = getJob(pending.name());+ Assertions.assertEquals(submitted.get(), recorded.jobExecutionId());+ Assertions.assertEquals(JobHandle.Status.QUEUED, recorded.status());++ // From then on the job is tracked by the node owning the execution like any other job.+ Awaitility.await()+ .atMost(1, TimeUnit.MINUTES)+ .until(+ () -> crashingExecutor.getJobStatus(submitted.get()) == JobHandle.Status.SUCCEEDED);+ crashingNode.pullAndUpdateJobStatus();+ Assertions.assertEquals(JobHandle.Status.SUCCEEDED, getJob(pending.name()).status());+ } finally {+ crashingNode.close();+ lookupNode.close();+ }+ }++ @TestTemplate+ public void testSubmissionSettledByAnotherNodeIsCancelled() throws Exception {+ // The submission takes longer than the submission timeout, so node B settles the job while it+ // is being submitted. Node A then cancels the execution it can no longer record.+ AtomicReference<String> submitted = new AtomicReference<>();+ JobExecutor decidingExecutor = Mockito.mock(JobExecutor.class);+ Mockito.when(decidingExecutor.findSubmittedJob(Mockito.any(), Mockito.any()))+ .thenReturn(Optional.empty());+ JobManager decidingNode = newJobManager(config, entityStore, decidingExecutor);+ JobExecutor slowExecutor = Mockito.spy(newLocalJobExecutor(config));+ Mockito.doAnswer(+ invocation -> {+ JobContext context = invocation.getArgument(0);+ String jobName = JobHandle.JOB_ID_PREFIX + context.jobId();+ moveJobTimestampsBack(jobName, SUBMISSION_TIMEOUT_IN_MS + 60_000L);+ decidingNode.pullAndUpdateJobStatus();+ Assertions.assertEquals(JobHandle.Status.FAILED, getJob(jobName).status());+ submitted.set((String) invocation.callRealMethod());+ return submitted.get();+ })+ .when(slowExecutor)+ .submitJob(Mockito.any(JobContext.class), Mockito.any(JobTemplate.class));+ JobManager slowNode = newJobManager(config, entityStore, slowExecutor);+ try {+ RuntimeException failure =+ Assertions.assertThrows(+ RuntimeException.class,+ () -> slowNode.runJob(METALAKE, TEMPLATE, ImmutableMap.of("seconds", "600")));+ Assertions.assertTrue(failure.getMessage().contains(submitted.get()), failure.getMessage());++ Awaitility.await()+ .atMost(1, TimeUnit.MINUTES)+ .until(() -> slowExecutor.getJobStatus(submitted.get()) == JobHandle.Status.CANCELLED);+ JobEntity settled = onlyJob();+ Assertions.assertEquals(JobHandle.Status.FAILED, settled.status());+ // The settled job keeps no execution id it never recorded.+ Assertions.assertEquals(+ JobManager.pendingSubmissionExecutionId(settled.id()), settled.jobExecutionId());+ } finally {+ slowNode.close();+ decidingNode.close();+ }+ }++ @TestTemplate+ public void testJobCancelledFromAnotherNodeDuringSubmissionIsCancelled() throws Exception {+ AtomicReference<String> submitted = new AtomicReference<>();+ JobExecutor slowExecutor = Mockito.spy(newLocalJobExecutor(config));+ Mockito.doAnswer(+ invocation -> {+ JobContext context = invocation.getArgument(0);+ String jobName = JobHandle.JOB_ID_PREFIX + context.jobId();+ // Node B has no execution to cancel yet, so it only marks the job as CANCELLING.+ Assertions.assertEquals(+ JobHandle.Status.CANCELLING, nodeB.cancelJob(METALAKE, jobName).status());+ submitted.set((String) invocation.callRealMethod());+ return submitted.get();+ })+ .when(slowExecutor)+ .submitJob(Mockito.any(JobContext.class), Mockito.any(JobTemplate.class));+ JobManager slowNode = newJobManager(config, entityStore, slowExecutor);+ try {+ JobEntity job = slowNode.runJob(METALAKE, TEMPLATE, ImmutableMap.of("seconds", "600"));+ Assertions.assertEquals(JobHandle.Status.CANCELLING, job.status());+ Assertions.assertEquals(submitted.get(), job.jobExecutionId());+ Awaitility.await()+ .atMost(1, TimeUnit.MINUTES)+ .until(() -> slowExecutor.getJobStatus(submitted.get()) == JobHandle.Status.CANCELLED);++ slowNode.pullAndUpdateJobStatus();+ Assertions.assertEquals(JobHandle.Status.CANCELLED, getJob(job.name()).status());+ } finally {+ slowNode.close();+ }+ }+@TestTemplatepublic void testCancelJobFromAnotherNode() throws IOException {JobEntity job = runLongJobOnNodeA();@@ -498,6 +682,16 @@ public class TestJobManagerMultiNode extends TestJDBCBackend {.build());}+ private JobEntity onlyJob() {+ List<JobEntity> jobs = nodeB.listJobs(METALAKE, Optional.empty());+ Assertions.assertEquals(1, jobs.size(), jobs.toString());+ return jobs.get(0);+ }++ // Thrown by a job executor to simulate that the server exits in the middle of a submission. It+ // is an Error, so that the server doesn't handle it as a failed submission.+ private static class SimulatedServerExit extends Error {}+private boolean jobExists(String jobName) {try {getJob(jobName);@@ -567,4 +761,295 @@ public class TestJobManagerMultiNode extends TestJDBCBackend {jobManager.cleanUpExecutor.shutdownNow();return jobManager;}++ @TestTemplate+ public void testOwnSubmissionSurvivesStatusPull() throws Exception {+ AtomicReference<JobManager> ownNode = new AtomicReference<>();+ JobExecutor slowExecutor = Mockito.spy(newLocalJobExecutor(config));+ Mockito.doAnswer(+ invocation -> {+ JobContext context = invocation.getArgument(0);+ String jobName = JobHandle.JOB_ID_PREFIX + context.jobId();+ // Force the persisted row beyond the submission timeout while this node is+ // submitting.+ moveJobTimestampsBack(jobName, SUBMISSION_TIMEOUT_IN_MS + 60_000L);+ ownNode.get().pullAndUpdateJobStatus();+ Assertions.assertEquals(JobHandle.Status.QUEUED, getJob(jobName).status());+ return invocation.callRealMethod();+ })+ .when(slowExecutor)+ .submitJob(Mockito.any(JobContext.class), Mockito.any(JobTemplate.class));+ JobManager slowNode = newJobManager(config, entityStore, slowExecutor);+ ownNode.set(slowNode);+ try {+ slowNode.runJob(METALAKE, TEMPLATE, ImmutableMap.of("seconds", "0"));+ } finally {+ slowNode.close();+ }+ }++ @TestTemplate+ public void testRecoveredSubmissionRetainsCreatorOwnership() throws Exception {+ String userName = PrincipalUtils.getCurrentUserName();+ backend.insert(+ UserEntity.builder()+ .withId(RandomIdGenerator.INSTANCE.nextId())+ .withName(userName)+ .withNamespace(AuthorizationUtils.ofUserNamespace(METALAKE))+ .withRoleNames(Collections.emptyList())+ .withRoleIds(Collections.emptyList())+ .withAuditInfo(AUDIT_INFO)+ .build(),+ false);+ OwnerDispatcher saved = GravitinoEnv.getInstance().internalOwnerDispatcher();+ Object savedCatalogManager =+ FieldUtils.readField(GravitinoEnv.getInstance(), "catalogManager", true);+ FieldUtils.writeField(+ GravitinoEnv.getInstance(), "catalogManager", Mockito.mock(CatalogManager.class), true);+ OwnerManager owners = new OwnerManager(entityStore);+ FieldUtils.writeField(GravitinoEnv.getInstance(), "internalOwnerDispatcher", owners, true);+ AtomicReference<String> pendingName = new AtomicReference<>();+ AtomicReference<String> execution = new AtomicReference<>();+ JobExecutor crashingExecutor = Mockito.spy(newLocalJobExecutor(config));+ Mockito.doAnswer(+ invocation -> {+ JobContext context = invocation.getArgument(0);+ pendingName.set(JobHandle.JOB_ID_PREFIX + context.jobId());+ JobEntity registered = getJob(pendingName.get());+ Assertions.assertEquals(+ userName,+ owners+ .getOwner(+ METALAKE,+ NameIdentifierUtil.toMetadataObject(+ registered.nameIdentifier(), Entity.EntityType.JOB))+ .orElseThrow()+ .name());+ execution.set((String) invocation.callRealMethod());+ throw new SimulatedServerExit();+ })+ .when(crashingExecutor)+ .submitJob(Mockito.any(JobContext.class), Mockito.any(JobTemplate.class));+ JobManager crashing = newJobManager(config, entityStore, crashingExecutor);+ JobExecutor lookupExecutor = Mockito.mock(JobExecutor.class);+ Mockito.when(lookupExecutor.findSubmittedJob(Mockito.any(), Mockito.any()))+ .thenAnswer(invocation -> Optional.of(execution.get()));+ JobManager lookup = newJobManager(config, entityStore, lookupExecutor);+ try {+ // Prove the same real hook and owner store establish ownership on an ordinary run.+ JobEntity ordinary =+ new JobHookDispatcher(nodeA).runJob(METALAKE, TEMPLATE, ImmutableMap.of("seconds", "0"));+ Assertions.assertTrue(+ owners+ .getOwner(+ METALAKE,+ NameIdentifierUtil.toMetadataObject(+ ordinary.nameIdentifier(), Entity.EntityType.JOB))+ .isPresent());+ Assertions.assertThrows(+ SimulatedServerExit.class,+ () ->+ new JobHookDispatcher(crashing)+ .runJob(METALAKE, TEMPLATE, ImmutableMap.of("seconds", "0")));+ moveJobTimestampsBack(pendingName.get(), SUBMISSION_TIMEOUT_IN_MS + 60_000L);+ lookup.pullAndUpdateJobStatus();+ JobEntity recovered = getJob(pendingName.get());+ Assertions.assertEquals(execution.get(), recovered.jobExecutionId());+ Assertions.assertTrue(+ owners+ .getOwner(+ METALAKE,+ NameIdentifierUtil.toMetadataObject(+ recovered.nameIdentifier(), Entity.EntityType.JOB))+ .isPresent(),+ "A recovered job must retain the ownership that permits its creator to get or cancel it");+ } finally {+ crashing.close();+ lookup.close();+ FieldUtils.writeField(GravitinoEnv.getInstance(), "internalOwnerDispatcher", saved, true);+ FieldUtils.writeField(+ GravitinoEnv.getInstance(), "catalogManager", savedCatalogManager, true);+ }+ }++ @TestTemplate+ public void testUnknownSubmissionRecoversAndRetriesCancellation() throws Exception {+ AtomicReference<JobHandle.Status> runnerStatus =+ new AtomicReference<>(JobHandle.Status.STARTED);+ AtomicReference<Boolean> reachable = new AtomicReference<>(false);+ AtomicInteger cancellations = new AtomicInteger();+ JobExecutor shared = Mockito.mock(LookupJobExecutor.class);+ Mockito.when(shared.ownsJob(Mockito.any())).thenReturn(true);+ Mockito.when(shared.submitJob(Mockito.any(), Mockito.any()))+ .thenThrow(new RuntimeException("accepted execution, response lost"));+ Mockito.when(shared.findSubmittedJob(Mockito.any(), Mockito.any()))+ .thenAnswer(+ invocation -> {+ if (!reachable.get()) {+ throw new RuntimeException("runner unavailable");+ }+ return Optional.of("shared-execution");+ });+ Mockito.when(shared.getJobExecutionInfo("shared-execution"))+ .thenAnswer(invocation -> JobExecutionInfo.of(runnerStatus.get()));+ Mockito.doAnswer(+ invocation -> {+ if (cancellations.incrementAndGet() == 1) {+ throw new RuntimeException("temporary cancel failure");+ }+ runnerStatus.set(JobHandle.Status.CANCELLED);+ return null;+ })+ .when(shared)+ .cancelJob("shared-execution");+ JobManager submitting = newJobManager(config, entityStore, shared);+ JobManager recovering = newJobManager(config, entityStore, shared);+ try {+ RuntimeException failure =+ Assertions.assertThrows(+ RuntimeException.class,+ () -> submitting.runJob(METALAKE, TEMPLATE, ImmutableMap.of("seconds", "600")));+ Assertions.assertTrue(failure.getMessage().contains("Check the job before retrying"));+ JobEntity pending = onlyJob();+ Assertions.assertEquals(JobHandle.Status.CANCELLING, pending.status());+ Assertions.assertTrue(jobStagingDir(pending).isDirectory());+ moveJobTimestampsBack(pending.name(), SUBMISSION_TIMEOUT_IN_MS + 60_000L);+ recovering.pullAndUpdateJobStatus();+ Assertions.assertEquals(pending.jobExecutionId(), getJob(pending.name()).jobExecutionId());+ reachable.set(true);+ recovering.pullAndUpdateJobStatus();+ Assertions.assertEquals("shared-execution", getJob(pending.name()).jobExecutionId());+ Assertions.assertEquals(JobHandle.Status.CANCELLING, getJob(pending.name()).status());+ recovering.pullAndUpdateJobStatus();+ Assertions.assertEquals(JobHandle.Status.CANCELLED, getJob(pending.name()).status());+ Assertions.assertEquals(2, cancellations.get());+ Mockito.verify(shared, Mockito.times(1)).submitJob(Mockito.any(), Mockito.any());+ } finally {+ submitting.close();+ recovering.close();+ }+ }++ @TestTemplate+ public void testRecordingFailureRetriesCancellationWithoutLookup() throws Exception {+ AtomicInteger updates = new AtomicInteger();+ EntityStore conflictingStore = Mockito.spy(entityStore);+ Mockito.doAnswer(+ invocation -> {+ if (updates.incrementAndGet() <= 3) {+ throw new OptimisticLockException("recording conflict");+ }+ return invocation.callRealMethod();+ })+ .when(conflictingStore)+ .update(+ Mockito.any(),+ Mockito.eq(JobEntity.class),+ Mockito.eq(Entity.EntityType.JOB),+ Mockito.any());+ AtomicInteger cancellations = new AtomicInteger();+ AtomicReference<JobHandle.Status> runnerStatus =+ new AtomicReference<>(JobHandle.Status.STARTED);+ JobExecutor shared = Mockito.mock(JobExecutor.class);+ Mockito.when(shared.ownsJob(Mockito.any())).thenReturn(true);+ Mockito.when(shared.submitJob(Mockito.any(), Mockito.any())).thenReturn("accepted-execution");+ // Like the default findSubmittedJob(), a lookup never finds the accepted execution.+ Mockito.when(shared.findSubmittedJob(Mockito.any(), Mockito.any()))+ .thenReturn(Optional.empty());+ Mockito.when(shared.getJobExecutionInfo("accepted-execution"))+ .thenAnswer(invocation -> JobExecutionInfo.of(runnerStatus.get()));+ Mockito.doAnswer(+ invocation -> {+ if (cancellations.incrementAndGet() == 1) {+ throw new RuntimeException("temporary cancellation failure");+ }+ runnerStatus.set(JobHandle.Status.CANCELLED);+ return null;+ })+ .when(shared)+ .cancelJob("accepted-execution");+ JobManager submitting = newJobManager(config, conflictingStore, shared);+ JobManager recovering = newJobManager(config, entityStore, shared);+ try {+ Assertions.assertThrows(+ RuntimeException.class,+ () -> submitting.runJob(METALAKE, TEMPLATE, ImmutableMap.of("seconds", "600")));+ JobEntity pending = onlyJob();+ Assertions.assertEquals("accepted-execution", pending.jobExecutionId());+ Assertions.assertEquals(JobHandle.Status.CANCELLING, pending.status());+ moveJobTimestampsBack(pending.name(), SUBMISSION_TIMEOUT_IN_MS + 60_000L);++ // The execution is still running, so the job is not settled as CANCELLED before it is.+ recovering.pullAndUpdateJobStatus();+ recovering.pullAndUpdateJobStatus();+ Assertions.assertEquals(JobHandle.Status.CANCELLED, getJob(pending.name()).status());+ Assertions.assertEquals(2, cancellations.get());+ Mockito.verify(shared, Mockito.never()).findSubmittedJob(Mockito.any(), Mockito.any());+ } finally {+ submitting.close();+ recovering.close();+ }+ }++ @TestTemplate+ public void testRecordingFailureRecoversAndRetriesCancellation() throws Exception {+ AtomicInteger updates = new AtomicInteger();+ EntityStore conflictingStore = Mockito.spy(entityStore);+ Mockito.doAnswer(+ invocation -> {+ if (updates.incrementAndGet() <= 3) {+ throw new OptimisticLockException("recording conflict");+ }+ return invocation.callRealMethod();+ })+ .when(conflictingStore)+ .update(+ Mockito.any(),+ Mockito.eq(JobEntity.class),+ Mockito.eq(Entity.EntityType.JOB),+ Mockito.any());+ AtomicInteger cancellations = new AtomicInteger();+ AtomicReference<JobHandle.Status> runnerStatus =+ new AtomicReference<>(JobHandle.Status.STARTED);+ JobExecutor shared = Mockito.mock(JobExecutor.class);+ Mockito.when(shared.ownsJob(Mockito.any())).thenReturn(true);+ Mockito.when(shared.submitJob(Mockito.any(), Mockito.any())).thenReturn("accepted-execution");+ Mockito.when(shared.findSubmittedJob(Mockito.any(), Mockito.any()))+ .thenReturn(Optional.of("accepted-execution"));+ Mockito.when(shared.getJobExecutionInfo("accepted-execution"))+ .thenAnswer(invocation -> JobExecutionInfo.of(runnerStatus.get()));+ Mockito.doAnswer(+ invocation -> {+ if (cancellations.incrementAndGet() == 1) {+ throw new RuntimeException("temporary cancellation failure");+ }+ runnerStatus.set(JobHandle.Status.CANCELLED);+ return null;+ })+ .when(shared)+ .cancelJob("accepted-execution");+ JobManager submitting = newJobManager(config, conflictingStore, shared);+ JobManager recovering = newJobManager(config, entityStore, shared);+ try {+ RuntimeException failure =+ Assertions.assertThrows(+ RuntimeException.class,+ () -> submitting.runJob(METALAKE, TEMPLATE, ImmutableMap.of("seconds", "600")));+ Assertions.assertFalse(failure instanceof OptimisticLockException);+ JobEntity pending = onlyJob();+ Assertions.assertEquals(JobHandle.Status.CANCELLING, pending.status());+ Assertions.assertEquals("accepted-execution", pending.jobExecutionId());+ Assertions.assertEquals(4, updates.get());+ moveJobTimestampsBack(pending.name(), SUBMISSION_TIMEOUT_IN_MS + 60_000L);+ recovering.pullAndUpdateJobStatus();+ Assertions.assertEquals("accepted-execution", getJob(pending.name()).jobExecutionId());+ recovering.pullAndUpdateJobStatus();+ Assertions.assertEquals(JobHandle.Status.CANCELLED, getJob(pending.name()).status());+ Assertions.assertEquals(2, cancellations.get());+ Mockito.verify(shared, Mockito.times(1)).submitJob(Mockito.any(), Mockito.any());+ } finally {+ submitting.close();+ recovering.close();+ }+ }}diff --git a/docs/development/custom-job-executor.md b/docs/development/custom-job-executor.mdindex c89d4f0886..57844accb7 100644--- a/docs/development/custom-job-executor.md+++ b/docs/development/custom-job-executor.md@@ -56,6 +56,42 @@ these times whenever the job runner provides them: Gravitino pulls job states onstatus change, and a job that starts and finishes between two pulls gets no start time. Once a jobhas started, keep reporting its start time in every later state, including the finished one.+### Recover Unrecorded Submissions++Gravitino registers a job and its initial owner before it calls `submitJob`, and records the returned+execution id afterwards. If that id is not recorded within three+`gravitino.job.statusPullIntervalInMs`, another server, or the same server after a restart, calls+`findSubmittedJob(JobContext, JobTemplate)` with the original job id, metalake and runtime template:++- A returned execution id is recorded. It must be the same string that `submitJob` returns.+- An empty result means that the runner has no execution. The job becomes `FAILED`, or+ `CANCELLED` if cancellation was requested. Only return it when the runner confirms it, unless+ the job executor can't look up executions at all, see the default implementation below.+- An exception keeps the job for a lookup in the next status pull.++The default implementation returns empty. Implement the lookup if the runner can identify an+execution by `JobContext#jobId()`.++The lookup may run concurrently with a slow submission. Keep the registration-to-recording phase+within three pull intervals; a submission that returns after another server settled the job is+cancelled and its run request fails. An execution id must not start with `pending-submission:`.++Throw `IllegalArgumentException` for invalid input, or `JobSubmissionRejectedException` when no+execution was created or its removal is confirmed. Gravitino then removes the job. Other failures,+including a lost response, have an unknown outcome:++- If the job executor implements `findSubmittedJob`, Gravitino keeps the job and marks it as+ `CANCELLING` rather than replaying the submission, so an execution found for it later is+ cancelled. If the metadata store cannot record that, the job is still kept, but a found execution+ may be tracked as running; check that job before retrying the run request.+- Otherwise Gravitino removes the job, as it couldn't find an execution left behind. Remove what+ the submission may have created before throwing.++`cancelJob` must be safe to repeat. A persisted `CANCELLING` job is retried while the runner reports+`QUEUED` or `STARTED`, including for shared runners. Report `CANCELLING` once an asynchronous+cancellation is accepted, or a terminal state when it finishes. A temporary failure must not erase+the cancellation intent.+### Register the Job ExecutorAfter you implement your own job executor, you need to register it in the Gravitino server bydiff --git a/docs/manage-jobs-in-gravitino.md b/docs/manage-jobs-in-gravitino.mdindex 5d2465a42c..702e77c61d 100644--- a/docs/manage-jobs-in-gravitino.md+++ b/docs/manage-jobs-in-gravitino.md@@ -254,6 +254,39 @@ job = client.run_job(</TabItem></Tabs>+Gravitino records a job as `QUEUED` and sets its initial owner before handing it to the job executor.+A recovered job therefore keeps the permissions of its original submitter. If the execution id is+not recorded within three times `gravitino.job.statusPullIntervalInMs`, another server, or the same+server after a restart, looks the job up in the runner. A found execution is tracked, or cancelled+if the job is `CANCELLING`. Otherwise the job is settled as `FAILED`, or `CANCELLED` if it is+`CANCELLING`. A failed lookup is retried in the next pull. The `k8s` executor finds a job while its+name prefix and namespace configuration remain unchanged. The local executor finds none, as the job+state is lost with the server that submitted it.++Invalid input and a rejected submission remove the job. For the `k8s` executor, a failed submission+with an unknown outcome, such as a lost response after the runner accepted it, keeps the job as+`CANCELLING`, so an execution found for it later is cancelled, and the job is then settled as+`CANCELLED`. If the store cannot record the cancellation, the job is still kept and may be tracked+as running. The error identifies the job: check it before retrying, since retrying a run request+creates a new job. The `k8s` executor also attempts immediate cleanup, and logs a manual `kubectl`+remedy if that fails. With a job executor that can't find a job, such as the local executor, any+failed submission removes the job.++Cancelling a job during submission persists `CANCELLING`. Once an execution is recorded, Gravitino+cancels it and retries temporary cancellation failures during status pulls. Repeating the cancel+request also retries cancellation without resetting its timeout. An executor that has acknowledged+an asynchronous cancellation by reporting `CANCELLING` is monitored until it finishes.++:::caution+With several Gravitino servers, use the same `gravitino.job.statusPullIntervalInMs` and keep their+clocks in sync. The entire registration-to-recording phase must fit within three pull intervals.+Otherwise another server may settle the job, and cancellation of a late submission is attempted+before its run request fails. Cancellation cannot undo completed work. If the job was already+settled and this late cancellation fails, check the execution in the runner before retrying.+`gravitino.job.stagingDirKeepTimeInMs` must also be longer than preparing, submitting, queueing and+running a job of the local executor, as described below.+:::+### List Jobs, Get a Job, and CancelListing can be filtered to one template. A job is identified by its id, and cancelling is a `POST`@@ -441,10 +474,12 @@ only tracks the jobs it runs itself:`CANCELLED` if it was being cancelled. Like other finished jobs, it is then kept for another`gravitino.job.stagingDirKeepTimeInMs` before being cleaned up together with its stagingdirectory.-- To clear such a job sooner, cancel it. If the job is still `CANCELLING` more than three times- `gravitino.job.statusPullIntervalInMs` after the cancel request, the server running it is- considered gone, and another server marks the job as `CANCELLED` when it pulls job statuses. Its- job template can then be deleted.+- For a job whose execution id was recorded, cancelling it can clear it sooner. If it is still+ `CANCELLING` more than three times `gravitino.job.statusPullIntervalInMs` after the cancel request,+ the server running it is considered gone, and another server marks it as `CANCELLED` when it+ pulls job statuses. Its job template can then be deleted.+- A job whose execution id was never recorded is settled within about four times+ `gravitino.job.statusPullIntervalInMs` too, as described in [Run a Job](#run-a-job).:::cautionThe local job executor can't tell a job left behind by an exited server from a job that is still@@ -463,10 +498,10 @@ jobs are only marked as `FAILED` once they expire as described above, which canevery tenth of that time. Until then, they are still reported as queued, started or cancelling, andthey keep their job templates from being deleted.-To clear these jobs sooner, cancel them. A cancelled job is marked as `CANCELLED` within about four-times `gravitino.job.statusPullIntervalInMs`, as described above. Lowering-`gravitino.job.stagingDirKeepTimeInMs` also shortens the time, but finished jobs are then kept for-a shorter time, and a job that runs longer than that without changing its status is marked as+For jobs whose execution id was recorded, cancelling them settles them as `CANCELLED` within about+four times `gravitino.job.statusPullIntervalInMs`, as described above. Lowering+`gravitino.job.stagingDirKeepTimeInMs` shortens retention, but finished jobs are then kept for a+shorter time, and a job that runs longer than that without changing its status is marked as`FAILED`.:::diff --git a/plugins/k8s-job-executor/src/main/java/org/apache/gravitino/job/k8s/K8sJobExecutor.java b/plugins/k8s-job-executor/src/main/java/org/apache/gravitino/job/k8s/K8sJobExecutor.javaindex 3911f94d6a..7e8e5cadcd 100644--- a/plugins/k8s-job-executor/src/main/java/org/apache/gravitino/job/k8s/K8sJobExecutor.java+++ b/plugins/k8s-job-executor/src/main/java/org/apache/gravitino/job/k8s/K8sJobExecutor.java@@ -55,6 +55,7 @@ import org.apache.commons.lang3.StringUtils;import org.apache.gravitino.connector.job.JobContext;import org.apache.gravitino.connector.job.JobExecutionInfo;import org.apache.gravitino.connector.job.JobExecutor;+import org.apache.gravitino.connector.job.JobSubmissionRejectedException;import org.apache.gravitino.exceptions.NoSuchJobException;import org.apache.gravitino.job.JobHandle;import org.apache.gravitino.job.JobTemplate;@@ -178,8 +179,8 @@ public class K8sJobExecutor implements JobExecutor {} catch (KubernetesClientException e) {if (isUnreachable(e) || e.getCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) {// The SparkApplication may have been created although no response or an error came back.- // Gravitino records no job for a failed submission, so delete it, otherwise it would run- // unknown.+ // Attempt cleanup immediately. If cleanup also fails, Gravitino retains the pending+ // registration and retries recovery and cancellation after the API server recovers.deleteUnsubmittedSparkApplication(jobExecutionId, context.jobId());throw e;}@@ -200,10 +201,9 @@ public class K8sJobExecutor implements JobExecutor {// that is being deleted.GenericKubernetesResource existing =getSparkApplicationClient(namespace).withName(name).get();- if (existing == null- || existing.getMetadata().getDeletionTimestamp() != null- || !K8sJobResourceUtils.isOfJob(existing, context.jobId())) {- throw new IllegalStateException(+ if (existing != null && !K8sJobResourceUtils.isOfJob(existing, context.jobId())) {+ // Nothing was created for this job, so the submission is rejected for sure.+ throw new JobSubmissionRejectedException(String.format("SparkApplication %s/%s already exists and can't be used for job %s. If it belongs"+ " to another Gravitino deployment sharing the namespace, use a different %s"@@ -211,12 +211,62 @@ public class K8sJobExecutor implements JobExecutor {namespace, name, context.jobId(), K8sJobExecutorConfigs.NAME_PREFIX),e);}+ if (existing == null || existing.getMetadata().getDeletionTimestamp() != null) {+ // A retried request may have created it before it was deleted, and its pods may still+ // run until the deletion finishes, so the outcome is unknown rather than rejected.+ // Recovery finds the resource until it is gone.+ throw new IllegalStateException(+ String.format(+ "SparkApplication %s/%s conflicted with job %s but is being deleted or already"+ + " gone, so whether it was created for this job can't be told",+ namespace, name, context.jobId()),+ e);+ }}LOG.info("Submitted job {} as {}", context.jobId(), jobExecutionId);return jobExecutionId.toString();}+ @Override+ public Optional<String> findSubmittedJob(JobContext context, JobTemplate jobTemplate) {+ if (!(jobTemplate instanceof SparkJobTemplate)) {+ return Optional.empty();+ }++ // The SparkApplication of a job is named after the job id, in the namespace that the job+ // template selects, so it's found the same way submitJob() names it. Only the name and the+ // namespace are derived, not the whole SparkApplication, whose checks may fail on the current+ // configurations although the job was submitted. A job is not found if the name prefix or the+ // default namespace of the job executor changed since it was submitted. A deleting resource+ // is retained too, so recovery can track its pods until cancellation actually finishes.+ String namespace;+ try {+ namespace = SparkApplicationUtils.namespaceOf((SparkJobTemplate) jobTemplate, configs);+ } catch (IllegalArgumentException e) {+ // submitJob() rejects such a job before creating anything.+ return Optional.empty();+ }+ K8sJobExecutionId jobExecutionId =+ K8sJobExecutionId.of(+ configs.cluster(),+ K8sJobExecutionId.Kind.SPARK_APPLICATION,+ namespace,+ K8sJobResourceUtils.resourceName(configs, context.jobId()));+ checkApiServerReachable();+ try {+ return getSparkApplication(jobExecutionId)+ .filter(existing -> K8sJobResourceUtils.isOfJob(existing, context.jobId()))+ .map(existing -> jobExecutionId.toString());+ } catch (KubernetesClientException e) {+ if (isUnreachable(e)) {+ unreachableAtMs = clock.millis();+ unreachableFailure = e;+ }+ throw e;+ }+ }+@Overridepublic JobExecutionInfo getJobExecutionInfo(String jobId) throws NoSuchJobException {K8sJobExecutionId id = parseJobExecutionId(jobId);@@ -535,10 +585,12 @@ public class K8sJobExecutor implements JobExecutor {LOG.info("Deleted the SparkApplication of job {}, whose submission failed", jobId);}} catch (RuntimeException e) {- // Gravitino doesn't sweep the resources of unknown jobs, so tell how to delete it by hand.+ // Recovery will retry through the retained registration. Also give operators a manual+ // remedy, for example when they cannot restore the runner connection.LOG.warn("Failed to clean up the SparkApplication {}/{} of job {}, whose submission failed. It may"- + " run although Gravitino has no record of it. If it exists with the label {}={},"+ + " still run; Gravitino retains its registration for recovery. If it exists with"+ + " the label {}={},"+ " delete it with: kubectl delete sparkapplication -n {} {}",id.namespace(),id.name(),diff --git a/plugins/k8s-job-executor/src/main/java/org/apache/gravitino/job/k8s/spark/SparkApplicationUtils.java b/plugins/k8s-job-executor/src/main/java/org/apache/gravitino/job/k8s/spark/SparkApplicationUtils.javaindex 53b170480c..77b0eeaa8c 100644--- a/plugins/k8s-job-executor/src/main/java/org/apache/gravitino/job/k8s/spark/SparkApplicationUtils.java+++ b/plugins/k8s-job-executor/src/main/java/org/apache/gravitino/job/k8s/spark/SparkApplicationUtils.java@@ -196,17 +196,7 @@ public final class SparkApplicationUtils {sparkConf.remove(SPARK_DEPLOY_MODE);putIfBlank(sparkConf, SPARK_IMAGE, configs.sparkImage());putIfBlank(sparkConf, SPARK_DRIVER_SERVICE_ACCOUNT, configs.sparkServiceAccount());- // Only a job chooses its namespace this way. A default set in the Spark configurations of- // the executor would silently shadow the namespace of the executor configurations.- String namespace = StringUtils.trimToNull(jobSparkConf.get(SPARK_NAMESPACE));- if (namespace == null) {- namespace = configs.namespace();- } else if (!K8sJobResourceUtils.isValidNamespace(namespace)) {- throw new IllegalArgumentException(- String.format(- "%s of job template %s isn't a valid namespace name: %s",- SPARK_NAMESPACE, template.name(), namespace));- }+ String namespace = namespaceOf(template, configs);sparkConf.put(SPARK_NAMESPACE, namespace);appendList(sparkConf, SPARK_JARS, template.jars());appendList(sparkConf, SPARK_FILES, template.files());@@ -260,6 +250,31 @@ public final class SparkApplicationUtils {return app;}+ /**+ * Returns the namespace the SparkApplication of a job is created in.+ *+ * @param template the runtime job template+ * @param configs the job executor configurations+ * @return the namespace the job template chooses, or else the namespace of the job executor+ * @throws IllegalArgumentException if the job template chooses an invalid namespace+ */+ public static String namespaceOf(SparkJobTemplate template, K8sJobExecutorConfigs configs) {+ // Only a job chooses its namespace this way. A default set in the Spark configurations of+ // the executor would silently shadow the namespace of the executor configurations. A built-in+ // job template can't choose it in its spark_conf, which ignores spark.kubernetes.*.+ String namespace = StringUtils.trimToNull(template.configs().get(SPARK_NAMESPACE));+ if (namespace == null) {+ return configs.namespace();+ }+ if (!K8sJobResourceUtils.isValidNamespace(namespace)) {+ throw new IllegalArgumentException(+ String.format(+ "%s of job template %s isn't a valid namespace name: %s",+ SPARK_NAMESPACE, template.name(), namespace));+ }+ return namespace;+ }+/*** Returns the Spark configurations that a job sets itself, which override the default Spark* configurations of the job executor.diff --git a/plugins/k8s-job-executor/src/test/java/org/apache/gravitino/job/k8s/TestK8sJobExecutor.java b/plugins/k8s-job-executor/src/test/java/org/apache/gravitino/job/k8s/TestK8sJobExecutor.javaindex 01f479941c..b4fb5a575f 100644--- a/plugins/k8s-job-executor/src/test/java/org/apache/gravitino/job/k8s/TestK8sJobExecutor.java+++ b/plugins/k8s-job-executor/src/test/java/org/apache/gravitino/job/k8s/TestK8sJobExecutor.java@@ -54,12 +54,14 @@ import java.time.ZoneOffset;import java.time.temporal.ChronoUnit;import java.util.HashMap;import java.util.Map;+import java.util.Optional;import java.util.Queue;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicBoolean;import java.util.concurrent.atomic.AtomicReference;import org.apache.gravitino.connector.job.JobContext;import org.apache.gravitino.connector.job.JobExecutionInfo;+import org.apache.gravitino.connector.job.JobSubmissionRejectedException;import org.apache.gravitino.exceptions.NoSuchJobException;import org.apache.gravitino.job.JobExecutorFactory;import org.apache.gravitino.job.JobHandle;@@ -199,6 +201,106 @@ public class TestK8sJobExecutor {Assertions.assertEquals(driverFinishedAt, succeeded.finishedAt());}+ @Test+ public void testFindSubmittedJob() {+ // Nothing is submitted for the job yet.+ Assertions.assertEquals(+ Optional.empty(), executor.findSubmittedJob(context(1L), sparkTemplate()));++ String jobExecutionId = executor.submitJob(context(1L), sparkTemplate());+ Assertions.assertEquals(+ Optional.of(jobExecutionId), executor.findSubmittedJob(context(1L), sparkTemplate()));+ // The SparkApplication of one job is never found for another one.+ Assertions.assertEquals(+ Optional.empty(), executor.findSubmittedJob(context(2L), sparkTemplate()));++ // A SparkApplication with the name of the job that belongs to another job is not its execution.+ GenericKubernetesResource app = sparkApplication("gravitino-job-1");+ app.getMetadata().getLabels().put(K8sJobResourceUtils.LABEL_JOB_ID, "3");+ client+ .genericKubernetesResources(SparkApplicationUtils.SPARK_APPLICATION)+ .inNamespace("default")+ .resource(app)+ .update();+ Assertions.assertEquals(+ Optional.empty(), executor.findSubmittedJob(context(1L), sparkTemplate()));++ // A job the k8s job executor doesn't support is never submitted.+ ShellJobTemplate shellTemplate =+ ShellJobTemplate.builder().withName("shell-job").withExecutable("/bin/echo").build();+ Assertions.assertEquals(+ Optional.empty(), executor.findSubmittedJob(context(1L), shellTemplate));+ }++ @Test+ public void testFindSubmittedJobByNameAndNamespaceOnly() {+ String jobExecutionId = executor.submitJob(context(1L), sparkTemplate());++ // Only the name and the namespace of the SparkApplication are derived, so a job is still found+ // when the checks of a submission would reject it now, e.g. as the configurations changed.+ SparkJobTemplate rejectedNow =+ SparkJobTemplate.builder()+ .withName("user-job")+ .withExecutable("local:///opt/spark/examples/jars/spark-examples.jar")+ .withClassName("org.apache.spark.examples.SparkPi")+ .withConfigs(ImmutableMap.of("spark.master", "local[*]"))+ .build();+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> executor.submitJob(context(2L), rejectedNow));+ Assertions.assertEquals(+ Optional.of(jobExecutionId), executor.findSubmittedJob(context(1L), rejectedNow));++ // A job whose namespace is invalid is never submitted.+ SparkJobTemplate invalidNamespace =+ SparkJobTemplate.builder()+ .withName("user-job")+ .withExecutable("local:///opt/spark/examples/jars/spark-examples.jar")+ .withClassName("org.apache.spark.examples.SparkPi")+ .withConfigs(ImmutableMap.of(SparkApplicationUtils.SPARK_NAMESPACE, "Not_A_Namespace"))+ .build();+ Assertions.assertEquals(+ Optional.empty(), executor.findSubmittedJob(context(1L), invalidNamespace));+ }++ @Test+ public void testFindSubmittedJobWhileApiServerUnreachable() {+ try (KubernetesClient unreachable =+ new KubernetesClientBuilder()+ .withConfig(+ new ConfigBuilder(Config.empty())+ .withMasterUrl("http://127.0.0.1:1")+ .withRequestRetryBackoffLimit(0)+ .build())+ .build()) {+ executor.initialize(+ TestSparkApplicationUtils.newConfigs(+ ImmutableMap.of(K8sJobExecutorConfigs.STATUS_CACHE_TTL_MS, "0")),+ unreachable);++ // The lookup fails rather than finds nothing, so the job isn't marked as FAILED.+ KubernetesClientException first =+ Assertions.assertThrows(+ KubernetesClientException.class,+ () -> executor.findSubmittedJob(context(1L), sparkTemplate()));+ Assertions.assertTrue(K8sJobExecutor.isUnreachable(first), first.toString());+ // The other queries fail right away without another request.+ KubernetesClientException next =+ Assertions.assertThrows(+ KubernetesClientException.class,+ () -> executor.findSubmittedJob(context(2L), sparkTemplate()));+ Assertions.assertSame(first, next.getCause());+ }+ }++ @Test+ public void testFindSubmittedJobAfterCancellation() {+ String jobExecutionId = executor.submitJob(context(1L), sparkTemplate());+ executor.cancelJob(jobExecutionId);++ Assertions.assertEquals(+ Optional.empty(), executor.findSubmittedJob(context(1L), sparkTemplate()));+ }+@Testpublic void testStatusCacheFallsBackToGet() {executor.initialize(@@ -656,8 +758,30 @@ public class TestK8sJobExecutor {.resource(created).update();- Assertions.assertThrows(- IllegalStateException.class, () -> executor.submitJob(context(1L), sparkTemplate()));+ // Its pods may still run, so it is not a confirmed rejection, and recovery still finds it.+ RuntimeException e =+ Assertions.assertThrows(+ RuntimeException.class, () -> executor.submitJob(context(1L), sparkTemplate()));+ Assertions.assertFalse(e instanceof JobSubmissionRejectedException, e.toString());+ Assertions.assertFalse(e instanceof IllegalArgumentException, e.toString());+ Assertions.assertTrue(executor.findSubmittedJob(context(1L), sparkTemplate()).isPresent());+ }++ @Test+ public void testConflictWithResourceGoneIsNotRejected() {+ // A retried request conflicts with the SparkApplication it created, which is deleted before+ // it is read back.+ server+ .expect()+ .post()+ .withPath(APPS_PATH)+ .andReturn(409, new StatusBuilder().withCode(409).build())+ .once();++ IllegalStateException e =+ Assertions.assertThrows(+ IllegalStateException.class, () -> executor.submitJob(context(1L), sparkTemplate()));+ Assertions.assertEquals(409, ((KubernetesClientException) e.getCause()).getCode());}@Test@@ -1008,7 +1132,8 @@ public class TestK8sJobExecutor {.create();Assertions.assertThrows(- IllegalStateException.class, () -> executor.submitJob(context(1L), sparkTemplate()));+ JobSubmissionRejectedException.class,+ () -> executor.submitJob(context(1L), sparkTemplate()));}@Test@@ -1540,4 +1665,50 @@ public class TestK8sJobExecutor {.withArguments(ImmutableList.of("10")).build();}++ @Test+ public void testFailedCleanupLeavesAcceptedExecution() {+ GenericKubernetesResource accepted =+ SparkApplicationUtils.buildSparkApplication(+ context(1L), sparkTemplate(), TestSparkApplicationUtils.newConfigs(ImmutableMap.of()));+ client+ .genericKubernetesResources(SparkApplicationUtils.SPARK_APPLICATION)+ .inNamespace("default")+ .resource(accepted)+ .create();+ server+ .expect()+ .post()+ .withPath(APPS_PATH)+ .andReturn(500, new StatusBuilder().withCode(500).withMessage("etcd timeout").build())+ .always();+ server+ .expect()+ .get()+ .withPath(APPS_PATH + "/gravitino-job-1")+ .andReturn(403, new StatusBuilder().withCode(403).build())+ .once();+ try (KubernetesClient noRetries = clientWithoutRetries(client.getConfiguration())) {+ executor.initialize(TestSparkApplicationUtils.newConfigs(ImmutableMap.of()), noRetries);+ KubernetesClientException failure =+ Assertions.assertThrows(+ KubernetesClientException.class,+ () -> executor.submitJob(context(1L), sparkTemplate()));+ Assertions.assertEquals(500, failure.getCode());+ }+ // The accepted execution survives the failed submission and can run when the operator recovers.+ Assertions.assertNotNull(sparkApplication("gravitino-job-1"));+ }++ @Test+ public void testRecoveryTracksDeletingApplication() {+ String execution = executor.submitJob(context(1L), sparkTemplate());+ GenericKubernetesResource app = sparkApplication("gravitino-job-1");+ app.getMetadata().setDeletionTimestamp(Instant.now().toString());+ // The mock CRUD dispatcher removes a resource once deletionTimestamp is set. Return a+ // foreground deletion that is still waiting for its pods instead.+ server.expect().get().withPath(APPS_PATH + "/gravitino-job-1").andReturn(200, app).always();+ Assertions.assertEquals(+ Optional.of(execution), executor.findSubmittedJob(context(1L), sparkTemplate()));+ }}