feat(sfn): publish history events for Parallel branches and Map iterations (#3167)

* feat(sfn): publish Parallel branch and Map iteration history events

The states inside a Parallel branch or an inline Map iteration now publish
their events into the execution history.

The cause of a failure the interpreter raises now carries the AWS prefix
"An error occurred while executing the state '<name>' (entered at the event
id #<n>). ". It is written once, at the innermost state.

Every shape was verified against real Step Functions in us-east-1.

* feat(sfn): record EvaluationFailed for JSONata failures

A JSONata expression that fails now leaves the EvaluationFailed event AWS
records, with error, the attributed cause, location and state. The location
names the field the way the cause does. The event is recorded once per
attempt when the state retries, and before the Failed event and the Catch.
A Catch clause whose own expression fails records it from where the state
stood before its first Failed event, then fails the state again.

Verified against real Step Functions in us-east-1

* fix(sfn): record every Distributed Map run so DescribeMapRun resolves its ARN

* fix(sfn): stop counting history events once the execution has ended
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-09-07 23:18:05 -04:00
1 parent 5eacd01636
commit fd21ac9a6d
19 files changed
+1726 -333

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -0,0 +1,169 @@
package io.github.hectorvent.floci.services.stepfunctions;
import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent;
import java.util.AbstractList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
/**
* One {@code previousEventId} chain of an execution's history: the top-level state loop, a Parallel
* branch, or a Map iteration. All chains share the execution's history and event limit.
*/
final class HistoryChain {
private final List<HistoryEvent> history;
private final AtomicLong producedEventCount;
private final AtomicBoolean ended;
private final HistoryChain parent;
private volatile boolean abandoned;
private long lastEventId;
private long tailEventId;
private HistoryChain(List<HistoryEvent> history, AtomicLong producedEventCount, AtomicBoolean ended,
HistoryChain parent, long lastEventId) {
this.history = history;
this.producedEventCount = producedEventCount;
this.ended = ended;
this.parent = parent;
this.lastEventId = lastEventId;
this.tailEventId = lastEventId;
}
/** Starts at 0, not at ExecutionStarted. AWS leaves the first state's Entered event unchained. */
static HistoryChain of(List<HistoryEvent> history) {
return new HistoryChain(history, new AtomicLong(history.size()), new AtomicBoolean(), null, 0L);
}
/** A Distributed Map item is a child execution. Its events are counted, not kept. */
static HistoryChain ofChildExecution() {
return new HistoryChain(new CountOnlyHistory(), new AtomicLong(), new AtomicBoolean(), null, 0L);
}
HistoryChain fork() {
return new HistoryChain(history, producedEventCount, ended, this, lastEventId);
}
boolean isBranch() {
return parent != null;
}
long lastEventId() {
return lastEventId;
}
void continueFrom(long eventId) {
lastEventId = eventId;
tailEventId = eventId;
}
void continueAfter(Collection<HistoryChain> chains) {
var last = lastEventId;
for (HistoryChain chain : chains) {
last = Math.max(last, chain.lastEventId);
}
continueFrom(last);
}
/** AWS records nothing of a branch it cut. */
void abandon() {
abandoned = true;
}
private boolean isAbandoned() {
for (var chain = this; chain != null; chain = chain.parent) {
if (chain.abandoned) {
return true;
}
}
return false;
}
/** Returns the event id, or 0 once the execution has ended. */
long publish(String type, Map<String, Object> details) {
if (isAbandoned()) {
return 0L;
}
long id = append(type, lastEventId, details, true);
if (id > 0) {
lastEventId = id;
tailEventId = id;
}
return id;
}
/**
* The event does not become the chain's tail. AWS records {@code *StateSucceeded},
* {@code MapRunSucceeded}, {@code MapIterationFailed} and {@code TaskStateAborted} this way.
*/
void publishAside(String type, Map<String, Object> details) {
if (isAbandoned()) {
return;
}
long id = append(type, tailEventId, 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);
}
/** ExecutionTimedOut points at 0. */
void end(String type, long previousEventId, Map<String, Object> details) {
synchronized (history) {
append(type, previousEventId, details, false);
ended.set(true);
}
}
/**
* Synchronized on the history because StopExecution appends the terminal event from another
* thread. An event counts towards the limit only once the history is known to take it.
*/
private long append(String type, long previousEventId, Map<String, Object> details, boolean counted) {
synchronized (history) {
if (ended.get()) {
return 0L;
}
if (counted) {
AslExecutor.countTowardsHistoryEventLimit(producedEventCount);
}
var event = new HistoryEvent();
event.setId(history.size() + 1L);
event.setPreviousEventId(previousEventId);
event.setType(type);
event.setDetails(details);
if (!history.add(event)) {
ended.set(true);
return 0L;
}
return event.getId();
}
}
private static final class CountOnlyHistory extends AbstractList<HistoryEvent> {
private int size;
@Override
public boolean add(HistoryEvent event) {
size++;
return true;
}
@Override
public HistoryEvent get(int index) {
throw new IndexOutOfBoundsException(index);
}
@Override
public int size() {
return size;
}
}
}
@@ -477,12 +477,13 @@ public class JsonataEvaluator {
} catch (QueryEvaluationFailure failure) {
throw new FailStateException(failure.error,
"The JSONata expression '" + expr + "' specified for the field '" + field
+ "' threw an error during evaluation" + failure.sentenceSeparator + failure.cause);
+ "' threw an error during evaluation" + failure.sentenceSeparator + failure.cause,
field);
}
if (value.isMissingNode()) {
throw new FailStateException("States.QueryEvaluationError",
"The JSONata expression '" + expr + "' specified for the field '" + field
+ "' returned nothing (undefined).");
+ "' returned nothing (undefined).", field);
}
return value;
}
@@ -16,6 +16,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
@@ -301,37 +302,38 @@ public class StepFunctionsJsonHandler {
* {@code arn:aws:states:::aws-sdk:sfn:describeMapRun} Task integration renders the same node in
* PascalCase, so this is the one place the response is described.
*
* <p>A retained run is one whose every item succeeded, because a Map fails on the first item
* that fails. That fixes {@code status}, both zero tolerances and {@code redriveCount}:
* {@code redriveDate} is absent until a run is redriven, and no run here ever is.
* <p>Both tolerances and {@code redriveCount} are zero because Floci implements neither, and
* {@code redriveDate} is absent until a run is redriven, which no run here ever is.
*/
static ObjectNode describeMapRunResponse(ObjectMapper objectMapper, MapRun mapRun) {
ObjectNode response = objectMapper.createObjectNode();
response.put("mapRunArn", mapRun.getMapRunArn());
response.put("executionArn", mapRun.getExecutionArn());
response.put("status", "SUCCEEDED");
response.put("status", mapRun.getStatus());
response.put("startDate", mapRun.getStartDate());
response.put("stopDate", mapRun.getStopDate());
response.put("maxConcurrency", mapRun.getMaxConcurrency());
response.put("toleratedFailurePercentage", 0.0);
response.put("toleratedFailureCount", 0);
putMapRunCounts(response.putObject("itemCounts"), mapRun.getItemCount());
putMapRunCounts(response.putObject("itemCounts"), mapRun);
// One child execution per item: ItemBatcher is not applied, so no execution covers a batch.
putMapRunCounts(response.putObject("executionCounts"), mapRun.getItemCount());
putMapRunCounts(response.putObject("executionCounts"), mapRun);
response.put("redriveCount", 0);
return response;
}
/** The ten counters of a run whose every item succeeded and was written to the result set. */
private static void putMapRunCounts(ObjectNode counts, int items) {
/** A failed item's result counts as written, as on AWS. */
private static void putMapRunCounts(ObjectNode counts, MapRun mapRun) {
var succeeded = mapRun.getSucceededCount();
var failed = mapRun.getFailedCount();
counts.put("pending", 0);
counts.put("running", 0);
counts.put("succeeded", items);
counts.put("failed", 0);
counts.put("succeeded", succeeded);
counts.put("failed", failed);
counts.put("timedOut", 0);
counts.put("aborted", 0);
counts.put("total", items);
counts.put("resultsWritten", items);
counts.put("aborted", mapRun.getItemCount() - succeeded - failed);
counts.put("total", mapRun.getItemCount());
counts.put("resultsWritten", succeeded + failed);
counts.put("failuresNotRedrivable", 0);
counts.put("pendingRedrive", 0);
}
@@ -367,7 +369,12 @@ public class StepFunctionsJsonHandler {
var arn = request.path("executionArn").asText();
var includeExecutionData = request.path("includeExecutionData").asBoolean(true);
List<HistoryEvent> events = service.getExecutionHistory(arn);
var live = service.getExecutionHistory(arn);
List<HistoryEvent> events;
// Branch and iteration threads append under the history's own monitor while a client reads.
synchronized (live) {
events = new ArrayList<>(live);
}
ObjectNode response = objectMapper.createObjectNode();
ArrayNode array = response.putArray("events");
for (HistoryEvent e : events) {
@@ -4,23 +4,24 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* A distributed Map run that has finished, keyed by its Map run ARN.
*
* <p>A Map fails on the first item that fails, so a run only reaches the {@code ResultWriter} that
* mints its ARN once every item has succeeded. That is why a run carries a single {@code itemCount}
* rather than the ten counters {@code DescribeMapRun} reports: the other nine are zero, and
* {@code succeeded}, {@code total} and {@code resultsWritten} are all this count.
* A distributed Map run that has finished, keyed by its Map run ARN. It is kept on success and on
* failure, so the {@code mapRunArn} of a {@code MapRunStarted} event resolves through
* {@code DescribeMapRun}. A Map cancels the remaining items on the first failure, so a failed run
* reports those as aborted.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class MapRun {
private String mapRunArn;
private String status;
/** The execution of the state machine whose Map state opened this run. */
private String executionArn;
private double startDate;
private double stopDate;
/** Items processed by the run, which is also the number of child executions it ran. */
/** Items of the run, which is also the number of child executions it ran. */
private int itemCount;
private int succeededCount;
private int failedCount;
/** The Map's declared MaxConcurrency, with an unbounded Map held as Integer.MAX_VALUE. */
private int maxConcurrency;
@@ -38,6 +39,13 @@ public class MapRun {
public int getItemCount() { return itemCount; }
public void setItemCount(int itemCount) { this.itemCount = itemCount; }
/** A run recorded before the status was kept is one whose every item succeeded. */
public String getStatus() { return status == null ? "SUCCEEDED" : status; }
public void setStatus(String status) { this.status = status; }
public int getSucceededCount() { return status == null ? itemCount : succeededCount; }
public void setSucceededCount(int succeededCount) { this.succeededCount = succeededCount; }
public int getFailedCount() { return failedCount; }
public void setFailedCount(int failedCount) { this.failedCount = failedCount; }
public int getMaxConcurrency() { return maxConcurrency; }
public void setMaxConcurrency(int maxConcurrency) { this.maxConcurrency = maxConcurrency; }