fix(emr): keep a cancelled running step's place until its driver is gone (#8351)

CancelSteps on a RUNNING step stopped its driver and started the next
PENDING step at once, but stopping a driver only asks for it: with a
step concurrency level of 1 the next step's driver could start beside
the cancelled one's. The Management Guide's "Cancel steps": "Canceling
a running step does not allow a pending step to start running, assuming
no change to stepConcurrencyLevel", and CancelSteps "is idempotent but
asynchronous".

In the docker runner mode a cancelled RUNNING step is now CANCEL_PENDING
while its driver stops, with the guide's step event for that state ("was
cancelled at Time and is pending cancellation", WARN), and keeps its
place among the running steps. Once its driver is gone, however it
ended, the step is CANCELLED, takes no ActionOnFailure, and the next
PENDING step starts. A second cancel answers SUBMITTED. A driver Floci's
own teardown stops leaves the step CANCEL_PENDING, as it leaves a
RUNNING one, and a restart cancels it, in either runner mode;
TerminateJobFlows cancels it at once. Until it is gone it also counts as
running for a failed step's CANCEL_AND_WAIT. In the immediate mode
nothing runs, so a cancelled step is still CANCELLED at once.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-14 15:18:49 -04:00
1 parent bbcc58f03b
commit 7981cadc7c
8 files changed
+303 -76

No files matched your search

