fix(emr-serverless): honour a cancel's grace period, keep flexExecution and check architecture (#9184)

CancelJobRun ignored its shutdownGracePeriodInSeconds and stopped a
run's driver at once, StartJobRun dropped flexExecution, and
CreateApplication and UpdateApplication took any architecture.

- From emr-7.9.0 a RUNNING run in the docker mode gets the grace
  period it is cancelled with, "during which the job can perform
  cleanup operations prior to final termination". Its driver gets
  SIGTERM through an init process, the run is CANCELLING until the
  driver ends, and a driver still running when the period ends is
  stopped. A batch run has none by default and a streaming run 120
  seconds; a run not yet RUNNING, or on an earlier release, is stopped
  at once, and a value other than 0 or 15 to 1800 is refused with
  ValidationException, in Floci's words. Step Functions' cancelJobRun
  passes its ShutdownGracePeriodInSeconds on, read in either case.
- A run keeps its flexExecution's one member, enabled, which GetJobRun,
  ListJobRuns and ListJobRunAttempts give back; an enabled that is not
  a boolean is refused with SerializationException.
- An architecture other than ARM64 or X86_64 is refused with the
  framework's ValidationException, from the one list CloudFormation's
  application provisioner checks too.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-22 02:57:31 -04:00
1 parent a9bea6567c
commit 8bc759420f
16 files changed
+388 -27

No files matched your search

