fix(stepfunctions): stop a .sync job whenever its Task is cut, and record the cut state (#4660)

* fix(stepfunctions): stop a .sync job whenever its Task is cut, and record the cut state

Measured on AWS (ap-northeast-1, 2026-09-29): Step Functions stops the
job a .sync Task waits on however the Task ends before the job does.
Besides the Task's own TimeoutSeconds and StopExecution, which #4519
covered, that is the execution's budget (child ABORTED, ECS task
UserInitiated, both at the budget) and a failure in a sibling Parallel
branch (both within about 0.1 s of the failure), always with the cause
"The Task state in AWS Step Functions execution [<arn>] which was
managing this resource was aborted". Floci left the job running in both
cases: the poll loops only stopped it on the Task's own timeout, and an
interrupt from a cut Parallel unwound through them untouched.

AWS also records the state each cut branch was in: one TaskStateAborted
per cut Task, or WaitStateAborted for a cut Wait, each chained to the
failing branch's last event and recorded before ParallelStateFailed,
which points at that same event. The Parallel now reads each branch's
current state before it cuts them and records those events with
HistoryChain.publishBeside. The execution's budget records none, as on
AWS.

Part of #4646

* fix(stepfunctions): read and cut a Parallel branch in one step

Review of #4660: the state a branch is in was published apart from the
event that enters or exits it, and read apart from the cut. A sibling
failure could therefore see a TaskStateEntered with no state marked and
record no TaskStateAborted, or mark a state that then exited before the
cut and record TaskStateAborted after its TaskStateExited.

HistoryChain now publishes the Entered and Exited events together with
the marker (publishStateEntered, publishStateExited), and the Parallel
reads and cuts each branch with abandonInState, all under the chain's
lock. A Task whose own failure ends its branch leaves the state and
records its TaskStateAborted in one step too (leaveStateAside), so a
concurrent cut reports it at most once. runState leaves the state in a
finally for the paths that end by throwing.

* fix(stepfunctions): let the cut branch's state alone decide its aborted event

Review of #4660: the cut read each branch's future after cutting it, so
a branch that finished in between had its Exited event suppressed by
the cut and its *StateAborted skipped by the isDone check, leaving a
state with neither. The future read is not needed: runState leaves
every state it entered before the branch returns, so a finished branch,
the failed one included, is always read as between states. The cut now
decides on the state it reads under the chain's lock and nothing else.

* test(stepfunctions): assert the parent's budget aborts a nested child over HTTP

StepFunctionsTimeoutSecondsIntegrationTest still said the child keeps
running when the parent's TimeoutSeconds fires, which this PR changes
to match AWS. The comment now says the child is aborted, and the test
asserts it through ListExecutions, so the change is covered end to end
and not only by the executor's unit tests.

---------

Co-authored-by: mitsukado-shinagawa <mitsukado-shinagawa@users.noreply.github.com>
This commit is contained in:
mitsukado-shinagawaandmitsukado-shinagawa authored and GitHub committed 2026-09-29 18:54:05 -05:00
1 parent b8aec4c50f
commit dc3beadf6a
8 files changed
+562 -32

No files matched your search

