Files
floci/docs/services/step-functions.md
T
Sam Fakhreddine 08e532ab1a feat(cloudformation): CDK Provider-framework custom resources and changeset/SSM param fidelity (#2688)
* feat(cloudformation): changeset diffs, stack params, SSM attributes

CDK's deploy loop reads all three: DescribeChangeSet now returns
computed Add/Modify/Remove resource changes instead of an empty list
(an empty list makes CDK skip ExecuteChangeSet on updates),
DescribeStacks echoes the stack's merged parameters, and
AWS::SSM::Parameter resources expose Value/Type/Name attributes so
Fn::GetAtt resolves the bootstrap version

(cherry picked from commit 80ac80063e84ef1be977fe625334e722cc1ed8bb)

* feat(cloudformation): resolve SSM-typed stack parameters

AWS::SSM::Parameter::Value<String> template parameters resolve through
SSM for the stack's account and region; missing parameters fail with the
real ValidationError message. Landing Zone Accelerator's security and
logging stacks depend on this typed-parameter resolution.

The IAM password-policy and S3 replication-config changes from the same
source commit ship separately in the iam and s3 branches.

(cherry picked from commit 10dbabbf5e31d763a398fc1fff16ab0484958af0)

* feat(cloudformation): drive CDK Provider framework custom resources

The CDK Provider framework defers its ResponseURL callback to a Step
Functions waiter that polls framework.isComplete on a Retry cadence until
the resource is ready. The custom-resource provisioner only waited the
synchronous single-lambda budget for a ResponseURL PUT, so the
waiter-driven PUT never landed. A framework.onEvent ServiceToken is now
awaited on a bounded async budget so that PUT is captured; onEvent-only
and single-lambda resources are unchanged.

The engine-side half of the original commit -- a Task-only Retry
implementation for the ASL executor (ErrorEquals/IntervalSeconds/
MaxAttempts/BackoffRate/MaxDelaySeconds) -- is dropped here: upstream
#2455 ("feat(sfn): support Retry policies in Task, Parallel, and Map
states") landed a broader Retry implementation independently (Task,
Parallel, and Map states; JitterStrategy; $$.State.RetryCount;
Retry-before-Catch ordering), a strict superset of what this commit
needed. The full stepfunctions suite (411 tests) is green against it
on this branch, and CustomResourceProviderFrameworkTest (a hermetic
test of the provisioner's own detect-and-wait logic, no Step Functions
involved) is unaffected by the drop.

(cherry picked from commit 5b3502d8c9dddf3766ca3f94fe7f146042dc00fd)

* docs(cloudformation): document CDK provisioning

Documents the CDK Provider-framework custom-resource support and folds
its cross-reference into upstream's existing "Retry policies" section
in step-functions.md rather than duplicating it with a separate
"State Retry" section (upstream #2455 already documents the Retry
engine itself).

* feat(cloudformation): budget custom-resource waits by idleness, not total time

The async custom-resource wait was a fixed 3-minute total budget. That is a
property of the emulator, but the time a CDK provider-framework resource needs
is a property of the work: Custom::CreateOrganizationAccounts creates exactly
one account per 15s waiter poll, so a 3-account org finishes in ~45s while a
15-account org needs ~195s. Past the budget the Lambda is guillotined mid-
success -- the accounts all exist, but the resource reports CREATE_FAILED, the
stack rolls back, and CDK's readback then surfaces the misleading "NoStack:
CloudFormationStack object does not hold a stack".

Measure idleness instead. The provisioner already embeds its callback token in
the ResponseURL it puts on every event, and the framework echoes that event into
each framework.isComplete poll, so a poll arriving at LambdaService is proof of
progress for a specific pending resource. Each poll resets the budget, which
makes the wait proportional to the work without CloudFormation needing to know
what the work is -- and a genuinely hung resource still fails after 3 idle
minutes exactly as before.

CustomResourceLiveness lives in core.common so the Lambda service can report
progress without depending on CloudFormation; the dependency already runs the
other way.

(cherry picked from commit 14087c992ebb75d109999153a9e8af7e3c2d79f4)
(cherry picked from commit 51349e4e017ed08d90e6e71212414e2f306c826b)

* fix(cloudformation): call the caller-scoped getStackOrThrow overload that exists

The changeset-diff commit re-derived onto main carried a call to a
three-arg getStackOrThrow(name, region, accountId) overload that only
existed on the account-scoping commit deliberately skipped as superseded
by upstream. Upstream's resolveStack already scopes to the caller's
account, so the two-arg form is equivalent and compiles.

* fix(cloudformation): honour an arrived custom-resource response past its budget

