Replacing a Stub Environment With a Commercial Simulator as the Authoritative Gym Step Function
Replace mock APIs with stateful simulators to train agents on realistic state transitions.

To use an API in an RL environment, make step() a thin adapter to a commercially verified, stateful API simulator. The simulator should own the world’s state, while the Gym environment translates actions, encodes observations, and computes rewards from the resulting state. Its authority depends on enforced transitions, isolated resets, and continuous comparison with the real API.
Why a hand-rolled stub breaks under a real RL training loop
An agent creates an order and receives an ID. It polls that order’s status, then attempts to cancel it. If the order has already completed, cancellation should return a 409 conflict. The next decision depends on that history. But when every status request returns the same pending-order fixture, completion is unreachable, and the agent never encounters the conflict it must learn to handle.
That is the structural failure of a stateless stub. It maps a request to a response without remembering what happened before. Even the creation response can be misleading, because its returned ID does not identify anything stored in the environment. A later read thus returns either a 404 or another hardcoded fixture that has nothing to do with what was created. The apparent sequence of API calls has no referential integrity.
The consequences reach directly into training. An action at step t must change the world observed at step t+1, or reward and next-state computation describe a fiction. Patching fixtures to agree with one another only starts a maintenance trap, because each new transition requires another manual update. Enforcing idempotency keys, valid status transitions, and resource relationships requires an actual state model. Otherwise, the policy learns to exploit inconsistencies that disappear when it reaches the real service.
What the Gym step() contract actually requires from the environment
Gymnasium defines step(action) as returning (observation, reward, terminated, truncated, info). RLlib, Stable Baselines3, and CleanRL adopt this environment API, so the replacement need not change the training framework. The contract stays the same. Each returned value must now reflect the action’s effect on a persistent world.
For an API-dependent agent, observation encodes the external state after the action. Likewise, reward must depend on the outcome, because cancelling a pending order is different from attempting to cancel a completed one. The adapter can use info to share details of the outcome while keeping them apart from the observation itself. These values must describe the same transition.
terminated marks a true episode end, such as reaching a goal or entering a terminal state, while truncated marks a cutoff such as the episode time limit. Conflating them biases value estimates. The simulator supplies the state needed to judge termination, but the environment still applies its own time limit. A stopped rollout does not necessarily mean the simulated task has ended.
Reproducibility adds a further requirement to that contract. With the same seed, action sequence, and environment state, the results must be statistically consistent. A live third-party API brings rate limits, downtime, and nondeterministic side effects that the environment cannot control. Those dependencies also slow the training loop. Every remote request sits on the path to the next observation, so environment throughput becomes an architectural constraint.
What properties a simulator must have to serve as an authoritative step() function
Four properties make a simulator credible for reward and next-state computation, namely persistent cross-request state, enforced state machine transitions, continuous fidelity verification, and first-class fault injection. Persistence starts with resource identity. A resource created in one call must exist when a later call reads its ID. Lists must reflect created and deleted resources, updates must propagate, and deletes must remove their targets.
Redocly’s sandbox requirements guide defines a true sandbox as one where “creation, updates, and deletions are remembered during a session” and an invoice “contributes to account totals”. That standard extends beyond storing individual records. It requires one mutation to affect the other views that depend on it. The same guide identifies state transitions, transactional logic, and asynchronous processing as cases requiring a full sandbox. A simulator that accepts every action in every state cannot provide credible evidence for terminated.
Persistence alone does not establish accuracy, however. A simulator built once and never compared with the real API can drift as that API evolves. Handwritten behavior inherits its author’s assumptions, while specification-derived behavior inherits the specification’s omissions. Neither provides its own warning of staleness. The defensible requirement is probing against the live API before every release, with published fidelity scores for the endpoint surfaces the agent will use.
The policy must face 429 rate limits, 503 service-unavailable responses, and latency spikes during training, before it meets them in production. A stateful simulator can also return a 500 after a successful transition, exercising recovery when the error response does not mean the mutation failed. A fixed error fixture cannot establish that distinction. Realistic pre-seeded data further broadens the observation space, exposing entity states, relationships, and edge cases that an empty starting world would omit.
How to wrap an external API as a Gym environment through a stateful simulator
The migration is a contained change to the environment. The simulator takes over state management, while the adapter retains action translation, observation encoding, reward logic, and episode boundaries. To make that separation explicit, map each existing route to the action it supports and identify mutations, reads, and asynchronous events. A pseudocode sketch is request = translate(action); result = api_call(request). The translation table replaces route-specific fixture selection without recreating the simulator’s state machine inside the adapter.
Before the training loop starts, launch the simulator as a subprocess or sidecar on a dedicated local port. The setup sketch is simulator = start_local(); client = connect(simulator.url). All training calls then go through that scoped client, with no need for live credentials or an external network and no upstream rate limits. In CI, the service belongs to the job. Its URL must stay job-scoped, because putting it in global configuration could redirect calls in another environment.
Next, implement reset() using the simulator’s reset primitive. The sequence is simulator.reset(seed_scenario); state = read_initial_state(); return encode(state), info. The starting point can be empty or a named seed scenario, but it must be known. Without that reset, one episode inherits another’s mutations and changes the training distribution. Resetting only the adapter’s counters leaves the external world untouched.
In step(), translate the action, run it, and read the resource state it leaves behind. The core sketch becomes result = execute(action); state = read_resource(); observation = encode(state). Structured JSON must be turned into the fields that the observation space expects, including fields that are present only because of earlier actions. Referential integrity makes those dependencies real. The encoding must handle both a populated relationship and an absent one rather than assume that every fixture field always exists.
The sketch is reward = score(state, result), so an attempted cancellation does not automatically earn the reward for a successful cancellation. In the order example, a read showing cancelled supports a positive reward, while a cancellation rejected with 409 because the order already completed follows the error path. The action alone cannot distinguish those outcomes. Reading the resulting world also prevents the adapter from treating an intended mutation as an accomplished one.
The sketch is terminated = is_terminal(state); truncated = time_limit_reached(); return observation, reward, terminated, truncated, info. A payment intent reaching succeeded or canceled with no further valid transitions can establish a true terminal state. The time limit remains a separate condition. This preserves the distinction the learning algorithm needs without making elapsed time part of the simulator’s business logic.
Start without faults, then progressively introduce 429s and 503s so that the agent learns recovery before deployment. The sketch is simulator.configure_faults(curriculum_stage), representing a configuration change with the adapter unchanged. State remains authoritative during these failures. Recovery training must still distinguish a rejected action from a completed mutation followed by an error response.
Asynchronous workflows require one final change to the step loop. When a mutation produces its result through a webhook, the sequence becomes execute(action); event = wait_for_webhook(); state = incorporate(event); observation = encode(state). A simulator that emits webhooks on transitions can support this sequence. A stateless fixture has no transition from which to emit an event, leaving the asynchronous part of the task outside training.
Scaling the simulator across parallel training workers in CI
Parallel rollout generators each need their own world, even when they already have their own clients. GRPO and RLOO workers must not see resources that another worker has created, changed, or deleted. Shared state corrupts rollouts. With a containerized simulator, each worker receives its own instance, so both persistent state and episode resets stay within that container. The isolation primitive is the simulator instance rather than a convention about which worker may touch which resource.
This changes the architecture relative to a shared vendor sandbox. Workers using the same live credentials share rate limits, and their sandbox state is not automatically isolated. Each remote call also adds time to step() because of network latency. With local instances, workers avoid those shared dependencies and have no need to coordinate their mutations. This setup also allows offline or air-gapped training because the simulator makes no outbound calls during the training run.
In CI, this isolation fits the job lifecycle. The job starts its simulator services, scopes training calls to their localhost URLs, and tears them down when it ends. Each worker resets only its own instance. A successful job then shows that the policy has run against a stateful world, going beyond the playback of response fixtures. It does not, by itself, establish that the simulated world matches every behavior of the vendor API.
In modern post-training workflows, environment rollout throughput can determine training wall-clock time more than GPU count. Removing the remote round-trip eliminates a recurring cost from each API-dependent step. More workers can then generate rollouts without competing for the same upstream request allowance. This architecture makes stateful training viable at scale, but its usefulness still depends on whether those fast rollouts teach the right behavior.
The fidelity problem: how you know the simulator is telling the truth
The legitimate worry is that a simulator introduces a second implementation that can diverge from the real API. That would reproduce the original failure in a more convincing form. The agent could learn to exploit simulated behavior and fail on the actual service. Neither commercial packaging nor realistic JSON resolves that objection. Resolving that objection requires a verification method whose results the user can inspect.
The live API must be the ground truth. Continuous automated probing before every release compares the simulator with that reference rather than assuming that an earlier implementation remains accurate. Specification-derived simulators need this comparison too, because a stale or incomplete OpenAPI document can produce stale or incomplete behavior. Structural agreement is not sufficient. The tests must check the state machine semantics that the agent relies on to make decisions.
Published fidelity scores make that evidence available for scrutiny. A useful score is a versioned artifact showing how much of an endpoint surface is verified and how many probes support the result. Its coverage must fit the training task. A team training an order-management policy needs evidence for the transitions and relationships that policy uses.
Reka Labs’ WorldModelGym framing defines decision-based fidelity through the real-world consequences of acting on a model’s predictions. For an API environment, the practical question is whether success in simulation transfers to the real service. Matching response shapes cannot answer it alone. Even with a great deal of probing, some details of vendor-specific business rules will be missing, including card-network-specific decline codes in a payment processor.
The resulting workflow has two phases. Training against the simulator validates integration patterns through repeatable state transitions, controlled failures, and isolated rollouts. A final validation pass in the vendor’s own test mode or sandbox then checks the policy before it goes into production. That pass does not replace scalable simulation, and simulation does not replace it.


