Modeling Complex API State Machines Inside a Controllable Test Simulator
Enforce state transitions and side effects to test APIs without hitting production.

Integration testing against stateful APIs requires a controllable simulator that enforces legal states, valid transitions, and side effects across ordered calls. Modeling complex API state machines makes it possible to test an integration without hitting production while preserving the constraints production enforces. The simulator must also support controlled failures and deliberate updates when the real API changes, or passing tests will offer false confidence.
Why API simulators fail when they treat state as an afterthought
A four-step probe exposes the basic distinction. POST a resource, GET it back, mutate it, and GET it again. In a stateful simulator, the final GET reflects the mutation made by the preceding call. In a stateless mock, it returns whatever response was configured for that route. The response may look correct in isolation while revealing nothing about whether earlier operations had any effect.
A test might POST a customer, POST a subscription referencing that customer, and then GET the subscription to assert that the customer appears on it. Hardcoded responses can make every assertion pass without ever checking that the customer exists or that the relationship persisted. The test has checked only the configured answers, leaving the integration’s behavior under the API’s constraints untested.
That gap can remain hidden through repeated successful builds. Production then rejects an operation because the resource is in the wrong state, a referenced resource does not exist, or an earlier call changed which operations are allowed. Those failures can all happen with the expected response shape. They arise because the real API interprets each request in the context of previous requests, while the mock treats each request as independent.
What a state machine actually is in API terms
An API state machine describes the states a resource can occupy, the permitted moves between them, and the effects of those moves. Stripe’s PaymentIntent reference identifies states including requires_payment_method, requires_confirmation, requires_action, processing, requires_capture, succeeded, and canceled. These are not merely labels for response fixtures. They determine what can happen next.
A valid transition moves a resource from its current state to another state through an allowed operation. A canceled payment cannot transition to succeeded, so a simulator that accepts that change contradicts the behavior it is meant to represent. Storing the new status faithfully does not make the operation valid.
Side effects complete the definition of a transition. Depending on the operation, a transition may create child resources, trigger a webhook, update a balance, or change which later operations are permitted. A payment-intent simulator therefore needs more than a status field that changes when called. It needs to represent the observable consequences that the real API attaches to each permitted change.
The API’s documentation and enforcement logic often leave this model implicit. A resource reference may enumerate statuses without presenting the full set of rules connecting them. Making those rules explicit gives the simulator a working definition of correctness, including both the operations it must accept and the operations it must reject.
How to identify the state machine hidden inside a real API
Before simulator code is written, the model must be worked out from documentation and controlled experiments. The provider’s OpenAPI or AsyncAPI specification supplies resource shapes and status enums, but transition rules often require further investigation. Stripe’s payment resources are a place to start when studying synchronous operations. Kalshi’s WebSocket feed makes the asynchronous portion of the investigation equally important.
An operation attempted in the wrong state reveals the error response that the simulator must reproduce. Repeating an operation reveals whether the API applies idempotency or reports a conflict, while deleting a referenced resource exposes relationship and cascade rules. These probes turn a collection of endpoint definitions into rules for ordered behavior.
Retry semantics add constraints that a status diagram alone cannot express. Stripe’s idempotency documentation defines a maximum key length and permits keys to be removed once they are at least 24 hours old. Those constraints belong in the simulator’s model because a repeated request cannot be interpreted correctly without the applicable idempotency rules.
Asynchronous behavior extends the investigation beyond the REST response. With Kalshi’s WebSocket feed and Stripe webhooks, the synchronous response and the subsequent event represent distinct observable parts of the operation. Both must be modeled and tested. The target also changes over time, as a September 2026 Slack drift issue identified blocks.validate missing from client TypeScript typings, illustrating that the API surface and the client’s representation can diverge.
How to test APIs where order of operations matters by encoding the state machine
The encoding begins with a per-resource state store that persists across requests within a session. Its basic shape is straightforward. A POST creates an entry, a GET reads that entry, a PATCH updates it, and a list endpoint returns the live collection. This makes earlier calls observable to later ones, but storage alone does not enforce a lifecycle.
A transition guard supplies that enforcement before each state-mutating operation. It evaluates the resource’s current state and the requested transition, allowing the operation only when the modeled rules permit it. A capture call against a canceled payment must be rejected with the appropriate status code, error body shape, and error code. Accepting the call is a simulator defect.
The side-effect engine then represents the consequences of permitted transitions. For the payment-intent lifecycle, that means encoding status-string changes along with the applicable webhook, balance, child-resource, and subsequent-operation behavior. Otherwise, a test may see a successful status change but miss the side effects that its application relies on.
Idempotency must also be a first-class primitive. Without it, duplicate operations may pass through the simulator even when they violate the real API’s retry semantics. Per-session isolation prevents another source of misleading results, since stale data from earlier runs can corrupt a test’s assumed starting state. Each run should receive sandboxed state that resets on teardown, with realistic baseline data supplying the prerequisites so that tests can focus on the transition under examination.
Fault injection as part of state machine testing, not a separate concern
The model is incomplete if it represents only successful transitions. Fault states and fault transitions describe what happens when an operation encounters latency, a dropped connection, a partial response, a 429, or a 503. These conditions test the integration’s handling of an interrupted or rejected operation. They are part of the integration contract.
Consider a gateway that keeps returning 503s while the service retries without backoff. The retry storm can saturate the connection pool, while a circuit breaker configured for 500s fails to open on 503s. A simulator must sustain the fault across a sequence of calls to expose that interaction, rather than return one error followed immediately by success.
Provider requirements can make retry behavior an explicit obligation. Kalshi’s Developer Agreement requires exponential backoff rather than immediate retries as part of its API best practices. A simulator that can sustain rate limits or service errors allows that behavior to be tested without relying on the live demo environment. Rate-limit tests also need the details that come back in the response, including Retry-After headers.
PayPal retries failed webhook deliveries many times over three days, while Stripe retries undelivered webhook events for up to three days. The test model thus needs an endpoint that is unavailable for a time, along with replay handling and deduplication. Running these network-fault and API-fault tests on every pull request keeps resilience logic under the same scrutiny as successful transitions.
Why continuous verification against the real API is non-negotiable
A coherent state machine can still become an inaccurate one. Once the provider changes, a simulator that keeps the old behavior still gives repeatable results, but against an out-of-date contract. This is a particularly dangerous failure because the tests remain green and the simulator remains trusted. Determinism does not establish fidelity.
GitHub issue #104, dated 2026-09-28, described blocks.validate as absent from the public docs changelog and flagged it as low-confidence and potentially experimental. The missing client typing was a useful discrepancy, but the issue’s characterization of the method’s publication status was not a reliable basis for changing the model without further review.
Drift detection should work like a dependency bump. When live API behavior or format differs from a pinned fixture, the process presents a diff and requires explicit acceptance of the update. Silent automatic migration would remove the stable reference that makes a failing test interpretable. Never updating would preserve repeatability at the expense of correctness.
Two mechanisms must remain separate throughout this process. During a test run, the simulator’s state machine stays frozen so that the same sequence can be repeated. Between versions, deliberate migration brings in provider changes that have been reviewed. Contract testing with tools such as Pact supports this verification by checking consumer and provider adherence to a shared contract without replacing the need to verify stateful behavior.
How stateful simulators serve AI agent testing and RL environments
An AI agent that calls external APIs faces the same constraints as a conventional integration. Its next action often depends directly on what the previous action produced. A stateless response can therefore distort both the observed result and the next decision. The evaluation no longer represents the environment the agent will encounter.
A multi-turn Stripe workflow makes that dependency concrete. An agent may create a customer, create a subscription for that customer, and then query the subscription balance. The simulator must preserve the resources and relationships established across those calls. Canned responses that ignore the sequence cannot show whether the agent carried out the required operations in a valid order.
Fault transitions also broaden what the evaluation can measure. Tool selection and parameter accuracy remain important, but the agent must also handle a 503 or a resource whose current state forbids the requested operation. These conditions distinguish successful behavior on a prepared path from robustness under API constraints. The same transition guards used for application tests provide those constraints for agent tests.
RL environments add a scale requirement without changing the correctness requirement. Thousands of parallel rollouts need independent state, so horizontal scaling across containers must not leak one session’s resources into another. AWS’s ToolSimulator within Strands Evals offers a different approach through simulated tool responses for safe, scalable agent testing. LLM-based simulation is a legitimate tool for safety evaluation, but its approximation cannot substitute for a verified, deterministic state machine when the goal is correctness against a specific API.
What a correctly modeled state machine looks like in a CI pipeline
In CI, each test run receives an isolated session with realistic baseline data and a fixed version of the modeled API behavior. The application performs its ordered calls against that session, and the simulator enforces relationships, transition guards, idempotency, and side effects. Final assertions read the state produced by the sequence.
Fault tests also run in this pull-request pipeline. They keep service errors going and test rate-limit handling and webhook replay behavior so that changes to retry or deduplication logic get checked. The build path no longer depends on live third-party credentials, rate limits, or availability. Provider verification remains a separate process that proposes reviewed changes to the pinned model rather than changing behavior underneath a running test.
This separation gives CI both repeatability and a route to continued accuracy. State-transition violations can be caught before staging because the simulator rejects the same forbidden operations the integration must handle in production. A stateless fixture cannot supply that evidence, even when it returns the right response fields.
The same simulator can then run locally and in an RL training cluster with hundreds of parallel containers. Per-session isolation preserves the modeled rules regardless of where the test runs or how many other sessions exist. The decisive criterion is whether each result follows from the accumulated history of permitted operations, including failures, rather than from a plausible answer assigned to an endpoint.


