* fix(stepfunctions): enforce both TimeoutSeconds clocks The state machine's top-level TimeoutSeconds was read back by DescribeStateMachine and copied into activityScheduledEventDetails but never used as a deadline, so an execution ran to completion however long it took. Compute the budget once in doExecute, check it before every state and inside the Wait sleep, and end the execution TIMED_OUT with stopDate set, no error, no cause, and one ExecutionTimedOut event carrying States.Timeout and previousEventId 0. A Task's two bounds were swapped: HeartbeatSeconds acted as the total wait and TimeoutSeconds was decorative, so "TimeoutSeconds": 5, "HeartbeatSeconds": 60 failed at 60 seconds instead of 5. awaitToken now bounds the whole wait with TimeoutSeconds and the gap between heartbeats with HeartbeatSeconds. SendTaskHeartbeat only logged, so the gap bound needed a per-token timestamp: the service now records one when the token is registered and again on every heartbeat, and forgets it when the waiting task stops listening. Either clock ends the state as a TaskTimedOutException, which is what us-east-1 answers for a heartbeat expiry: an ActivityTimedOut event carrying error States.Timeout and no cause, then an execution reading FAILED with error States.Timeout and no cause key, over the six-event history ExecutionStarted, TaskStateEntered, ActivityScheduled, ActivityStarted, ActivityTimedOut, ExecutionFailed. A Catch still matches a heartbeat expiry under States.HeartbeatTimeout, so ErrorEquals matching now asks the failure which names it answers to rather than comparing one string. The Wait sleep stops at the execution deadline instead of sleeping its full duration first, which would have reported the timeout as many seconds late as the Wait outlasts the budget and left a WaitStateExited behind for a state AWS never finished. awaitToken discards its token on the way out; without that the token would stay pending for the life of the process and a later SendTaskSuccess would be answered as if someone were still waiting. Neither timeout carries a cause, so failExecution now reads a null cause as the failure having none and leaves the key out of both DescribeExecution and the ExecutionFailed event. The two other failures that reach it without a cause -- a Fail state with no Cause, and SendTaskFailure with no cause -- keep reporting an empty one, since AWS's shape for those is unmeasured. Refs #2733 * fix(stepfunctions): bound an execution's history and make StopExecution stop it AWS puts two bounds on a running execution that floci did not: it ends one that reaches 25,000 history events with States.Runtime, event 25,000 being the ExecutionFailed event itself, and StopExecution stops the worker rather than relabelling an execution that goes on to overwrite the status it wrote. Counting an event against that limit and numbering it in the published history are two meanings that one AtomicLong was carrying. They are separated here. producedEventCount counts every event the execution produces, the top-level flow's and those of its Parallel branches and inline Map iterations alike, and is what the limit judges. The published history numbers its own events: an event's id is its position in the list, which makes the list the only authority for the next id, where the counter and the seal in StepFunctionsService used to be a second one that agreed with it only at rest. A branch's events are counted and never built, so executeBranch no longer assembles HistoryEvent objects with full input and output JSON into a list it throws away. A Distributed Map runs each item as a child execution on AWS, and a child execution has a history of its own, so its items are counted against their own limit rather than the parent's: a Distributed Map over 13,000 items no longer fails the parent partway through with States.Runtime. The count is taken before it is judged. Reading it and then taking it let 40 concurrent inline Map iterations through the same check and spent more events than the execution had. StopExecution records its abort against a history that need not be in memory. Executions are stored and histories are not, so a restart in persistent mode brings a RUNNING execution back with nothing behind it, and the same window opens between a reset emptying the cache and emptying the store; the abort was written to the store and then thrown away as a 500. * fix(stepfunctions): end an execution that spends its budget waiting A state machine's TimeoutSeconds budget was read only between states and around the two pauses a definition asks for, a Wait and a Retry backoff. Every other way a state blocks outlasted it: a Task waiting for its token, a states:startExecution.sync or ecs:runTask.sync poll, and a Parallel or Map waiting for its branches. Those executions ended past their budget, and ended FAILED or SUCCEEDED rather than TIMED_OUT. Each of those waits now stops at the budget, and the Task path publishes no failure event for the state it cuts. Measured against us-east-1: a state machine with TimeoutSeconds 5 over an activity Task whose own TimeoutSeconds is 60 stops at exactly 5.000 s with status TIMED_OUT, and its history is ExecutionStarted, TaskStateEntered, ActivityScheduled, ExecutionTimedOut, with no ActivityTimedOut and no ExecutionFailed. --------- Co-authored-by: Facundo Paredes <naranjax@MAC-69786.local>
21 KiB
Step Functions
Protocol: AWS JSON 1.0 (X-Amz-Target: AWSStepFunctions.*)
Endpoint: POST http://localhost:4566/
Supported Actions
| Action | Description |
|---|---|
CreateStateMachine |
Create a state machine (Standard or Express) |
UpdateStateMachine |
Update definition, role, logging, tracing, or encryption settings and optionally publish a version |
DescribeStateMachine |
Get state machine definition and metadata |
ListStateMachines |
List all state machines |
DeleteStateMachine |
Delete a state machine |
PublishStateMachineVersion |
- |
ListStateMachineVersions |
- |
DeleteStateMachineVersion |
- |
ValidateStateMachineDefinition |
Validate an ASL definition without creating a state machine |
StartExecution |
Start a new execution |
StartSyncExecution |
- |
DescribeExecution |
Get execution status and output |
ListExecutions |
List executions for a state machine |
StopExecution |
Stop a running execution |
GetExecutionHistory |
Get the full event history of an execution |
DescribeMapRun |
Get the item and execution counters of a distributed Map run |
SendTaskSuccess |
Report task success (for .waitForTaskToken tasks) |
SendTaskFailure |
Report task failure |
SendTaskHeartbeat |
Send a heartbeat for long-running tasks |
CreateActivity |
- |
DeleteActivity |
- |
DescribeActivity |
- |
ListActivities |
- |
GetActivityTask |
- |
ListTagsForResource |
- |
TagResource |
- |
UntagResource |
- |
UpdateStateMachine returns the new revision ID and update timestamp. CloudFormation updates
definition, role, logging, tracing, encryption, and tags without replacing the state machine;
changes to StateMachineName or StateMachineType use replacement semantics.
Execution history events
GetExecutionHistory emits an event family around a Task state's TaskStateEntered and
TaskStateExited pair. Which family depends on the resource type.
- A service integration ARN (
arn:aws:states:::...) emitsTaskScheduled,TaskStarted, and thenTaskSucceededorTaskFailed.taskScheduledEventDetailscarriesresourceType,resource,region, andparameters.parametersis the resolvedParametersorArgumentspayload, serialized as a JSON string.timeoutInSecondsandheartbeatInSecondsappear only when the state setsTimeoutSecondsorHeartbeatSecondsas a literal number. - A direct Lambda function ARN emits
LambdaFunctionScheduled,LambdaFunctionStarted, and thenLambdaFunctionSucceededorLambdaFunctionFailed.LambdaFunctionScheduledcarriesresourceandinput.resourceholds the full function ARN.LambdaFunctionStartedcarries no details at all. This matches AWS. - An activity ARN emits the equivalent
Activity*family.
A Retry re-entry emits its own Scheduled, Started, and Failed triple for each attempt. A
mocked Task (SFN_MOCK_CONFIG) emits the same events as a real one, because Step Functions
Local does the same.
Every event's previousEventId points to the id of the event right before it. The one
exception is the first state's *StateEntered event. Its previousEventId is 0. That
matches ExecutionStarted, which is always id: 1, previousEventId: 0.
inputDetails appears on ExecutionStarted, on stateEnteredEventDetails, and on
LambdaFunctionScheduled/ActivityScheduled. outputDetails appears on
stateExitedEventDetails, on executionSucceededEventDetails, and on
taskSucceededEventDetails/lambdaFunctionSucceededEventDetails. Both are always
{"truncated": false}. Floci never truncates a payload, so the value never changes.
When the request sets includeExecutionData to false, the details objects stay but lose
input, inputDetails, output, and outputDetails. Every other field stays, including
taskScheduledEventDetails.parameters. This matches AWS.
A few gaps remain. TaskStarted, LambdaFunctionStarted, and ActivityStarted fire at
scheduling time, not when a worker actually picks up the task. Events inside a Parallel or
Map branch are not recorded in the parent execution's history. TaskSubmitted, which real
AWS emits for .sync and .waitForTaskToken integrations, is not emitted yet.
Map concurrency
Map states honor MaxConcurrency and, for JSONPath state machines, MaxConcurrencyPath.
JSONata state machines may supply MaxConcurrency as an expression. A value of 0, or an
omitted value, uses the AWS service ceiling: 40 concurrent iterations for Inline Map states and
10,000 for Distributed Map states. MaxConcurrency: 1 runs iterations sequentially.
Results remain in input order even when iterations finish out of order. If an iteration fails, the Map state fails promptly, cancels its active sibling iterations, and does not start queued iterations.
Retry policies
Task, Parallel, and Map states honor their Retry field. ErrorEquals matching
follows AWS semantics, including the States.ALL and States.TaskFailed wildcards.
States.Runtime is never retried. AWS defaults apply when fields are omitted
(MaxAttempts 3, IntervalSeconds 1, BackoffRate 2.0), MaxDelaySeconds is honored,
and each retrier keeps its own attempt counter. Retry is evaluated before Catch, and
$$.State.RetryCount increments per attempt. Attempt counts, defaults, and backoff
timing were verified against real AWS Step Functions.
A state with no Retry array runs exactly once. This is what makes CDK-generated provider-framework
workflows converge: the framework-isComplete-task throws on every not-yet-complete poll and relies on
Retry to poll again until the custom resource reports done — see
CloudFormation custom resources.
JitterStrategy supports NONE (the default) and FULL. FULL draws the delay
uniformly between zero and the computed delay, as on AWS. One deviation. The delay
between attempts is capped at 30 seconds, the same cap Floci applies to Wait states,
so emulated runs stay fast.
Timeouts
ASL carries two TimeoutSeconds fields and Floci enforces both, in the two terminal shapes
AWS uses. The state machine's own field bounds every state; a Task's own field only bounds
one that waits for a task token — an activity, or a .waitForTaskToken integration. A Lambda
or other SDK task that returns directly is not bound by it.
The state machine's own TimeoutSeconds is the whole execution's budget. It is checked before
every state and inside a Wait, so a Wait longer than what is left is cut rather than slept
out. The execution ends TIMED_OUT with stopDate set and no error and no cause at all;
States.Timeout is named only in the single ExecutionTimedOut event, whose previousEventId
is 0. The state that was cut gets no *StateExited event. A Parallel or Map branch runs
on its own thread and is not cut mid-state: the budget is enforced again as soon as the branch
returns.
A Task that waits for a task token — an activity, or a .waitForTaskToken integration — has
two independent bounds. TimeoutSeconds is the whole wait; HeartbeatSeconds is the longest gap
allowed between two SendTaskHeartbeat calls, and every heartbeat pushes that gap forward, so a
worker that reports as often as the definition asks runs until TimeoutSeconds runs out. Either
clock ends the state the same way: an ActivityTimedOut event — TaskTimedOut for a
.waitForTaskToken integration — carrying States.Timeout and no cause, then an execution that
reads FAILED with that same error. A Catch on a heartbeat expiry matches under
States.HeartbeatTimeout and under States.Timeout alike. Neither timeout carries a cause:
DescribeExecution and the ExecutionFailed event both leave the key out, where every other
failure reports one. A Task that declares no TimeoutSeconds waits 300 seconds, where AWS
waits a year.
One deviation. AWS starts the TimeoutSeconds clock when a worker picks the task up, the instant
it emits ActivityStarted. Floci emits ActivityStarted at schedule time, so both clocks start
when the task is scheduled.
JSONata nulls
An expression that evaluates to JSON null produces a value, not a missing one. It keeps its key
in Output, in Assign and in a Task's Arguments, at any nesting depth, and it stays in place as
an array element:
"Output": {"v": "{% $states.input.bar %}"} on input {"bar": null} -> {"v": null}
The same null is a value inside the expression too: $exists() on it is true and $type() on it
is "null".
One deviation. $count() on a JSON null answers 0; AWS answers 1.
An expression that returns nothing fails the state
An expression that returns nothing, which is what $states.input.absent and the functions listed
below that evaluate to undefined do, is not a missing value the state carries on without. It fails
the state with States.QueryEvaluationError, naming the field it was written in, and a Catch on
that error fires:
"Output": {"v": "{% $states.input.absent %}"}
-> States.QueryEvaluationError
The JSONata expression '$states.input.absent' specified for the field 'Output/v'
returned nothing (undefined).
The field is named relative to the state, with / before each object key and [i] for each array
index: Output, Output/a/b[0], Assign/x, Arguments/MessageGroupId, Choices[1]/Condition,
Seconds, Error, Cause, Items, MaxConcurrency. A matched Choice rule and a matching
Catch clause carry their own Assign and Output, which are named under the rule or clause:
Choices[1]/Output/v, Choices[0]/Assign/x, Catch[1]/Output/v. A Choice stops at the first rule
that matches, so an undefined condition in a later rule is never evaluated.
One deviation. AWS prefixes the cause of a real execution with
An error occurred while executing the state '<name>' (entered at the event id #<n>).; Floci
returns the cause without it, which is the form AWS's own TestState returns.
JSONata functions
State machines with "QueryLanguage": "JSONata" reach the six functions Step Functions adds on
top of the JSONata language, alongside every function JSONata itself provides.
| Function | Returns |
|---|---|
$parse(jsonString) |
the deserialized value; the replacement for $eval, which AWS disables |
$partition(array, chunkSize) |
array split into chunks of chunkSize, the last one holding the remainder |
$range(start, end, step) |
the values from start to end, inclusive when step lands on end |
$hash(str, algorithm) |
the hex digest of str; algorithm is MD5, SHA-1, SHA-256, SHA-384 or SHA-512, case-sensitive |
$random(seed) |
a number in [0, 1), reproducible under the optional integer seed |
$uuid() |
a v4 UUID |
Three behaviours are worth knowing before reading an unexpected result, and all three are AWS's:
- A non-integer argument is rounded towards zero, so
$range(-1.7, 2, 1)starts at-1and$partition(items, 2.9)chunks by 2. - Several arguments evaluate to undefined rather than failing: a chunk size of zero, an empty
array, a
$rangewith nostepor with a step whose sign disagrees with the direction, and a$hashwith no algorithm. The argument itself does not fail; the field the expression was written in does, underStates.QueryEvaluationError, as the section above records. $rangecollapses a single-element range to the bare number, not a one-element array.
JSONata's own $string follows AWS's number notation: a whole number is written out in full below
1e21 and in exponent notation from there, on both signs, so $string(1e20) is
100000000000000000000 and $string(1e21) is 1e+21.
Evaluation is bounded, as it is on AWS: one expression may run for five seconds and nest 500
levels deep, and past either the state fails with States.QueryEvaluationError. Both bounds sit
well above what AWS itself accepts, so an expression that evaluates there evaluates here. AWS
refuses a non-tail-recursive function past a nesting depth near 100, and the largest sequence it
accepts evaluates here in about a tenth of a second.
One deviation. AWS also bounds the memory an expression may use, refusing
[1..900000] ~> $count() with Expression evaluation memory limit exceeded while accepting the
same expression at 800,000 elements. Floci bounds time and depth but not memory, and its ranges
are lazy, so that expression answers immediately at any size.
Nested workflows
A parent workflow calls a child workflow through one of several integrations, and they differ in more than syntax:
| Resource | Child type | A child that fails | Result |
|---|---|---|---|
arn:aws:states:::states:startExecution |
Standard | not awaited | {executionArn, startDate} |
arn:aws:states:::states:startExecution.sync |
Standard | fails the calling task | execution envelope, output as a JSON string |
arn:aws:states:::states:startExecution.sync:2 |
Standard | fails the calling task | the child output, parsed |
arn:aws:states:::aws-sdk:sfn:startExecution |
Standard | not awaited | {ExecutionArn, StartDate} |
arn:aws:states:::aws-sdk:sfn:startSyncExecution |
Express | reported through Status |
PascalCase envelope, Output as a JSON string |
states:startExecution and aws-sdk:sfn:startExecution are the same API through two different
integrations, and only the casing of the result tells them apart.
startSyncExecution is the only one that does not fail the calling task when the child fails: the
SDK call itself succeeded, so the task result carries Status, Error and Cause and the parent
decides what to do next.
AWS SDK task integrations
A resource of the form arn:aws:states:::aws-sdk:<service>:<action> calls the service's API and
returns its response. Two conventions separate that result from the same API's wire response, and
both are AWS's:
- Field names are the SDK's, so a
startDateon the wire is aStartDatein the task result. - A timestamp is an ISO-8601 string such as
2026-08-28T20:34:59.712Z, where the wire response carries epoch seconds.
A failure names the SDK exception class, which always ends in Exception:
StartExecution answers a missing state machine with the error code StateMachineDoesNotExist on
the wire and the task fails with Sfn.StateMachineDoesNotExistException.
| Resource | Result | Notable failure |
|---|---|---|
arn:aws:states:::aws-sdk:sfn:startExecution |
{ExecutionArn, StartDate} |
Sfn.ExecutionAlreadyExistsException when Name is reused |
arn:aws:states:::aws-sdk:sfn:startSyncExecution |
execution envelope | Sfn.StateMachineTypeNotSupportedException for a Standard child |
arn:aws:states:::aws-sdk:sfn:sendTaskSuccess |
{} |
Sfn.InvalidTokenException when no task is waiting on the token |
arn:aws:states:::aws-sdk:sfn:sendTaskFailure |
{} |
Sfn.InvalidTokenException |
arn:aws:states:::aws-sdk:scheduler:createSchedule |
{ScheduleArn} |
Scheduler.ConflictException when the name is taken |
arn:aws:states:::aws-sdk:scheduler:updateSchedule |
{ScheduleArn} |
Scheduler.ResourceNotFoundException |
sendTaskSuccess and sendTaskFailure resolve a token a .waitForTaskToken task is parked on. A
token nobody is waiting for fails the calling task rather than reporting a delivery that never
happened.
Publishing events
arn:aws:states:::events:putEvents returns the PutEvents response itself, Entries and
FailedEntryCount, and one rejected entry fails the whole task with EventBridge.FailedEntry. The
cause is the response serialized as a string, so a Catch can read which entry was rejected:
{"FailedEntryCount":1,"Entries":[{"EventId":"08cbdc46-…"},{"ErrorCode":"InvalidArgument","ErrorMessage":"EventBus not found: no-such-bus"}]}
One deviation, and it belongs to EventBridge rather than to the integration: Floci rejects an entry
addressed to an event bus that does not exist, while AWS accepts it and returns an EventId.
JSONata expressions are validated when the state machine is created
A JSONata expression runs with no context item: the execution input arrives as $states.input
and a variable written by Assign as $name. A path that starts from neither reads a context
item that does not exist, and AWS refuses the whole definition:
An error occurred (InvalidDefinition) when calling the CreateStateMachine operation:
Invalid State Machine Definition: 'UNSUPPORTED_JSONATA_EXPRESSION: Reference to 'phone' at the
top level is not supported. at /States/E/Output/v'
Floci refuses it too, from CreateStateMachine, UpdateStateMachine and
ValidateStateMachineDefinition, with that message and that location. Write
$states.input.phone to read the input and $phone to read a variable: an earlier Assign of
phone does not put a bare phone in scope on AWS either.
Only the first step of a path is read against the top-level context, so a name in a later step,
in a predicate, in a sort term or in an object grouping stays legal and
$states.input.items[value > 3] is accepted. A lambda body keeps the context of the expression
that defines it, so $map($states.input.a, function($x){ b }) does name b at the top level.
Two neighbouring rules stay with the execution rather than the definition. A syntax error such as
{% a[1,2) %} is accepted here and fails the execution, where AWS reports
INVALID_JSONATA_EXPRESSION when the state machine is created; and $$, which AWS refuses under
its own message, is accepted here.
Mocked service integrations
Floci supports the Step Functions Local mock configuration format
(MockConfigFile.json). This lets a Task state return a predefined result or error
instead of calling the integrated service. It is the standard way to unit test Catch
and Retry branches, and it also lets you execute state machines whose integrations
Floci does not implement yet.
Point SFN_MOCK_CONFIG at the mock configuration file and start an execution against
<stateMachineArn>#<testCaseName>:
# docker run -e SFN_MOCK_CONFIG=/tmp/mock.json -v ./MockConfigFile.json:/tmp/mock.json ...
aws stepfunctions start-execution \
--state-machine-arn "$SM_ARN#Throw422" \
--input '{}' \
--endpoint-url $AWS_ENDPOINT_URL
{
"StateMachines": {
"Test": { "TestCases": { "Throw422": { "Call API": "ApiFailure" } } }
},
"MockedResponses": {
"ApiFailure": {
"0": { "Throw": { "Error": "ApiGateway.422", "Cause": "Unprocessable" } }
},
"ApiSuccess": {
"0-1": { "Return": { "StatusCode": 200, "ResponseBody": { "id": 1 } } }
}
}
}
Each test case maps a state name to a MockedResponses entry. Each mocked response is
keyed by retry attempt ("0", "1", or a range like "1-2"), so a state can fail on
the first attempt and succeed on a retry. Return supplies the task result. Throw
fails the task with the given Error and Cause, which flow through Retry and
Catch unchanged. States not named in the test case run their real integration, so
mocked and real service calls can be combined in one execution. The file is re-read
when it changes, so it can be edited without restarting Floci.
Behavior was verified against Step Functions Local 2.0.0. As there, StartSyncExecution
rejects a test case suffix with UnsupportedOperation and does not strip a bare trailing
#, a bare trailing # on StartExecution runs the execution unmocked, and a retry
attempt with no mocked entry fails the execution with States.Runtime. One intentional deviation: Floci reports an unknown test case and any
invalid mock configuration (unparseable file, bad attempt key, missing MockedResponses
entry, Return and Throw together, Throw without Error) as a structured 400 error
at StartExecution. Step Functions Local instead returns a plain HTTP 500 for most of
these and starts the execution only to fail it with States.Runtime for the last two.
Configuration
| Variable | Default | Description |
|---|---|---|
FLOCI_SERVICES_STEPFUNCTIONS_ENABLED |
true |
Enable or disable the service |
SFN_MOCK_CONFIG |
unset | Path to a Step Functions Local compatible mock configuration file (alias: FLOCI_SERVICES_STEPFUNCTIONS_MOCK_CONFIG_FILE) |
Examples
export AWS_ENDPOINT_URL=http://localhost:4566
# Create a state machine
SM_ARN=$(aws stepfunctions create-state-machine \
--name my-workflow \
--definition '{
"Comment": "Simple workflow",
"StartAt": "HelloWorld",
"States": {
"HelloWorld": {
"Type": "Pass",
"Result": {"message": "Hello, World!"},
"End": true
}
}
}' \
--role-arn arn:aws:iam::000000000000:role/step-functions-role \
--query stateMachineArn --output text \
--endpoint-url $AWS_ENDPOINT_URL)
# Start an execution
EXEC_ARN=$(aws stepfunctions start-execution \
--state-machine-arn $SM_ARN \
--input '{"key":"value"}' \
--query executionArn --output text \
--endpoint-url $AWS_ENDPOINT_URL)
# Check status
aws stepfunctions describe-execution \
--execution-arn $EXEC_ARN \
--endpoint-url $AWS_ENDPOINT_URL
# Get event history
aws stepfunctions get-execution-history \
--execution-arn $EXEC_ARN \
--endpoint-url $AWS_ENDPOINT_URL