Scaffolding a Simulated API Backend as a Gym Environment Without Mocking Away Stateful Side Effects
Stateful API simulators preserve causal consistency that mocks cannot test.

Gymnasium is the standard interface for building custom RL environments, and a stateful API simulator is the world an agent acts on. Wrapping that simulator in reset() and step() tests sequential API behavior without mocking away its side effects. The decisive criteria are deterministic reset, causal state transitions, and rewards based on world state.
Why stateless mocks are structurally incapable of testing sequential API behavior
A stateless mock answers each request independently of earlier calls. It has no record of what happened. When a create response and a later fetch response contain the same transaction ID, their agreement comes from the developer’s fixture configuration. Adding more fixtures can cover more responses, but it cannot turn that agreement into evidence that the integration preserves cross-request consistency.
A checkout flow exposes the structural failure clearly. The application initiates a payment intent synchronously, then relies on asynchronous webhook delivery to fulfill the order. A static stub can return plausible payloads for both interactions without preserving the causal chain between them. The test can therefore pass even though it has never tested whether payment state produces the event that fulfillment requires.
What a stateful simulator actually preserves that a mock cannot
A stateful simulator maintains a world that accumulates changes. A GET after a POST returns the resource that was written, while a read after deletion returns 404. Later requests depend on actual earlier results. That dependency lets a workflow fetch the exact transaction ID or subscription object created during the episode, in place of an artifact the test author chose ahead of time.
The same memory extends beyond stored records. A simulator can track whether a webhook listener returned HTTP 2xx and schedule another delivery when it did not. Its state must also be inspectable, resettable, and forkable from outside the simulator so that an evaluator can control and judge the world. These capabilities establish the architecture, but not its fidelity. Continuous verification against the real API is the constraint that keeps a stateful implementation from quietly becoming an inaccurate one.
How the Gymnasium interface maps onto a simulated API backend
Gymnasium defines environments through Python classes that subclass gymnasium.Env. Its reset() method returns an initial observation and an information dictionary, which maps naturally to loading a known simulator state and exposing the first observation. Its step(action) method executes a transition and returns the observation, reward, termination flag, truncation flag, and information dictionary. The simulator controls what happens in the world when those calls run. The wrapper controls how they become an RL episode.
The action_space and observation_space attributes define the agent’s boundary. The former maps to allowed endpoints and parameter schemas, while the latter describes the exposed state, whether a full snapshot, a diff, or a structured summary. The observation can show less than the verifier can inspect. This separation lets the environment limit the agent’s view without weakening outcome checking.
The smallest useful gym combines a task world, an action interface, an episode runner, and a verifier. Gymnasium gives those parts a common container rather than requiring each training system to invent an interaction protocol. Its versioned environment names also support reproducibility. Changes that affect learning results belong in a new environment version.
Why reset() is the hardest part and how structured state solves it
If reset fails, earlier episodes can affect a run in ways the test cannot see. An old receipt can satisfy a lookup, while a scheduled webhook retry can complete a task after the next episode has begun. Parallel workers can also mix up runs when one worker reads a record that another created. These are measurement errors. They can make an agent appear successful because another run already did the work.
MobileGym captures environment state as structured JSON through a layered model separating world data, runtime state, and OS state. That representation makes state readable for judging, writable for reset, and forkable for parallel rollouts. The corresponding API design treats reset as a complete state load, including the runtime state that governs pending work.
An empty database removes the conflicting records and partially completed transactions that make API tasks demanding. Seeded snapshots preserve that friction while allowing repeated trials under identical conditions. MobileGym’s reported training gain was largely preserved on real devices, supporting the usefulness of simulation without establishing fidelity for any particular API backend.
How step() must handle stateful side effects rather than mocking them away
A step() implementation that intercepts calls and returns fixtures recreates the original defect inside a standard interface. The call must change the simulator’s world. Creating a resource writes it to the state store, subsequent reads retrieve it, and deletion removes it. Generated identifiers must remain consistent because the simulator stores the corresponding objects.
Asynchronous behavior also belongs to that world. Webhooks need scheduled transitions governed by the simulator’s clock rather than immediate responses that erase delivery delays. Stripe does not guarantee event order, allows duplicate deliveries, and retries undelivered events for up to three days. A simulator representing those semantics needs event emission and retry scheduling. Otherwise, the policy learns a simpler delivery model than the service provides.
PayPal retries failed webhook deliveries multiple times over several days, so delivery status and HTTP 2xx acknowledgments must affect when the next delivery is scheduled. Kalshi exposes another kind of coupling, where order fills change position records. Returning a successful fill without updating the position creates a causally broken trading world. Faults must preserve these dependencies too. A timeout changes what the agent observes, but it cannot automatically erase a write that already committed.
Designing the reward signal and verifier against world state, not agent transcript
A success message is not proof of task completion. The verifier must inspect whether the record exists, whether the balance reflects the transaction, and whether the webhook listener was reached and returned HTTP 2xx. The agent’s description of its work can disagree with them without altering the verdict.
Correct completion also includes the absence of unintended changes. Full-state comparison can detect an agent that completes a payment task while also sending an unintended message. A verifier restricted to the payment record would miss that mutation. EnterpriseOps-Gym frames evaluation around stateful planning and tool use in an interactive enterprise sandbox, where the resulting state is the relevant object of evaluation.
For training, the same state access can support intermediate rewards as well as a final verdict. A step can receive credit for an expected state change without treating its response body as the complete outcome. MobileGym’s AnswerSheet protocol offers a related principle through typed fields and type-specific matching. Structured assertions make the acceptance condition explicit.
The verifier itself needs a valid contract. Requiring a value absent from both the seed state and the prompt creates an impossible task. Checking a field the simulator never persists creates a broken evaluation. Accepting the agent’s own outcome report instead creates a circular one.
Fault injection as a first-class gym action, not a test afterthought
Fault conditions need to be part of the environment’s transition model. A configurable 429 with a Retry-After header, a 503, a dropped connection, or a delayed webhook lets the episode expose recovery behavior under controlled conditions. Retry, backoff, escalation, and duplicate writes then appear in the same episode trace as ordinary actions. Recovery becomes a trainable behavior.
AgentCheck (2026) demonstrates a controlled comparison pattern. It runs an agent against its real tools, holds every tool response constant except one, and perturbs that response with a fault injector. Its open suite has 120 scenarios that cover 12 fault types. Replaying the same fault after a mitigation allows a developer to compare clean and faulted behavior without changing the disturbance.
The simulator must keep track of the fault’s commit boundary. When a write succeeds but its acknowledgment is lost, retrying without checking for the existing record can create a duplicate. A state-based verifier can spot the extra record even if the agent says it recovered. A simulator that forgets whether the write committed cannot represent this partial failure honestly.
Horizontal scaling and parallel rollouts without live credentials
Parallel RL requires isolation as well as throughput. Live API sandboxes can share global state and account-level rate limits across sessions, so workers may interfere through both data and request budgets. A vendor’s sandbox allocation also constrains how many isolated worlds a training run can create.
With a containerized simulator, each worker has its own state store and rate-limit counters, with no shared live credentials. Loading the same snapshot into separate instances lets group-based methods such as GRPO run the multiple rollouts they need from the same initial states. Forking removes the need to reconstruct those conditions through live API calls.
MobileGym demonstrates hundreds of parallel instances on a single server, with roughly 400 MB RAM and roughly 3 s cold start per instance. Those figures come from MobileGym and do not guarantee how much memory or startup time an API simulator will need. The transferable principle is programmable, isolated state. A local process or private cluster can also run API training offline, with no outbound calls to the real service.
What a verified simulator adds over a hand-rolled stub in this architecture
A hand-rolled stub encodes its author’s understanding of the API when it was written. Undocumented schema changes, new error codes, and altered retry semantics can leave that understanding behind without making the gym fail. Stateful behavior alone cannot expose the divergence.
Verification against the real API before each release gives a simulator version an evidenced scope of fidelity. Exact error payloads and retry semantics are part of that scope. Plausible error responses can otherwise make invalid calls look like evidence that an endpoint works. Verification does not replace the task verifier. The former assesses the backend’s correspondence to the service, while the latter judges the agent’s changes within that backend.
Putting the architecture together — a Gymnasium env class backed by a stateful API simulator
The buildable pattern is a Python gymnasium.Env subclass with a simulator client, a snapshot protocol, an action schema, a world-state reward function, and a verifier. Its initializer connects to the local simulator process or container and defines both spaces. The wrapper remains an adapter. Resource mutation, webhook scheduling, and retry behavior stay in the simulator that owns the world.
In this sketch, reset(seed=None) loads a known snapshot or seed-derived variant and returns the initial structured observation with its information dictionary. For parallel rollouts, it loads that snapshot into an isolated instance. The corresponding step(action) serializes the action into an API call, executes it, and reads the resulting state. It then computes reward, checks termination and truncation, and returns Gymnasium’s standard five-tuple. A verifier hook checks the actual state against the intended outcome and flags mutations the task did not call for.
Fault configuration can be exposed through a method or action type that affects the next calls without rewriting the wrapper’s core logic. Before model training, the recommended validation is a deterministic scripted policy that completes the task, followed by a deliberately broken policy that the verifier must reject. Both directions need to work before the score is credible. Environment names should use a suffix such as -v0 and move to the next version when changes to state, action, or reward affect what the agent learns. Real service credentials stay outside the training loop, so the agent learns in a controlled world where it cannot talk away the effects of its actions.
Sources
- MobileGym: A Verifiable and Highly Parallel Simulation Platform for Mobile GUI Agent Research
- Paper page - EnterpriseOps-Gym: Environments and Evaluations for Stateful Agentic Planning and Tool Use in Enterprise Settings
- Env - Gymnasium Documentation
- Gymnasium: A Standardized Interface for Reinforcement Learning Environments