@@ -528,4 +528,48 @@ public class EmrServerlessIntegrationTest {
.body("application.releaseLabel", equalTo("emr-7.5.0"))
.body("application.maximumCapacity.cpu", equalTo("100 vCPU"));
}
@Test
@Order(14)
void anArchitectureOutsideItsEnumIsRefusedOnCreateAndUpdate() {
givenReq()
.body("""
{"releaseLabel": "emr-7.5.0", "type": "SPARK", "clientToken": "%s", "architecture": "x86"}
""".formatted(UUID.randomUUID()))
.when()
.post("/applications")
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", containsString("Value 'x86' at 'architecture' failed to satisfy constraint"));
String graviton = givenReq()
.body("""
{"releaseLabel": "emr-7.5.0", "type": "SPARK", "clientToken": "%s", "architecture": "ARM64"}
""".formatted(UUID.randomUUID()))
.when()
.post("/applications")
.then()
.statusCode(200)
.extract().path("applicationId");
try {
givenReq()
.body("""
{"clientToken": "%s", "architecture": "ARM"}
""".formatted(UUID.randomUUID()))
.when()
.patch("/applications/" + graviton)
.then()
.statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", containsString("Value 'ARM' at 'architecture' failed to satisfy constraint"));
givenReq()
.when()
.get("/applications/" + graviton)
.then()
.statusCode(200)
.body("application.architecture", equalTo("ARM64"));
} finally {
EmrServerlessRequests.deleteApplication("us-east-1", graviton);
}
}
}
@@ -741,4 +741,31 @@ class EmrServerlessJobRunIntegrationTest {
EmrServerlessRequests.emrServerless("eu-west-1").when().get("/applications/" + applicationId + "/jobruns")
.then().statusCode(200).body("jobRuns", empty());
}
@Test
void aRunKeepsItsFlexExecutionAndCancelJobRunChecksItsGracePeriod() {
String applicationId = createApplication("");
String jobRunId = startedRunId(applicationId, sparkRun(UUID.randomUUID().toString(),
", \"mode\": \"STREAMING\", \"flexExecution\": {\"enabled\": true}"));
String run = "/applications/" + applicationId + "/jobruns/" + jobRunId;
givenReq().when().get(run).then().statusCode(200).body("jobRun.flexExecution.enabled", equalTo(true));
givenReq().when().get("/applications/" + applicationId + "/jobruns").then().statusCode(200)
.body("jobRuns.find { it.id == '" + jobRunId + "' }.flexExecution.enabled", equalTo(true));
startJobRun(applicationId,
sparkRun(UUID.randomUUID().toString(), ", \"flexExecution\": {\"enabled\": \"yes\"}"))
.then().statusCode(400)
.body("__type", equalTo("SerializationException"));
givenReq().queryParam("shutdownGracePeriodInSeconds", "soon").when().delete(run)
.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("shutdownGracePeriodInSeconds must be an integer."));
givenReq().queryParam("shutdownGracePeriodInSeconds", 10).when().delete(run)
.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", equalTo("shutdownGracePeriodInSeconds must be 0, or from 15 to 1800 seconds."));
givenReq().when().get(run).then().statusCode(200).body("jobRun.state", equalTo("RUNNING"));
givenReq().queryParam("shutdownGracePeriodInSeconds", 30).when().delete(run).then().statusCode(200);
givenReq().when().get(run).then().statusCode(200).body("jobRun.state", equalTo("CANCELLED"));
}
}
@@ -1035,6 +1035,113 @@ class EmrServerlessJobRunServiceTest {
assertTrue(tasks.isEmpty());
}
@Test
void aRunCancelledWithAGracePeriodGetsSigtermAndMayEndByItselfUntilThePeriodEnds() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
String graceful = application("graceful", "emr-7.9.0", null);
String ended = service.startJobRun(graceful, request(null, null)).getJobRunId();
List<String> cancelling = new ArrayList<>();
runner.whileRunning = () -> {
cancelling.add(service.cancelJobRun(graceful, ended, 60).getState());
// A second cancel while it is CANCELLING changes nothing.
service.cancelJobRun(graceful, ended, 0);
clock.advance(Duration.ofSeconds(59));
};
runNext();
runNext();
assertEquals(List.of("CANCELLING"), cancelling);
assertEquals(List.of(false, false), runner.cancelledAsRunning, "its driver may run on within the period");
assertEquals(Set.of(ended), runner.interrupted);
assertTrue(runner.stopped.isEmpty());
assertTrue(tasks.isEmpty());
assertTrue(runner.jobs.get(0).interruptible(), "its driver gets the SIGTERM through an init process");
assertEquals("CANCELLED", service.getJobRun(graceful, ended, null).getState());
String outlasted = service.startJobRun(graceful, request(null, null)).getJobRunId();
runner.cancelledAsRunning.clear();
runner.whileRunning = () -> {
service.cancelJobRun(graceful, outlasted, 15);
clock.advance(Duration.ofSeconds(15));
};
runNext();
runNext();
assertEquals(List.of(false, true), runner.cancelledAsRunning, "its driver is stopped when the period ends");
assertEquals("CANCELLED", service.getJobRun(graceful, outlasted, null).getState());
}
@Test
void aStreamingRunHasAGracePeriodByDefaultAndABatchRunOrAnEarlierReleaseNone() {
FakeRunner runner = new FakeRunner();
EmrServerlessJobRunService service = dockerService(runner);
String graceful = application("graceful", "emr-7.9.0", null);
String earlier = application("earlier", "emr-7.8.0", null);
String streaming = service.startJobRun(graceful, request("STREAMING", null)).getJobRunId();
runner.whileRunning = () -> {
service.cancelJobRun(graceful, streaming);
clock.advance(Duration.ofSeconds(119));
};
runNext();
runNext();
String batch = service.startJobRun(graceful, request(null, null)).getJobRunId();
runner.whileRunning = () -> service.cancelJobRun(graceful, batch);
runNext();
runNext();
String immediate = service.startJobRun(graceful, request("STREAMING", null)).getJobRunId();
runner.whileRunning = () -> service.cancelJobRun(graceful, immediate, 0);
runNext();
runNext();
String older = service.startJobRun(earlier, request("STREAMING", null)).getJobRunId();
runner.whileRunning = () -> service.cancelJobRun(earlier, older, 60);
runNext();
runNext();
assertEquals(Set.of(streaming), runner.interrupted);
assertEquals(Set.of(batch, immediate, older), runner.stopped);
assertEquals(List.of(false, false, false, true, false, true, false, true), runner.cancelledAsRunning);
assertFalse(runner.jobs.get(3).interruptible(), "an earlier release's driver needs no init process");
for (String run : List.of(streaming, batch, immediate)) {
assertEquals("CANCELLED", service.getJobRun(graceful, run, null).getState());
}
assertEquals("CANCELLED", service.getJobRun(earlier, older, null).getState());
}
@Test
void aGracePeriodOutsideItsRangeIsRefused() {
EmrServerlessJobRunService service = service(60);
String running = service.startJobRun(applicationId, request(null, null)).getJobRunId();
for (int seconds : List.of(14, 1801, -1)) {
AwsException refused = assertThrows(AwsException.class,
() -> service.cancelJobRun(applicationId, running, seconds));
assertEquals("ValidationException", refused.getErrorCode());
assertEquals("shutdownGracePeriodInSeconds must be 0, or from 15 to 1800 seconds.", refused.getMessage());
}
assertEquals("CANCELLED", service.cancelJobRun(applicationId, running, 1800).getState());
}
@Test
void aRunKeepsItsFlexExecutionAndANonBooleanEnabledIsRefused() {
EmrServerlessJobRunService service = service(0);
StartJobRunRequest flex = request(null, null);
// A member FlexExecution does not have is not kept.
flex.setFlexExecution(Map.of("enabled", true, "capacity", "spare"));
String jobRunId = service.startJobRun(applicationId, flex).getJobRunId();
assertEquals(Map.of("enabled", true), service.getJobRun(applicationId, jobRunId, null).getFlexExecution());
JobRunSummary listed = service.listJobRuns(applicationId, null, null, null, null, null, null).items().stream()
.filter(summary -> jobRunId.equals(summary.getId())).findFirst().orElseThrow();
assertEquals(Map.of("enabled", true), listed.getFlexExecution());
assertEquals(Map.of("enabled", true),
service.listJobRunAttempts(applicationId, jobRunId, null, null).items().get(0).getFlexExecution());
StartJobRunRequest notBoolean = request(null, null);
notBoolean.setFlexExecution(Map.of("enabled", "yes"));
AwsException refused = assertThrows(AwsException.class, () -> service.startJobRun(applicationId, notBoolean));
assertEquals("SerializationException", refused.getErrorCode());
}
@Test
void eachAttemptIsLaunchedWhileItsApplicationCannotBeDeleted() {
FakeRunner runner = new FakeRunner();
@@ -1739,6 +1846,7 @@ class EmrServerlessJobRunServiceTest {
private static final class FakeRunner implements SparkJobRunner {
final List<Job> jobs = new ArrayList<>();
final Set<String> stopped = new HashSet<>();
final Set<String> interrupted = new HashSet<>();
final List<String> driversStarted = new ArrayList<>();
// What progress.cancelled() said once the driver ran, and again after whileRunning.
final List<Boolean> cancelledAsRunning = new ArrayList<>();
@@ -1789,6 +1897,11 @@ class EmrServerlessJobRunServiceTest {
stopped.add(runId);
}
@Override
public void interrupt(String runId) {
interrupted.add(runId);
}
@Override
public void removeLeftoverDrivers(String service) {
// A test's drivers live no longer than its runs.
@@ -401,7 +401,9 @@ class EmrServerlessServiceTest {
}
UpdateApplicationRequest other = new UpdateApplicationRequest();
other.setMaximumCapacity(capacity("200 vCPU"));
setter.invoke(other, someValue(setter.getParameterTypes()[0]));
// An architecture in the model's enum, which a value outside it would be refused for first.
setter.invoke(other, "setArchitecture".equals(setter.getName()) ? "ARM64"
: someValue(setter.getParameterTypes()[0]));
AwsException refusal = assertThrows(AwsException.class,
() -> service.updateApplication(applicationId, other), setter.getName());
assertEquals("ValidationException", refusal.getErrorCode());
@@ -31,6 +31,7 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -126,37 +127,37 @@ class AslExecutorEmrServerlessSyncTest {
assertEquals("data", run.path("Tags").path("team").asText());
assertEquals("4g", run.path("ConfigurationOverrides").path("ApplicationConfiguration").path(0)
.path("Properties").path("spark.executor.memory").asText());
verify(jobRuns, never()).cancelJobRun(anyString(), anyString());
verify(jobRuns, never()).cancelJobRun(anyString(), anyString(), any());
}
@Test
void startJobRunSyncCancelsItsRunWhenTheTaskTimesOut() {
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("RUNNING"));
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID)).thenReturn(jobRun("CANCELLED"));
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("CANCELLED"));
Execution execution = run(timingOut("startJobRun.sync"), START_JOB_RUN);
assertEquals("FAILED", execution.getStatus());
assertEquals("States.Timeout", execution.getError());
verify(jobRuns).cancelJobRun(APPLICATION_ID, JOB_RUN_ID);
verify(jobRuns).cancelJobRun(APPLICATION_ID, JOB_RUN_ID, null);
}
@Test
void startJobRunSyncStillTimesOutWhenEmrServerlessRefusesTheCancel() {
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("RUNNING"));
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID))
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID, null))
.thenThrow(new AwsException("ValidationException", "Job run is not in a cancellable state", 400));
Execution execution = run(timingOut("startJobRun.sync"), START_JOB_RUN);
assertEquals("States.Timeout", execution.getError());
verify(jobRuns).cancelJobRun(APPLICATION_ID, JOB_RUN_ID);
verify(jobRuns).cancelJobRun(APPLICATION_ID, JOB_RUN_ID, null);
}
@Test
void anInternalErrorCancellingTheRunFailsTheTaskWithIt() {
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("RUNNING"));
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID))
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID, null))
.thenThrow(new AwsException("InternalServerException", "Request processing failed", 500));
Execution execution = run(timingOut("startJobRun.sync"), START_JOB_RUN);
@@ -168,7 +169,8 @@ class AslExecutorEmrServerlessSyncTest {
@Test
void aFaultWhileCancellingTheRunIsNotPassedOver() {
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("RUNNING"));
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID)).thenThrow(new IllegalStateException("store closed"));
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID, null))
.thenThrow(new IllegalStateException("store closed"));
Execution execution = run(timingOut("startJobRun.sync"), START_JOB_RUN);
@@ -179,7 +181,7 @@ class AslExecutorEmrServerlessSyncTest {
@Test
void cancelJobRunSyncFailsWhenTheRunSucceedsInstead() throws Exception {
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID)).thenReturn(jobRun("CANCELLING"));
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("CANCELLING"));
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("SUCCESS"));
Execution execution = run(task("cancelJobRun.sync"),
@@ -189,6 +191,33 @@ class AslExecutorEmrServerlessSyncTest {
assertEquals("SUCCESS", objectMapper.readTree(execution.getCause()).path("JobRun").path("State").asText());
}
@Test
void cancelJobRunSyncPassesItsGracePeriodOn() {
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID, 30)).thenReturn(jobRun("CANCELLING"));
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("CANCELLED"));
Execution execution = run(task("cancelJobRun.sync"), "{\"ApplicationId\": \"" + APPLICATION_ID
+ "\", \"JobRunId\": \"" + JOB_RUN_ID + "\", \"ShutdownGracePeriodInSeconds\": 30}");
assertEquals("SUCCEEDED", execution.getStatus());
verify(jobRuns).cancelJobRun(APPLICATION_ID, JOB_RUN_ID, 30);
}
@Test
void cancelJobRunSyncReadsItsGracePeriodInEitherCaseAndRefusesOneThatIsNotANumber() {
when(jobRuns.cancelJobRun(APPLICATION_ID, JOB_RUN_ID, 45)).thenReturn(jobRun("CANCELLING"));
when(jobRuns.getJobRun(APPLICATION_ID, JOB_RUN_ID, null)).thenReturn(jobRun("CANCELLED"));
String ids = "{\"applicationId\": \"" + APPLICATION_ID + "\", \"jobRunId\": \"" + JOB_RUN_ID + "\", ";
Execution lowercase = run(task("cancelJobRun.sync"), ids + "\"shutdownGracePeriodInSeconds\": 45}");
Execution structure = run(task("cancelJobRun.sync"), ids + "\"ShutdownGracePeriodInSeconds\": {}}");
assertEquals("SUCCEEDED", lowercase.getStatus());
verify(jobRuns).cancelJobRun(APPLICATION_ID, JOB_RUN_ID, 45);
assertEquals("FAILED", structure.getStatus());
verify(jobRuns, times(1)).cancelJobRun(anyString(), anyString(), any());
}
@Test
void createApplicationSyncDeletesTheApplicationWhenTheTaskTimesOut() {
Application creating = application("CREATING");