@@ -561,8 +561,21 @@ public class AslExecutor {
StateMachine sm, String topLevelQueryLanguage, JsonNode context,
ObjectNode variables, long executionDeadlineNanos) throws Exception {
var type = stateDef.path("Type").asText();
var enteredEventId = chain.publish(stateEnteredEventType(type),
long enteredEventId = chain.publishStateEntered(type, stateEnteredEventType(type),
Map.of("name", name, "input", input.toString(), "inputDetails", Map.of("truncated", false)));
try {
return runEnteredState(chain, name, enteredEventId, type, stateDef, input, sm, topLevelQueryLanguage,
context, variables, executionDeadlineNanos);
} finally {
// A state that ends by throwing publishes no Exited event, so the chain leaves it here.
chain.leaveState();
}
}
private StateResult runEnteredState(HistoryChain chain, String name, long enteredEventId, String type,
JsonNode stateDef, JsonNode input, StateMachine sm,
String topLevelQueryLanguage, JsonNode context, ObjectNode variables,
long executionDeadlineNanos) throws Exception {
updateStateContext(context, name);
var jsonata = isJsonata(stateDef, topLevelQueryLanguage);
StateResult result;
@@ -589,12 +602,12 @@ public class AslExecutor {
if (result == null) {
if (chain.isBranch() && "Task".equals(type) && !failure.isRuntimeError()) {
// AWS records this after TaskFailed when the failure ends the branch.
chain.publishAside("TaskStateAborted", null);
chain.leaveStateAside("TaskStateAborted", null);
}
throw failure;
}
}
chain.publish(stateExitedEventType(type),
chain.publishStateExited(stateExitedEventType(type),
Map.of("name", name, "output", result.output().toString(),
"outputDetails", Map.of("truncated", false)));
return result;
@@ -831,7 +844,8 @@ public class AslExecutor {
// was sealed by the abort; nothing more is written about the state.
throw e;
} catch (InterruptedException e) {
// The task of a branch that was cut. AWS records nothing for it.
// The task of a branch that was cut. The branch records nothing more; the Parallel
// that cut it records its TaskStateAborted.
throw e;
} catch (Exception e) {
var failure = e instanceof FailStateException f ? f : null;
@@ -1703,16 +1717,16 @@ public class AslExecutor {
return result;
}
// .sync or .sync:2 polls until terminal, or until one of the two clocks runs out: the parent
// execution's TimeoutSeconds budget ends the parent as TIMED_OUT and leaves the child running;
// the Task's own TimeoutSeconds fails the state with States.Timeout and aborts the child, the
// way AWS does (measured: child ABORTED, no error, the cause below). A StopExecution on the
// parent ends the wait the same way, so a stopped execution does not keep a polling worker.
// .sync or .sync:2 polls until terminal. Whatever else ends the wait aborts the child, the way
// AWS does (measured: child ABORTED, no error, the cause below): the Task's own TimeoutSeconds,
// which fails the state with States.Timeout; the parent execution's budget, which ends it
// TIMED_OUT; a failure in a sibling Parallel branch, which interrupts this one; and a
// StopExecution on the parent, so a stopped execution does not keep a polling worker.
while (true) {
try {
sleepOrTimeOutTask(TimeUnit.MILLISECONDS.toNanos(SYNC_POLL_INTERVAL_MS),
executionDeadlineNanos, taskDeadlineNanos);
} catch (TaskTimedOutException e) {
} catch (TaskTimedOutException | ExecutionTimedOutException | InterruptedException e) {
abortChildExecution(execArn, executionArn);
throw e;
}
@@ -1839,15 +1853,16 @@ public class AslExecutor {
// All tasks must be polled (not just the first): with Count > 1, a failure in any task must
// fail the state, otherwise tasks beyond the first would run unmonitored. The wait is bounded
// by the Task's TimeoutSeconds and by the execution's budget, never by a poll count of its own.
// The Task's clock also stops the tasks it launched, the way AWS does (measured: the ECS task
// reads stopCode UserInitiated with the cause below), and so does a StopExecution on the
// execution, which otherwise would leave this worker polling until a clock ran out.
// Whatever ends the wait before the tasks stop also stops the tasks it launched, the way AWS
// does (measured: the ECS task reads stopCode UserInitiated with the cause below): either
// clock, a failure in a sibling Parallel branch, which interrupts this one, and a
// StopExecution on the execution, which otherwise would leave this worker polling.
List<String> taskArns = launched.stream().map(EcsTask::getTaskArn).toList();
while (true) {
try {
sleepOrTimeOutTask(TimeUnit.MILLISECONDS.toNanos(SYNC_POLL_INTERVAL_MS),
executionDeadlineNanos, taskDeadlineNanos);
} catch (TaskTimedOutException e) {
} catch (TaskTimedOutException | ExecutionTimedOutException | InterruptedException e) {
stopEcsTasks(cluster, taskArns, executionArn, region);
throw e;
}
@@ -1882,8 +1897,8 @@ public class AslExecutor {
}
/**
* The reason AWS writes on a job it stops because the {@code .sync} Task waiting on it ran out
* of its {@code TimeoutSeconds}: verbatim, as the ECS task's {@code stoppedReason} and the child
* The reason AWS writes on a job it stops because the {@code .sync} Task waiting on it ended
* first, whichever way it ended: verbatim, as the ECS task's {@code stoppedReason} and the child
* execution's {@code cause}.
*/
private static String syncAbortCause(String executionArn) {
@@ -1891,24 +1906,24 @@ public class AslExecutor {
+ "] which was managing this resource was aborted";
}
/** Best effort, like AWS: a task that is already gone does not change the timeout being reported. */
/** Best effort, like AWS: a task that is already gone does not change how the state ends. */
private void stopEcsTasks(String cluster, List<String> taskArns, String executionArn, String region) {
for (String taskArn : taskArns) {
try {
ecsService.stopTask(cluster, taskArn, syncAbortCause(executionArn), region);
} catch (RuntimeException e) {
LOG.warnv("ecs:runTask.sync timed out but the task {0} could not be stopped: {1}",
LOG.warnv("ecs:runTask.sync ended before its task {0} did, and the task could not be stopped: {1}",
taskArn, e.getMessage());
}
}
}
/** Best effort, like AWS: a child that already ended does not change the timeout being reported. */
/** Best effort, like AWS: a child that already ended does not change how the state ends. */
private void abortChildExecution(String childExecutionArn, String executionArn) {
try {
sfnService.get().stopExecution(childExecutionArn, syncAbortCause(executionArn), null);
} catch (RuntimeException e) {
LOG.warnv("states:startExecution.sync timed out but the child {0} could not be stopped: {1}",
LOG.warnv("states:startExecution.sync ended before its child {0} did, and the child could not be stopped: {1}",
childExecutionArn, e.getMessage());
}
}
@@ -2580,8 +2595,13 @@ public class AslExecutor {
Thread.currentThread().interrupt();
throw e;
} catch (ExecutionException e) {
abandon(branchChains, futures);
List<String> abortedEventTypes = cutAfterFailure(branchChains, futures);
chain.continueFrom(branchChains.get(joined).lastEventId());
if (e.getCause() instanceof FailStateException failure && !failure.isRuntimeError()) {
for (String abortedEventType : abortedEventTypes) {
chain.publishBeside(abortedEventType, null);
}
}
// Unwrap so a branch's FailStateException reaches the Parallel state's own Retry and
// Catch handling instead of surfacing as States.Runtime, and so an Error reaches the
// execution-level handler as itself rather than as an ExecutionException wrapper. The
@@ -2617,6 +2637,28 @@ public class AslExecutor {
return new StateResult(output, stateDef.path("Next").asText(null));
}
/**
* Cuts every branch after one of them failed, like {@link #abandon}, and returns one
* {@code *StateAborted} event type per branch it cut inside a Task or a Wait: the two state
* types AWS was measured recording it for (a {@code .sync} Task waiting on its job, and a Wait).
* A branch between states, or inside any other state, gets no event. Each branch is read and cut
* in one step, so a state that exits before its cut is not reported, and one that is reported
* records no Exited event afterwards. The state alone decides: a branch that has finished, the
* failed one included, has left every state it entered, and reading its future as well would
* reopen the gap between the cut and that read.
*/
private static List<String> cutAfterFailure(List<HistoryChain> chains, List<? extends Future<?>> futures) {
List<String> abortedEventTypes = new ArrayList<>();
for (HistoryChain branch : chains) {
String stateType = branch.abandonInState();
if ("Task".equals(stateType) || "Wait".equals(stateType)) {
abortedEventTypes.add(stateType + "StateAborted");
}
}
futures.forEach(future -> future.cancel(true));
return abortedEventTypes;
}
private static void abandon(List<HistoryChain> chains, List<? extends Future<?>> futures) {
chains.forEach(HistoryChain::abandon);
futures.forEach(future -> future.cancel(true));
@@ -20,6 +20,7 @@ final class HistoryChain {
private final AtomicBoolean ended;
private final HistoryChain parent;
private volatile boolean abandoned;
private String activeStateType;
private long lastEventId;
private long tailEventId;
@@ -68,11 +69,57 @@ final class HistoryChain {
continueFrom(last);
}
/** AWS records nothing of a branch it cut. */
/**
* Nothing more is recorded on a branch once it is cut. The state it was cut in is recorded by
* the Parallel that cut it, through {@link #publishBeside}.
*/
void abandon() {
abandoned = true;
}
/*
* The state this chain is in is published together with the event that enters or exits it,
* and read together with the cut, all under this chain's lock. A cut therefore reports a state
* only when its Entered event is recorded and its Exited event never will be.
*/
/** Publishes a state's Entered event and marks the chain as inside that state. */
synchronized long publishStateEntered(String stateType, String eventType, Map<String, Object> details) {
long id = publish(eventType, details);
activeStateType = stateType;
return id;
}
/** Marks the chain as between states and publishes the state's Exited event. */
synchronized void publishStateExited(String eventType, Map<String, Object> details) {
activeStateType = null;
publish(eventType, details);
}
/** Marks the chain as between states when a state ends without an Exited event. */
synchronized void leaveState() {
activeStateType = null;
}
/**
* Marks the chain as between states and publishes an aside event, as a Task whose own failure
* ends its branch records {@code TaskStateAborted}. A cut that lands first reports the state
* instead, and this event is then not recorded, so the state is reported aborted exactly once.
*/
synchronized void leaveStateAside(String eventType, Map<String, Object> details) {
activeStateType = null;
publishAside(eventType, details);
}
/**
* Cuts the chain like {@link #abandon} and returns the type of the state it was in, or null
* when it was between states.
*/
synchronized String abandonInState() {
abandoned = true;
return activeStateType;
}
private boolean isAbandoned() {
for (var chain = this; chain != null; chain = chain.parent) {
if (chain.abandoned) {
@@ -109,6 +156,22 @@ final class HistoryChain {
}
}
/**
* Chained to the last event rather than to the tail, and the last event stays where it is, so
* several events published this way all point at the same one. AWS records the
* {@code *StateAborted} event of each branch a failure cuts this way, before the Parallel's
* {@code ParallelStateFailed}, which points at that same event.
*/
void publishBeside(String type, Map<String, Object> details) {
if (isAbandoned()) {
return;
}
long id = append(type, lastEventId, details, true);
if (id > 0) {
tailEventId = id;
}
}
/** The terminal event does not count towards the limit, and nothing is recorded after it. */
void end(String type, Map<String, Object> details) {
end(type, tailEventId, details);