nemo_gym.server_runtime.base_environment_server
nemo_gym.server_runtime.base_environment_server
Shared lifecycle for environment servers, and the base for those that serve each episode’s tools.
Module Contents
Classes
Functions
Data
_RETRYABLE_CLIENT_ERROR_STATUSES
API
Bases: SimpleServer, Generic[EpisodeRequestT, EpisodeResponseT]
Expose a typed episode protocol with shared limits and cleanup.
A subclass implements run and registers the release of each resource it holds, such as a sandbox, in the
episode’s CleanupContext. When the server shuts down, it finishes the cleanups of every episode still
running (see finish_running_cleanups).
A handled failure that this episode met outside run; the episode fails with it when run returns.
Aggregate per-rollout scores into task-level metrics.
Record that a protocol step completed; state names the next step and what it needs.
While a checkpoint is open the episode parks here until resume.
A replacement attempt
that continues a checkpoint receives the latest recorded state from checkpoint_continuation.
Pass a function when building state costs something: it is called only with checkpointing on.
Return the protocol state this attempt continues from a checkpoint, once, or None.
Mark this episode as a restart: a server it uses cannot capture its part, such as a restart-only agent.
Call it when a seed reply says so (nemo_gym.server_runtime._checkpoint.steps.seed_restarts).
The episode then never holds up a checkpoint and is never exported; after a crash,
the controller starts it over from its input.
Run one protocol step as a wait or replay step (see nemo_gym.server_runtime._checkpoint.steps).
Use replay only for a step that is safe to run again after a crash
and does not change checkpointed state; everything else waits.
The wall-clock bound of this episode: default_episode_timeout_seconds (None is no bound).
A protocol whose tasks carry their own budgets may derive a longer one per episode (the Harbor server does for a multi-step task whose steps add up to more than the default); it must never raise here, as nothing of the episode has started yet.
Adapt runtime event, local policy and evidence to the protocol’s wire failure model.
The failure’s FailureReport goes in the reply’s failure_report, beside the failure.
Finish the cleanups of every episode still running; the server runs this when it shuts down.
Shutdown cancels the running /run requests and does not wait for them, so a second cancellation can
interrupt an episode’s cleanup partway. Cleanups are idempotent, so this runs each one that has not
finished, under its episode’s rollout. They all start at once, so a sandbox stop does not wait behind a
call to a Gym server that is shutting down too; a cleanup that needs another one to finish first awaits that
one’s CleanupHandle. The sweep waits cleanup_timeout_seconds in all, and logs each episode whose
cleanup it could not confirm.
The /ng-sampling/ value for one participant’s model calls in this episode, or None for none.
A participant the training framework trains samples with the values the episode carries. Every other
participant gets null: it keeps its own sampling, or its Model Server’s sampling_overrides. An episode
without values, as in Gym-only evaluation, gives every participant none, so its URLs stay as they are.
Run one concrete environment protocol.
Take part in partial-rollout checkpoints when they are enabled.
Every episode is tracked.
A protocol that records boundaries (checkpoint_mode = "exported") continues after a restore;
the episodes of a protocol that records none are restarts,
which never hold up a checkpoint and start over from their input after a crash.
Call this from any setup_webserver that builds its own app.
Finish the cleanups of every episode still running when app shuts down.
Call this from any setup_webserver that builds its own app.
Bases: BaseRunServerInstanceConfig
Configure protocol-neutral episode limits.
Bases: BaseEnvironmentServer[EpisodeRequestT, EpisodeResponseT]
An Environment Server that serves each episode’s tools itself, so it needs no Resources Server.
Each episode has a control plane and a data plane. The control plane is this server: it decides which operation
a tool call runs and with which limits, records the call and answers. The data plane is the episode’s sandbox:
it holds the episode’s world, such as a database, and runs every operation on it, the grader’s included. The
control plane never runs such an operation in its own process; it starts the sandbox with
start_episode_sandbox and sends the operation there. sandbox_provider says where the data plane runs.
run holds the episode’s state, and serve_tools grants the agent the episode’s tools until the episode
ends, over each transport in tool_transports. Every call carries the episode token in the
X-NeMo-Gym-Episode-Token header:
- direct HTTP: a separate request to
POST /<tool name>at the server’s root, as on a Resources Server; - MCP:
tools/callon/mcp, wheretools/listshows only the episode’s own tools.
Both transports check the token the same way. A request with an episode token reaches only the tools. Calls to
one episode run one at a time, whatever their transport, each under the episode’s rollout, and each is
recorded in ServedTools.calls. When the episode ends, a call still running is cancelled. A call that runs
longer than tool_call_timeout_seconds is cancelled and answered 504. A client that disconnects
cancels its call, which is recorded.
The tool route takes every one-segment POST path that the server does not route when setup_webserver
returns, so a subclass that adds its own routes gives them more than one path segment.
An agent may send the model’s call_id in X-NeMo-Gym-Tool-Call-Id; the record keeps it, to join the call
to the agent’s trajectory. Every call runs, as on a Resources Server: an agent’s client that resends a call after
a dropped connection runs it again.
The base refuses checkpoint_mode = "exported": a restored attempt has a new episode ID, and the agent’s
grant still names the old one.
A tool that raises a handled episode failure (handled_episode_failure), such as for a crashed sandbox,
fails the episode with it when run returns; the agent sees that call fail meanwhile.
With several workers, the worker that runs the episode owns it (see session_routing), so a tool call that
reaches another worker, over either transport, is forwarded there, by the episode its token names.
Run one call, under the episode’s rollout, and record it, including a call to a tool it does not have.
The open episode an episode token was granted for, or why the call is refused.
Run one tool call on the episode, after the calls before it, whatever its transport.
Grant the agent toolset for this episode, until the episode’s cleanup runs.
Returns one grant for each of tool_transports, for the agent’s seed
(AgentSeedSessionRequest.tool_accesses), and the list that records each call. A call after the episode
ends is refused. Declare the tools to the model with ToolSpec.function_tool.
Start a sandbox for this episode’s data plane, run setup in it, and stop it with the episode.
The stop is registered in cleanup before the sandbox starts, so the episode’s cleanup, or the shutdown
sweep, also stops a sandbox whose start or first stop failed. spec.ttl_s is required: the provider
reclaims a sandbox that a crashed server never stopped. Some providers ignore it: Docker when the spec sets
an entrypoint, Apptainer, Enroot and local. With them, a crashed server leaves its sandboxes running
until they are removed by hand. The spec’s metadata goes over the provider’s defaults, and the server’s name
and the episode’s rollout label the sandbox. A setup that fails stops the sandbox, within the cleanup
timeout, before its error propagates. Call it again for a second sandbox or a fresh one.
Bases: BaseEnvironmentServerConfig
Configure how a BaseEnvironmentServerWithTools grants and serves its episodes’ tools.
Hold bounded process-local cleanup callbacks for one episode.
Callbacks:
- are process-local Python objects, although they may issue remote close requests;
- run sequentially in LIFO order, each with its own cleanup timeout;
- must be idempotent because a timed-out remote request may have succeeded;
- are lost on process or host failure, so remote owners need expiry or reaping.
Callback failures or timeouts do not prevent later owners from tearing down their resources. Total cleanup is bounded by the number of registered callbacks times the per-callback timeout. Cleanup has no durable retry after this context is discarded.
Close one registered participant at a protocol boundary.
Run this idempotent callback once.
The episode timeout bounds calls made during the protocol. The context’s cleanup timeout bounds callbacks left for final unwinding.
The grants that give the agent one episode’s tools, and the calls it has made so far.
Refuse a request that carries an episode token anywhere but the episode’s tools.
The agent sends the token with every call it makes through the grant, so this stops a model’s call named
run (or ../run) from starting another episode on this server.
Turn a failed call to another server into the episode’s failure.
failure_reason keeps the dependency’s own explanation from its response body
(see format_exception_with_response_body), prefixed with the error’s class name when name_error_type is set,
and bounded to the failure’s 2000 characters. terminal defaults to
not is_retryable_dependency_error(error); pass it only where the stage decides on its own.
fields retain partial evidence for the response adapter, such as a partial response.
The environment’s handled episode failure: one NgFailureEvent with the local policy kept apart.
terminal and evidence are runtime outcome data for the response adapter, never event fields; the
adapter builds the protocol’s EpisodeFailure after cleanup. failure_kind is the outcome’s kind and
may stay unset; the event then records the registered episode_failed.
Whether error is an environment failure built by handled_episode_failure.
Return whether a failed call to another server is worth another episode attempt.
An HTTP error is classified by its status (see is_retryable_dependency_status). A refused or dropped
connection and a timeout are transient. Any other error, such as a reply that fails validation, would fail the
same way again.
Return whether an HTTP error status from another server is worth another episode attempt.
408, 425, 429 and every 5xx are retried; every other 4xx is terminal.