feat(emr-serverless): retry a failed job run as its retry policy allows (#6894)

In the docker runner mode a job run's retryPolicy was stored and
returned, but a run whose driver failed was never tried again: every
run was its one attempt. Now, on release 7.1.0 or later, "EMR
Serverless releases 7.1.0 and higher include support for job
resiliency", a run whose driver fails is tried again as the user
guide's "Job resiliency" gives it:

- a BATCH run until it has made maxAttempts attempts, "The default is
  1, which means to not rerun the job";
- a STREAMING run, which "EMR Serverless indefinitely retries", until
  it has failed maxFailedAttemptsPerHour times within an hour, "The
  default is five".

The failed attempt ends FAILED with its stateDetails, and the next is
SCHEDULED again and runs its driver from the beginning, "its own set
of logs" under attempts/<n>/ in S3 and CloudWatch Logs. A cancelled
run, one past its timeout ("Cancelling: ... or the job run has timed
out"), one Floci's own shutdown stopped and one whose application is
gone are not tried again; a retry is admitted while its application
cannot be deleted, as the first attempt is.
GetJobRun without attempt returns "the latest attempt", and with one
an earlier attempt as it ended; ListJobRunAttempts lists them all,
oldest first, each with its own createdAt and updatedAt. No source says
whether a run's timeout spans its attempts; Floci applies it to each.
Floci sends no EMR Serverless events, so the job run retry event is
not sent.

StartJobRun holds retryPolicy to "Accepted values are 1 to 10,
inclusive" for both members: outside that range is a
ValidationException in the model's constraint form, and a member that
is not an integer a SerializationException, as Smithy's restJson1
malformed-request tests have it.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-29 00:34:34 -05:00
1 parent c9c1c0990b
commit 66a5c05037
5 files changed
+413 -78

No files matched your search

@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.services.emrserverless.model.Application;
import io.github.hectorvent.floci.services.emrserverless.model.CreateApplicationRequest;
import io.github.hectorvent.floci.services.emrserverless.model.JobDriver;
import io.github.hectorvent.floci.services.emrserverless.model.JobRun;
import io.github.hectorvent.floci.services.emrserverless.model.JobRunAttemptSummary;
import io.github.hectorvent.floci.services.emrserverless.model.JobRunRecord;
import io.github.hectorvent.floci.services.emrserverless.model.MonitoringConfiguration;
import io.github.hectorvent.floci.services.emrserverless.model.RuntimeConfiguration;
@@ -34,6 +35,7 @@ import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
@@ -67,12 +69,7 @@ class EmrServerlessJobRunServiceTest {
when(iamService.resolveCallerArn(any())).thenReturn(Optional.empty());
store = AccountAwareStorageBackend.inMemory(ACCOUNT_ID);
CreateApplicationRequest create = new CreateApplicationRequest();
create.setName("jobs");
create.setReleaseLabel("emr-7.5.0");
create.setType("SPARK");
create.setClientToken(UUID.randomUUID().toString());
applicationId = applications.createApplication(create).getApplicationId();
applicationId = application("jobs", "emr-7.5.0", null);
}
private EmrServerlessJobRunService service(int runDurationSeconds) {
@@ -271,13 +268,7 @@ class EmrServerlessJobRunServiceTest {
void aRunsDriverOutputGoesToCloudWatchWhenItsOwnOrTheApplicationsLoggingIsEnabled() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
CreateApplicationRequest create = new CreateApplicationRequest();
create.setName("watched");
create.setReleaseLabel("emr-7.5.0");
create.setType("SPARK");
create.setClientToken(UUID.randomUUID().toString());
create.setMonitoringConfiguration(cloudWatchLogging(Map.of("enabled", true)));
String watched = applications.createApplication(create).getApplicationId();
String watched = application("watched", "emr-7.5.0", cloudWatchLogging(Map.of("enabled", true)));
StartJobRunRequest own = request(null, null);
own.setConfigurationOverrides(Map.of("monitoringConfiguration", Map.of("cloudWatchLoggingConfiguration",
Map.of("enabled", true, "logGroupName", "spark-jobs", "logStreamNamePrefix", "nightly",
@@ -343,13 +334,7 @@ class EmrServerlessJobRunServiceTest {
void aRunsDriverLogsGoUnderItsOwnS3LogUriOrElseTheApplications() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
CreateApplicationRequest create = new CreateApplicationRequest();
create.setName("logged");
create.setReleaseLabel("emr-7.5.0");
create.setType("SPARK");
create.setClientToken(UUID.randomUUID().toString());
create.setMonitoringConfiguration(s3LogUri("s3://logs/app-level"));
String logged = applications.createApplication(create).getApplicationId();
String logged = application("logged", "emr-7.5.0", s3LogUri("s3://logs/app-level"));
StartJobRunRequest ownLogUri = request(null, null);
ownLogUri.setConfigurationOverrides(Map.of("monitoringConfiguration",
Map.of("s3MonitoringConfiguration", Map.of("logUri", "s3://logs/job-level/"))));
@@ -387,6 +372,219 @@ class EmrServerlessJobRunServiceTest {
EmrServerlessJobRunService.driverLogFolder(app, run("emr-7.0.0", "STREAMING", null)));
}
@Test
void aBatchRunWhoseDriverFailsIsTriedAgainUntilItSucceedsEachAttemptWithItsOwnLogs() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
String logged = application("logged", "emr-7.5.0", s3LogUri("s3://logs/"));
StartJobRunRequest resilient = request(null, null);
resilient.setRetryPolicy(Map.of("maxAttempts", 3));
String jobRunId = service.startJobRun(logged, resilient).getJobRunId();
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
runNext();
JobRun scheduled = service.getJobRun(logged, jobRunId, null);
clock.advance(Duration.ofSeconds(10));
runNext();
runner.outcome = SparkJobRunner.Outcome.exitedWith(0);
clock.advance(Duration.ofSeconds(10));
runNext();
assertEquals(List.of("SCHEDULED", "2"), List.of(scheduled.getState(), String.valueOf(scheduled.getAttempt())));
JobRun latest = service.getJobRun(logged, jobRunId, null);
assertEquals("SUCCESS", latest.getState());
assertEquals(3, latest.getAttempt());
// "the attempt generates its own set of logs".
String driver = "s3://logs/applications/" + logged + "/jobs/" + jobRunId + "/attempts/%d/SPARK_DRIVER/";
assertEquals(List.of(driver.formatted(1), driver.formatted(2), driver.formatted(3)),
runner.jobs.stream().map(SparkJobRunner.Job::logFolder).toList());
JobRun first = service.getJobRun(logged, jobRunId, 1);
assertEquals("FAILED", first.getState());
assertEquals("Job run failed: the Spark driver exited with code 1.", first.getStateDetails());
assertEquals(1, first.getAttempt());
List<JobRunAttemptSummary> attempts = service.listJobRunAttempts(logged, jobRunId, null, null).items();
assertEquals(List.of(1, 2, 3), attempts.stream().map(JobRunAttemptSummary::getAttempt).toList());
assertEquals(List.of("FAILED", "FAILED", "SUCCESS"),
attempts.stream().map(JobRunAttemptSummary::getState).toList());
// Each attempt after the first is made as the one before it fails.
assertEquals(List.of(attempts.get(0).getUpdatedAt(), attempts.get(1).getUpdatedAt()),
List.of(attempts.get(1).getCreatedAt(), attempts.get(2).getCreatedAt()));
assertEquals(10, Duration.between(attempts.get(1).getCreatedAt(), attempts.get(2).getCreatedAt()).toSeconds());
assertEquals(List.of(latest.getCreatedAt(), latest.getCreatedAt(), latest.getCreatedAt()),
attempts.stream().map(JobRunAttemptSummary::getJobCreatedAt).toList());
}
@Test
void aBatchRunIsFailedOnceItHasMadeItsMaxAttempts() {
FakeRunner runner = new FakeRunner();
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
EmrServerlessJobRunService service = dockerService(runner);
StartJobRunRequest resilient = request(null, null);
resilient.setRetryPolicy(Map.of("maxAttempts", 2));
String jobRunId = service.startJobRun(applicationId, resilient).getJobRunId();
runNext();
runNext();
JobRun failed = service.getJobRun(applicationId, jobRunId, null);
assertEquals(List.of("FAILED", "2"), List.of(failed.getState(), String.valueOf(failed.getAttempt())));
assertEquals(2, runner.jobs.size());
assertTrue(tasks.isEmpty());
}
@Test
void aRunIsNotTriedAgainWithoutARetryPolicyOrBeforeRelease710() {
FakeRunner runner = new FakeRunner();
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
EmrServerlessJobRunService service = dockerService(runner);
StartJobRunRequest resilient = request(null, null);
resilient.setRetryPolicy(Map.of("maxAttempts", 3));
String once = service.startJobRun(applicationId, request(null, null)).getJobRunId();
// "EMR Serverless releases 7.1.0 and higher include support for job resiliency".
String older = application("older", "emr-7.0.0", null);
String beforeResiliency = service.startJobRun(older, resilient).getJobRunId();
runNext();
runNext();
assertEquals(1, service.getJobRun(applicationId, once, null).getAttempt());
assertEquals("FAILED", service.getJobRun(applicationId, once, null).getState());
assertEquals(1, service.getJobRun(older, beforeResiliency, null).getAttempt());
assertTrue(tasks.isEmpty());
}
@Test
void aStreamingRunIsTriedAgainUntilItFailsMaxFailedAttemptsPerHourWithinAnHour() {
FakeRunner runner = new FakeRunner();
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
EmrServerlessJobRunService service = dockerService(runner);
StartJobRunRequest streaming = request("STREAMING", null);
streaming.setRetryPolicy(Map.of("maxFailedAttemptsPerHour", 2));
String jobRunId = service.startJobRun(applicationId, streaming).getJobRunId();
runNext();
// The first failure is more than an hour old by the second, so it no longer counts.
clock.advance(Duration.ofMinutes(61));
runNext();
clock.advance(Duration.ofMinutes(10));
runNext();
JobRun failed = service.getJobRun(applicationId, jobRunId, null);
assertEquals(List.of("FAILED", "3"), List.of(failed.getState(), String.valueOf(failed.getAttempt())));
assertTrue(tasks.isEmpty());
}
@Test
void aCancelledRunOrOnePastItsTimeoutIsNotTriedAgain() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
StartJobRunRequest resilient = request(null, null);
resilient.setRetryPolicy(Map.of("maxAttempts", 3));
String cancelled = service.startJobRun(applicationId, resilient).getJobRunId();
runner.whileRunning = () -> service.cancelJobRun(applicationId, cancelled);
runNext();
runNext();
runner.whileRunning = () -> { };
StartJobRunRequest timed = request(null, 5L);
timed.setRetryPolicy(Map.of("maxAttempts", 3));
String timedOut = service.startJobRun(applicationId, timed).getJobRunId();
runner.outcome = SparkJobRunner.Outcome.outOfTime();
runNext();
assertEquals("CANCELLED", service.getJobRun(applicationId, cancelled, null).getState());
assertEquals("CANCELLED", service.getJobRun(applicationId, timedOut, null).getState());
assertEquals(List.of(1, 1), List.of(service.getJobRun(applicationId, cancelled, null).getAttempt(),
service.getJobRun(applicationId, timedOut, null).getAttempt()));
assertTrue(tasks.isEmpty());
}
@Test
void eachAttemptIsLaunchedWhileItsApplicationCannotBeDeleted() {
FakeRunner runner = new FakeRunner();
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
// Whether the lock DeleteApplication takes was held as each attempt's driver was handed to its thread.
List<Boolean> launchedHoldingTheApplications = new ArrayList<>();
EmrServerlessJobRunService service = new EmrServerlessJobRunService(store, applications, iamService,
new RegionResolver(REGION, ACCOUNT_ID), null, objectMapper, 0, clock, runner, task -> {
launchedHoldingTheApplications.add(Thread.holdsLock(applications));
tasks.add(task);
});
StartJobRunRequest resilient = request(null, null);
resilient.setRetryPolicy(Map.of("maxAttempts", 2));
service.startJobRun(applicationId, resilient);
runNext();
assertEquals(List.of(true, true), launchedHoldingTheApplications);
}
@Test
void aRunWhoseApplicationIsDeletedWhileItsDriverRunsIsNotTriedAgain() {
FakeRunner runner = new FakeRunner();
runner.outcome = SparkJobRunner.Outcome.exitedWith(1);
EmrServerlessJobRunService service = dockerService(runner);
StartJobRunRequest resilient = request(null, null);
resilient.setRetryPolicy(Map.of("maxAttempts", 3));
String jobRunId = service.startJobRun(applicationId, resilient).getJobRunId();
runner.whileRunning = () -> {
applications.stopApplication(applicationId);
applications.deleteApplication(applicationId);
};
runNext();
JobRun failed = store.get(jobRunId).orElseThrow().getJobRun();
assertEquals(List.of("FAILED", "1"), List.of(failed.getState(), String.valueOf(failed.getAttempt())));
assertTrue(tasks.isEmpty());
}
@Test
void aRetryPolicyMemberOutsideOneToTenOrNotAnIntegerIsRefused() {
EmrServerlessJobRunService service = service(0);
assertEquals("1 validation error detected: Value '0' at 'retryPolicy.maxAttempts' failed to satisfy "
+ "constraint: Member must have value greater than or equal to 1",
refused(service, Map.of("maxAttempts", 0), "ValidationException"));
assertEquals("1 validation error detected: Value '11' at 'retryPolicy.maxFailedAttemptsPerHour' failed to "
+ "satisfy constraint: Member must have value less than or equal to 10",
refused(service, Map.of("maxFailedAttemptsPerHour", 11), "ValidationException"));
// As Smithy's restJson1 malformed-request tests have it: a string, a boolean or a fraction for an integer.
for (Object malformed : List.of("3", true, 2.5)) {
assertEquals("retryPolicy.maxAttempts must be an integer",
refused(service, Map.of("maxAttempts", malformed), "SerializationException"));
}
StartJobRunRequest bounds = request(null, null);
bounds.setRetryPolicy(Map.of("maxAttempts", 10, "maxFailedAttemptsPerHour", 1));
assertEquals(Map.of("maxAttempts", 10, "maxFailedAttemptsPerHour", 1),
service.startJobRun(applicationId, bounds).getRetryPolicy());
}
// The message StartJobRun refuses a run with retryPolicy with, as errorCode with HTTP 400.
private String refused(EmrServerlessJobRunService service, Map<String, Object> retryPolicy, String errorCode) {
StartJobRunRequest request = request(null, null);
request.setRetryPolicy(retryPolicy);
AwsException refusal = assertThrows(AwsException.class, () -> service.startJobRun(applicationId, request));
assertEquals(List.of(errorCode, 400), List.of(refusal.getErrorCode(), refusal.getHttpStatus()));
return refusal.getMessage();
}
// A SPARK application on releaseLabel, with monitoring as its monitoring configuration (null for none).
private String application(String name, String releaseLabel, MonitoringConfiguration monitoring) {
CreateApplicationRequest create = applicationRequest(name, releaseLabel, "SPARK");
create.setMonitoringConfiguration(monitoring);
return applications.createApplication(create).getApplicationId();
}
// The request for an application of type on releaseLabel, which a test adds to as it needs.
private static CreateApplicationRequest applicationRequest(String name, String releaseLabel, String type) {
CreateApplicationRequest create = new CreateApplicationRequest();
create.setName(name);
create.setReleaseLabel(releaseLabel);
create.setType(type);
create.setClientToken(UUID.randomUUID().toString());
return create;
}
private static MonitoringConfiguration s3LogUri(String logUri) {
MonitoringConfiguration monitoring = new MonitoringConfiguration();
monitoring.setProperty("s3MonitoringConfiguration", Map.of("logUri", logUri));
@@ -400,6 +598,7 @@ class EmrServerlessJobRunServiceTest {
run.setReleaseLabel(releaseLabel);
run.setMode(mode);
run.setRetryPolicy(maxAttempts != null ? Map.of("maxAttempts", maxAttempts) : null);
run.setAttempt(1);
return run;
}
@@ -442,11 +641,7 @@ class EmrServerlessJobRunServiceTest {
RuntimeConfiguration defaults = new RuntimeConfiguration();
defaults.setMember("classification", "spark-defaults");
defaults.setMember("properties", Map.of("spark.executor.cores", "4", "spark.app.name", "from-app"));
CreateApplicationRequest create = new CreateApplicationRequest();
create.setName("configured-" + releaseLabel);
create.setReleaseLabel(releaseLabel);
create.setType("SPARK");
create.setClientToken(UUID.randomUUID().toString());
CreateApplicationRequest create = applicationRequest("configured-" + releaseLabel, releaseLabel, "SPARK");
create.setRuntimeConfiguration(List.of(defaults));
return applications.createApplication(create).getApplicationId();
}
@@ -527,12 +722,8 @@ class EmrServerlessJobRunServiceTest {
@Test
void aHiveRunFailsWithoutRunning() {
CreateApplicationRequest create = new CreateApplicationRequest();
create.setName("hive");
create.setReleaseLabel("emr-7.5.0");
create.setType("HIVE");
create.setClientToken(UUID.randomUUID().toString());
String hive = applications.createApplication(create).getApplicationId();
String hive = applications.createApplication(applicationRequest("hive", "emr-7.5.0", "HIVE"))
.getApplicationId();
JobDriver.Hive query = new JobDriver.Hive();
query.setQuery("s3://bucket/queries/report.sql");
StartJobRunRequest request = request(null, null);