A synchronous custom-resource handler PUTs to the ResponseURL from inside the
invoke the provisioner is blocked on, so its response can already be delivered
by the time await() is entered. Two independent flaws then threw it away.

The idle clock started at register(), before the invoke. A provider-framework
onEvent-only handler that took 75s to return -- two nested cold container
starts -- had spent its 10s CR_RESPONSE_TIMEOUT six times over before await
was reached, so the very first deadline check was already negative. Idleness
of the wait cannot include time the handler spent working; the clock now
starts when the caller starts waiting.

The deadline guard also threw without ever consulting the future, so a
response that had completed it was discarded as a timeout. Observed on
AccessAnalyzerServiceLinkedRoleCreateServiceLinkedRoleResource: the handler
logged its response at 15:52:11.768 and the resource was failed 24ms later.
An arrived response outranks the clock.

Both are pinned by red-first tests. The existing idle-timeout guarantees are
unchanged: nothing arriving still times out, and a resource that stops
reporting liveness still dies on schedule from its last touch.

(cherry picked from commit 7dc8bbca7d47b2a029b5656a89421a556b8296be)
(cherry picked from commit 77b71b31a634ae27d7460a078b52dac250d67dc7)

* refactor(cloudformation): extract Provider-framework detection from the provisioner

The CDK Provider-framework `framework.onEvent` detection and the longer idle
budget it earns lived in CloudFormationResourceProvisioner, adding ~55 lines to a
class that is being dismantled rather than grown.

Move the concern to ProviderFrameworkDetector: it owns the two waiter marker env
vars, the best-effort environment probe, the 3-minute async budget and the test
seam that shortens it. CustomResourceResponseStore — which already owns the
idle-timeout concept via touch/await — gains an await overload that resolves the
budget for a ServiceToken and delegates to the existing one, so the provisioner
only passes the token through and appends the store's timeout detail to its
error. Behaviour is unchanged.

(cherry picked from commit 5f93439f409a32012a01b996c5edd0c29d23b260)

* fix(stepfunctions): report custom-resource liveness on waiter polls

A CDK provider-framework waiter's framework.isComplete poll is itself a
Lambda Task the state machine invokes, so it goes through
AslExecutor.invokeResource -> LambdaExecutorService directly, bypassing
LambdaService.invoke() and the liveness hook it carries. A long-but-
progressing custom resource's idle budget in CustomResourceResponseStore
ticked down as if no polls were arriving, even while they kept landing.

AslExecutor now reports liveness the same way LambdaService does: extract
the callback token from the invoke payload and touch() it before invoking.

* perf(core): avoid materializing the full payload string in tokenIn

CustomResourceLiveness.tokenIn() ran on every Lambda invoke once liveness
reporting is wired in, decoding the whole invoke payload as a UTF-8 String
even though the overwhelming majority of invokes carry no callback URL at
all. Scan the raw bytes for the ASCII "/cfn-response/" marker instead, and
only allocate a String for the small token substring when one is found.

* fix(cloudformation): compute accurate changeset resource diffs

computeChangeSetChanges never read cs.getParameters(), so an update that
only changed parameter values reported an empty diff and CDK skipped
execution, leaving the old parameter-derived config deployed. It also
diffed a SAM change set's raw template against the stack's expanded
deployed template, reporting spurious Modify/Remove on every SAM-generated
resource for a no-op update, and hardcoded Replacement=False even when a
resource's Type changed.

Now the diff expands a SAM change set's template before comparing, marks a
resource Modify when it references a changed parameter, and reports
Replacement=True when a resource's Type changes.

* fix(cloudformation): restore last-successful parameters on update rollback

executeTemplate overwrote the stack's live parameter map with an update's
attempted values before resolving SSM-typed parameters, which can fail. A
failed resolution rolled the stack back, but the update snapshot never
captured parameters, so DescribeStacks reported the failed update's
attempted values instead of the last successfully deployed ones.

StackUpdateSnapshot now captures the stack's parameters alongside its
template body, and rollbackFailedUpdate restores them together.

* fix(cloudformation): log tolerated wait-slice timeouts in custom-resource poll loop

Each slice of the custom-resource poll loop below the outer idle budget
hit an intentionally-tolerated TimeoutException that was swallowed with
only a comment, against the repo's convention of logging deliberately
caught exceptions.

* fix(cloudformation): honor Parameters.member.N.UsePreviousValue

extractParameters never read UsePreviousValue, so submitting it without a
ParameterValue stored an empty string for that key. The new parameter-diff
logic in computeChangeSetChanges (9fb02c6a9) then treated that empty
string as different from the deployed value, reporting a spurious Modify
for every resource referencing an otherwise-unchanged parameter.