@@ -38,6 +38,7 @@ final class EmrClusterLifecycle {
static final String TERMINATED = "TERMINATED";
static final String PENDING = "PENDING";
static final String COMPLETED = "COMPLETED";
static final String CANCEL_PENDING = "CANCEL_PENDING";
static final String CANCELLED = "CANCELLED";
static final String FAILED = "FAILED";
static final String TERMINATED_WITH_ERRORS = "TERMINATED_WITH_ERRORS";
@@ -148,22 +149,35 @@ final class EmrClusterLifecycle {
cluster.setStateChangeMessage(message);
cluster.setTerminatingDateTime(now);
for (EmrStep step : cluster.getSteps()) {
if (PENDING.equals(step.getState()) || RUNNING.equals(step.getState())) {
if (PENDING.equals(step.getState()) || holdsAPlace(step)) {
cancelStep(cluster, step, now, region);
}
}
}
/**
* CancelSteps for one step: null once it is cancelled, or why it cannot be. CancelSteps: "When you
* use Amazon EMR releases 5.28.0 and later, you can cancel steps that are in a PENDING or RUNNING
* state." A cancelled RUNNING step makes room for the next PENDING one.
* CancelSteps for one step: null once its cancel is under way, or why it cannot be. CancelSteps: "When you
* use Amazon EMR releases 5.28.0 and later, you can cancel steps that are in a PENDING or RUNNING state",
* and it "is idempotent but asynchronous". A RUNNING step whose driver runs is CANCEL_PENDING, "cancelled
* at Time and is pending cancellation" as the guide's step events put it, until its driver is gone
* ({@link #stepEnded}), and keeps its place among the running steps meanwhile: "Canceling a running step does
* not allow a pending step to start running, assuming no change to stepConcurrencyLevel". One that completes
* by time, nothing running it, is CANCELLED at once and makes room for the next PENDING one.
*/
String cancel(EmrCluster cluster, EmrStep step, Instant now, String region) {
if (CANCEL_PENDING.equals(step.getState())) {
return null;
}
boolean running = RUNNING.equals(step.getState()) && cancelsRunningSteps(cluster.getReleaseLabel());
if (!running && !PENDING.equals(step.getState())) {
return "Step is not in a cancellable state: " + step.getState();
}
if (running && !timed(step)) {
step.setState(CANCEL_PENDING);
events.queue(events.stepCancelPending(cluster, step, now), region);
execution.stop(step);
return null;
}
cancelStep(cluster, step, now, region);
if (running) {
runSteps(cluster, now, region);
@@ -271,7 +285,7 @@ final class EmrClusterLifecycle {
* cluster is done.
*/
private void runSteps(EmrCluster cluster, Instant at, String region) {
long running = cluster.getSteps().stream().filter(step -> RUNNING.equals(step.getState())).count();
long running = cluster.getSteps().stream().filter(EmrClusterLifecycle::holdsAPlace).count();
// The model allows 1 to 256; Floci stores any level it is given, and a lower one would never start a step.
int level = Math.max(1, cluster.getStepConcurrencyLevel());
List<EmrStep> started = new ArrayList<>();
@@ -303,10 +317,16 @@ final class EmrClusterLifecycle {
/**
* A step run for real has ended: COMPLETED when {@code failure} is null, otherwise FAILED, with
* {@code failure} as its FailureDetails message, and its ActionOnFailure taken. Either way the
* cluster goes on as it would once a step is done.
* {@code failure} as its FailureDetails message, and its ActionOnFailure taken. A CANCEL_PENDING one is
* CANCELLED, however its driver ended, and takes no action: "Canceling a running step does not trigger the
* step ActionOnFailure". Either way the cluster goes on as it would once a step is done.
*/
void stepEnded(EmrCluster cluster, EmrStep step, String failure, Instant at, String region) {
if (CANCEL_PENDING.equals(step.getState())) {
cancelStep(cluster, step, at, region);
runSteps(cluster, at, region);
return;
}
step.setEndDateTime(at);
if (failure == null) {
step.setState(COMPLETED);
@@ -340,7 +360,8 @@ final class EmrClusterLifecycle {
terminate(cluster, STEP_FAILURE, SHUT_DOWN_AS_STEP_FAILED, at, region);
return;
}
boolean othersRunning = cluster.getSteps().stream().anyMatch(other -> RUNNING.equals(other.getState()));
// The failed step is FAILED by now; one whose cancel is pending still runs until its driver is gone.
boolean othersRunning = cluster.getSteps().stream().anyMatch(EmrClusterLifecycle::holdsAPlace);
if (activates && "CANCEL_AND_WAIT".equals(action) && !othersRunning) {
if (cluster.isAutoTerminate()) {
terminate(cluster, STEP_FAILURE, SHUT_DOWN_AS_STEP_FAILED, at, region);
@@ -397,6 +418,11 @@ final class EmrClusterLifecycle {
return bootstrapping == null || !cluster.isBootstrapInContainer();
}
/** Whether {@code step} takes one of its cluster's StepConcurrencyLevel places: RUNNING, or CANCEL_PENDING. */
static boolean holdsAPlace(EmrStep step) {
return RUNNING.equals(step.getState()) || CANCEL_PENDING.equals(step.getState());
}
/** TERMINATED, or TERMINATED_WITH_ERRORS: the cluster has ended. */
static boolean isTerminated(String state) {
return TERMINATED.equals(state) || TERMINATED_WITH_ERRORS.equals(state);
@@ -88,18 +88,31 @@ public class EmrEventPublisher {
* FAILED.
*/
Event stepStatusChange(EmrCluster cluster, EmrStep step, String state) {
ObjectNode detail = objectMapper.createObjectNode();
detail.put("severity", switch (state) {
return stepEvent(cluster, step, state, switch (state) {
case "CANCELLED" -> "WARN";
case "FAILED" -> "ERROR";
default -> "INFO";
});
}, stepMessage(cluster, step, state));
}
/**
* {@code step} of {@code cluster} going CANCEL_PENDING, cancelled at {@code at}: WARN, as the guide's step events
* table has it.
*/
Event stepCancelPending(EmrCluster cluster, EmrStep step, Instant at) {
return stepEvent(cluster, step, "CANCEL_PENDING", "WARN", "Step " + named(step) + " in Amazon EMR cluster "
+ named(cluster) + " was cancelled at " + time(at) + " and is pending cancellation.");
}
private Event stepEvent(EmrCluster cluster, EmrStep step, String state, String severity, String message) {
ObjectNode detail = objectMapper.createObjectNode();
detail.put("severity", severity);
detail.put("actionOnFailure", step.getActionOnFailure());
detail.put("stepId", step.getId());
detail.put("name", step.getName());
detail.put("clusterId", cluster.getId());
detail.put("state", state);
detail.put("message", stepMessage(cluster, step, state));
detail.put("message", message);
return new Event(STEP_STATUS_CHANGE, detail.toString());
}
@@ -137,7 +150,7 @@ public class EmrEventPublisher {
}
private static String clusterMessage(EmrCluster cluster, String state, Instant at) {
String named = cluster.getId() + " (" + cluster.getName() + ")";
String named = named(cluster);
return switch (state) {
case "STARTING" -> "Amazon EMR cluster " + named + " was requested at " + time(at)
+ " and is being created.";
@@ -153,8 +166,8 @@ public class EmrEventPublisher {
}
private static String stepMessage(EmrCluster cluster, EmrStep step, String state) {
String stepNamed = step.getId() + " (" + step.getName() + ")";
String clusterNamed = cluster.getId() + " (" + cluster.getName() + ")";
String stepNamed = named(step);
String clusterNamed = named(cluster);
return switch (state) {
case "PENDING" -> "Step " + stepNamed + " was added to Amazon EMR cluster " + clusterNamed + " at "
+ time(step.getCreationDateTime()) + " and is pending execution.";
@@ -174,6 +187,16 @@ public class EmrEventPublisher {
};
}
// "StepID (StepName)", as the guide's tables write a step.
private static String named(EmrStep step) {
return step.getId() + " (" + step.getName() + ")";
}
// "ClusterId (ClusterName)", as the guide's tables write a cluster.
private static String named(EmrCluster cluster) {
return cluster.getId() + " (" + cluster.getName() + ")";
}
private static String time(Instant instant) {
return TIME.format(instant);
}
@@ -286,7 +286,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
for (AccountAwareStorageBackend.AccountEntry<EmrCluster> entry
: clusterStore.scanAllAccountEntries(k -> true)) {
EmrCluster cluster = entry.value();
boolean interrupted = sparkRunner != null && hasContainerStepRunning(cluster)
boolean interrupted = cluster.getSteps().stream().anyMatch(this::leftByARestart)
|| bootstrapRunner != null && bootstrapsInContainer(cluster);
Instant due = interrupted ? clock.instant() : lifecycle.nextChange(cluster);
if (due != null) {
@@ -528,11 +528,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
public EmrStep describeStep(String clusterId, String stepId) {
return call(() -> {
EmrCluster cluster = snapshotOf(requireCluster(clusterId));
return cluster.getSteps().stream()
.filter(s -> s.getId().equals(stepId))
.findFirst()
.orElseThrow(() -> new AwsException("InvalidRequestException",
"Step " + stepId + " does not exist.", 400));
return stepOf(cluster, stepId).orElseThrow(() -> new AwsException("InvalidRequestException",
"Step " + stepId + " does not exist.", 400));
});
}
@@ -563,8 +560,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
EmrCluster cluster = requireCluster(clusterId);
List<CancelStepInfo> result = new ArrayList<>();
for (String stepId : stepIds) {
EmrStep step = cluster.getSteps().stream()
.filter(s -> s.getId().equals(stepId)).findFirst().orElse(null);
EmrStep step = stepOf(cluster, stepId).orElse(null);
String refusal = step == null ? "Step does not exist."
: lifecycle.cancel(cluster, step, now(), regionOf(cluster));
result.add(refusal == null
@@ -1403,25 +1399,35 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
}
private boolean failInterruptedSteps(EmrCluster cluster) {
if (sparkRunner == null) {
return false;
}
boolean failed = false;
boolean ended = false;
for (EmrStep step : List.copyOf(cluster.getSteps())) {
if (runsInContainer(step) && !executing.contains(stepKey(regionResolver.getAccountId(), step.getId()))) {
if (leftByARestart(step)) {
lifecycle.stepEnded(cluster, step, EmrSparkSteps.INTERRUPTED, now(), regionOf(cluster));
failed = true;
ended = true;
}
}
return failed;
return ended;
}
private static boolean hasContainerStepRunning(EmrCluster cluster) {
return cluster.getSteps().stream().anyMatch(EmrService::runsInContainer);
/**
* Whether a step a container ran is one no thread runs any more, since Floci stopped while it ran: it ends,
* FAILED, or CANCELLED when its cancel was pending. Without the docker runner mode only one whose cancel was
* pending is, as nothing would end it; a RUNNING one completes by time there.
*/
private boolean leftByARestart(EmrStep step) {
if (sparkRunner == null) {
return EmrClusterLifecycle.CANCEL_PENDING.equals(step.getState());
}
return runsInContainer(step) && !executing.contains(stepKey(regionResolver.getAccountId(), step.getId()));
}
// A step a container runs: RUNNING, or CANCEL_PENDING until its driver is gone.
private static boolean runsInContainer(EmrStep step) {
return EmrClusterLifecycle.RUNNING.equals(step.getState()) && step.isRunInContainer();
return EmrClusterLifecycle.holdsAPlace(step) && step.isRunInContainer();
}
private static Optional<EmrStep> stepOf(EmrCluster cluster, String stepId) {
return cluster.getSteps().stream().filter(step -> step.getId().equals(stepId)).findFirst();
}
private static String stepKey(String accountId, String stepId) {
@@ -1458,8 +1464,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
}
/**
* Ends a step its thread ran, COMPLETED when {@code failure} is null and FAILED otherwise, unless a
* reset came since it started or the step is no longer RUNNING: cancelled, or on a cluster that ended.
* Ends a step its thread ran, COMPLETED when {@code failure} is null and FAILED otherwise, or CANCELLED when a
* cancel had made it CANCEL_PENDING, unless a reset came since it started or the step is past running:
* cancelled, or on a cluster that ended.
*/
private void stepEnded(StepLaunch launch, String failure) {
if (launch.launchedIn() != generation) {
@@ -1468,9 +1475,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
// Read while the step still counts as running, so it is not taken for one a restart left.
Optional<EmrCluster> found = findCluster(launch.clusterId());
executing.remove(stepKey(launch.accountId(), launch.stepId()));
EmrStep step = found.flatMap(cluster -> cluster.getSteps().stream()
.filter(candidate -> launch.stepId().equals(candidate.getId())).findFirst()).orElse(null);
if (step == null || !EmrClusterLifecycle.RUNNING.equals(step.getState())) {
EmrStep step = found.flatMap(cluster -> stepOf(cluster, launch.stepId())).orElse(null);
if (step == null || !EmrClusterLifecycle.holdsAPlace(step)) {
// A step of a cluster that has ended no longer runs: what the cluster kept may go with it, its last one.
found.ifPresent(this::releaseEnded);
return;
@@ -1482,16 +1488,30 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
}
/**
* A step's driver was stopped. A cancel, or its cluster's end, has ended the step already. One still
* RUNNING was stopped by Floci itself, by a reset's teardown or its shutdown, and is left as it is, still
* counted as running: the reset wipes it, a restart fails it, and its ActionOnFailure, which could start
* the next step after the teardown has passed, is not taken now.
* A step's driver was stopped. A cancel has made the step CANCEL_PENDING, which is CANCELLED now that its driver
* is gone, and makes room for the next; its cluster's end has ended it already. One still RUNNING, or
* CANCEL_PENDING, that Floci itself stopped, by a reset's teardown or its shutdown, is left as it is, still
* counted as running: the reset wipes it, a restart ends it, and what its end leads to, which could start the
* next step after the teardown has passed, does not happen now.
*/
private void driverStopped(StepLaunch launch) {
if (!stillRunning(launch)) {
executing.remove(stepKey(launch.accountId(), launch.stepId()));
clusterStore.get(launch.clusterId()).ifPresent(this::releaseEnded);
if (stillRunning(launch)) {
return;
}
Optional<EmrCluster> found = clusterStore.get(launch.clusterId());
Optional<EmrStep> cancelPending = found.flatMap(cluster -> stepOf(cluster, launch.stepId()))
.filter(step -> EmrClusterLifecycle.CANCEL_PENDING.equals(step.getState()));
if (cancelPending.isPresent() && teardowns.get() != launch.teardownsBefore()) {
return;
}
executing.remove(stepKey(launch.accountId(), launch.stepId()));
if (cancelPending.isPresent() && launch.launchedIn() == generation) {
EmrCluster cluster = found.get();
lifecycle.stepEnded(cluster, cancelPending.get(), null, now(), regionOf(cluster));
store(cluster);
return;
}
found.ifPresent(this::releaseEnded);
}
/**
@@ -1509,10 +1529,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
// Whether a step's driver may still start, or go on: one cancelled, on a cluster that ended, or a reset
// removed, is past it.
private synchronized boolean stillRunning(StepLaunch launch) {
return launch.launchedIn() == generation && clusterStore.get(launch.clusterId()).stream()
.flatMap(cluster -> cluster.getSteps().stream())
.anyMatch(step -> launch.stepId().equals(step.getId())
&& EmrClusterLifecycle.RUNNING.equals(step.getState()));
return launch.launchedIn() == generation && clusterStore.get(launch.clusterId())
.flatMap(cluster -> stepOf(cluster, launch.stepId()))
.filter(step -> EmrClusterLifecycle.RUNNING.equals(step.getState())).isPresent();
}
private synchronized boolean resetSince(StepLaunch launch) {