extractParameters now takes the stack's current parameters and resolves
UsePreviousValue against them; CloudFormationService.currentParameters
looks those up (empty map if the stack doesn't exist yet, e.g. a CREATE
change set).

* fix(cloudformation): resolve UsePreviousValue against deployed StackSet parameters

UpdateStackSet extracted parameters with the previous-value-unaware
extractParameters() overload, so a member with UsePreviousValue=true and no
ParameterValue stored an empty string and clobbered the StackSet's deployed
value instead of preserving it.

* fix(cloudformation): resolve template defaults for omitted parameters in changeset diff

computeChangeSetChanges compared only explicitly submitted parameters against
the deployed stack, so an update that omits a parameter (falling back to its
template Default) was never flagged as a change even when that default
differs from the deployed value. ExecuteChangeSet applies the default when it
actually runs, so the preview under-reported what would change. Resolve
defaults for the change set's parameters the same way execution does before
diffing.

* fix(cloudformation): resolve SSM parameter drift and no-default omissions in changeset diff

computeChangeSetChanges compared raw submitted parameter values against the
deployed stack, so it missed two cases ExecuteChangeSet actually handles
differently: an omitted parameter with no template Default disappears
entirely from the resolved map (previously undetected since the diff only
walked the new parameter set), and AWS::SSM::Parameter::Value<String>
parameters are resolved against the live SSM store at execution time but
compared as raw parameter names in the preview, masking a changed SSM value
behind an unchanged parameter name.

Stack now tracks resolvedParameters (the SSM-resolved map executeTemplate
last applied, restored on rollback like parameters already was) so the diff
can compare resolved values on both sides. The diff falls back to unresolved
values if SSM resolution fails, since a preview must not fail harder than
the operation it previews - ExecuteChangeSet still raises the real
ValidationError when it resolves for real.

* fix(stepfunctions): pass CustomResourceLiveness to AslExecutor in error-termination test

Upstream's issue #2666 regression test predates this branch's addition
of CustomResourceLiveness to AslExecutor's constructor. The merge from
upstream/main brought the file in as new content with no line overlap,
so it auto-merged cleanly but left the constructor call one argument
short.

* fix(cloudformation): evaluate Conditions in changeset diff, always restore params on rollback

computeChangeSetChanges never evaluated template Conditions, so a resource
whose Condition depends on a changed parameter but whose own definition text
is unchanged was invisible to the diff even though ExecuteChangeSet would
Add or Remove it once the condition flips (see
deleteRemovedOrConditionFalseResources). The diff now resolves Conditions
against the new resolved parameters and compares against whether the
resource is actually present in stack.getResources() - the same ground
truth execution already uses to decide whether a resource was created -
falling back to the existing text-based Modify detection when the condition
doesn't change.

rollbackFailedUpdate only restored the last-successful parameter maps when
resource rollback itself also succeeded, so a stack that lands in
UPDATE_ROLLBACK_FAILED (resource rollback failed too) kept serving the
failed update's attempted parameter values via DescribeStacks and later
change-set previews. Parameters are independent of resource-rollback
outcome and are now restored unconditionally; templateBody restoration
stays gated on rollback success since a partially-rolled-back resource set
doesn't correspond to either template.

* fix(stepfunctions): pass EventBridgeHandler/SchedulerService/SchedulerController mocks in AslExecutor test

Merging upstream/main (55acdec6e) added these three constructor
parameters to AslExecutor without updating this test's call site,
breaking test-compile.
2026-08-29 15:01:00 -04:00

19 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:::...) emits TaskScheduled, TaskStarted, and then TaskSucceeded or TaskFailed. taskScheduledEventDetails carries resourceType, resource, region, and parameters. parameters is the resolved Parameters or Arguments payload, serialized as a JSON string. timeoutInSeconds and heartbeatInSeconds appear only when the state sets TimeoutSeconds or HeartbeatSeconds as a literal number.
  • A direct Lambda function ARN emits LambdaFunctionScheduled, LambdaFunctionStarted, and then LambdaFunctionSucceeded or LambdaFunctionFailed. LambdaFunctionScheduled carries resource and input. resource holds the full function ARN. LambdaFunctionStarted carries 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.

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 -1 and $partition(items, 2.9) chunks by 2.
  • Several arguments evaluate to undefined rather than failing: a chunk size of zero, an empty array, a $range with no step or with a step whose sign disagrees with the direction, and a $hash with no algorithm. The argument itself does not fail; the field the expression was written in does, under States.QueryEvaluationError, as the section above records.
  • $range collapses 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 startDate on the wire is a StartDate in 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