nemo_gym.server_runtime.base_resources_server
nemo_gym.server_runtime.base_resources_server
Module Contents
Classes
Functions
Data
NEMO_GYM_MCP_SESSION_TOKEN_HEADER
API
Bases: BaseVerifyResponse
Base verify response for environments with multiple reward objectives.
Subclass this response instead of declaring reward_components on an
environment-specific BaseVerifyResponse subclass. The mapping is required, and
its objective keys should remain consistent across every task in the environment.
Set the inherited reward to the scalar aggregate expected by single-reward
consumers. To include individual objectives in aggregate metrics, also expose them
as top-level numeric fields because metrics do not descend into this mapping. See
resources_servers/example_tool_call_multireward for a complete example.
Bases: BaseServer
Bases: BaseRunServerInstanceConfig
Bases: BaseModel
Bases: BaseModel
Bases: BaseModel
Bases: BaseRunRequest
Bases: BaseVerifyRequest
Producers learn about a name outside the vocabulary without losing the failure.
Validation warns rather than rejects: an unregistered kind is a migration signal, and dropping the response over it would replace a visible wrong label with an invisible lost failure.
Bases: typing.TypedDict
The verify response fields of a masked sample for a session the server no longer holds.
Bases: BaseModel
Metadata returned from /seed_session for per-rollout Gym MCP access.
Bases: BaseModel
Close resources-server state.
Bases: BaseModel
Confirm resources-server state was closed.
Bases: HTTPException, ValueError
Refuse a seed whose input no retry can fix, such as task_data that fails validation.
FastAPI answers it with HTTP 422, which an Environment Server treats as terminal, so the episode fails once
with this message instead of being dispatched again with the same input. It is also a ValueError, so code
that seeds outside a request (a direct call in a test) keeps catching it as before.
Bases: BaseModel
Idempotently initialize resources state under a caller-assigned identifier.
Repeating the same identifier and episode must return the existing session. Closing an unknown identifier must prevent a racing seed from creating it for session_close_retry_window_seconds (see ResourcesSessionFences); callers must use unique IDs and finish seed retries within that window. External resources should use provider TTLs when available. Current process-local session records may remain until the server shuts down.
Bases: BaseModel
Confirm resources state and return optional agent access and an initial observation.
Preserve the seed wire shape when the server supplies no observation field.
Bases: HTTPException, ValueError
Refuse a seed or close that conflicts with what this server recorded for the session.
Examples: a resources_session_id already bound to another episode or task, a close that names another
episode, or a seed for a session that already closed. FastAPI answers it with HTTP 409, which an Environment
Server treats as terminal. It is also a ValueError for direct callers.
Bases: Generic[FenceRecordT]
The fences of the resources sessions this worker closed, each lasting the close retry window.
A fence is the record a close leaves so that a seed arriving after the close (a retry, or a reply that raced
the close) is refused instead of creating the session again. Each fence holds a record of the server’s choice,
such as the episode that first closed the session, which a retried close can check.
A fence expires close_retry_window_seconds after the first close; a retried close does not extend it.
Construct it with the server’s session_close_retry_window_seconds.
With several workers, the worker’s ownership of the ID expires that long after the last request for the session,
and the fence is set before the close’s reply is sent.
So ownership never expires before the fence
(see nemo_gym.server_runtime.request_handling.session_routing.ResourcesSessionLifetimes).
While ownership lasts, a late seed reaches the worker that holds the fence and is refused.
After it expires, every worker treats the ID as new, so the answer does not depend on which worker gets it.
Delete every fence, for a server that drops all of its sessions at shutdown.
Fence a closed session; call it only after its state was released.
A retried close keeps the first close’s record and expiry.
Return the record of the session’s fence, or None if it is not fenced or its fence expired.
A fence may hold a None record, so test resources_session_id in fences to ask whether a session is fenced.
Refuse a seed for a fenced session with 409, which the environment server treats as terminal.
Lock each resources session so that its seed and close never interleave.
A session’s lock exists only while a request holds or waits for it.
Hold the lock for resources_session_id.
Bases: HTTPException
Answer a tool call for a session this server no longer holds with HTTP 404.
Raise this instead of returning an ordinary tool observation that says the session is gone. What a harness does
with the 404 varies: simple_agent returns its body to the model as the tool output and keeps going, Stirrup
fails the run so the episode is dispatched again, and an MCP client reports a tool error. In every case the
trajectory records a failed tool call whose detail names the failure_kind, which a log can group by. The
verify for the session answers with lost_session_verification, whose masked sample keeps the episode out
of the score.
Bases: BaseModel, Generic[VerificationInputT]
Carry typed environment output to a resources server.
Bases: enum.Enum
Bases: BaseResourcesServer, AggregateMetricsMixin, SimpleServer
The participant that takes part in partial-rollout checkpoints, or None with checkpointing off.
The session and attempt an MCP request’s signed token names.
None without a token or for one that does not verify; the MCP endpoint rejects a bad token.
An attempt claim that does not decode counts as missing.
Compute aggregate metrics from verify responses.
RewardProfiler provides baseline stats. Override compute_metrics(), compute_repeat_metrics(), and/or get_key_metrics() for benchmark-specific customization.
Report that the request’s session ended; standard /close_session and /verify do this.
Call it from a protocol route that ends a session under another name, such as a terminal step.
Close state an Environment Server seeded; the default keeps none.
Served at /close_session. Servers that keep per-rollout state override this method, and may accept
other close bodies by overriding it with a different signature. The name differs from the
close_session helpers some servers already define for their own state.
An override must:
- succeed when the session is already closed or was never seeded;
- keep a seed that arrives after the close from creating the session again, for a bounded time
(
ResourcesSessionFencesdoes this forsession_close_retry_window_seconds); - release the session’s state by
resources_session_ideven when the request carries no session cookie; - raise when releasing fails rather than recording the session as closed, so the caller can retry.
A served resources server routes sessions (see nemo_gym.server_runtime.request_handling.session_routing):
an episode seed’s session cookie carries resources_session_id as its SESSION_ID_KEY, and an episode
close that carries no cookie, as when the seed’s reply was lost, is given that ID too, so a server may key
state by either; they name the same session. An app built without session routing, such as one under TestClient, gives a new session a random
ID instead, so release by body.resources_session_id to be correct either way.
nemo_gym.server_runtime.testing.session_conformance.check_resources_session_contract checks these rules from a server’s tests.
TODO: also expire sessions that are never closed, as when the environment server dies before its close. Planned
rule: a fixed lifetime from the seed (the sandbox ttl_s when set, else 24 hours), checked on the next
request and at shutdown; an expired session is released, fenced, and verifies as SESSION_EXPIRED.
Build the app with what every resources server shares, whatever its episode protocol.
That is the session and rollout middleware, the checkpoint participant,
/aggregate_metrics and /reverify_mode.
A server with another protocol, such as Gymnasium’s /reset and /step,
overrides register_protocol_routes instead of building its own app.
Return each session’s state for a checkpoint, leaving out sessions this server no longer holds.
Per-session tool restriction: return the tool names allowed for this rollout’s MCP token,
or None (the default) for unrestricted. seed_body is the JSON body POSTed to
/seed_session, or its task_data when an Environment Server seeds the session.
Return the MCP tools to expose (default: the auto-harvested typed POST routes).
Override to exclude (filter harvested), add catch-all-backed tools (harvested + [catchall.tool(…)]), or disable (return None). ‘catchall’ is None unless the server has one parameterized catch-all route.
Strip this server’s MCP namespace from a trajectory tool-call name (see module function).
Register the episode routes /seed_session, /close_session and /verify.
Validate every state, then install all of them; never install a partial set.
Discard a session whose attempt was retired; called in every checkpoint mode.
The default does nothing. A server that keeps per-session state releases it here, since a retired session’s late requests, a terminal step among them, are refused.
Seed per-rollout state; the default keeps none.
An Environment Server seeds with a ResourcesSeedSessionRequest and gets its caller-assigned
resources_session_id back. An Agent’s /run seeds with its legacy body and gets an empty
response. Servers that keep per-rollout state override this method.
An override refuses a seed that no retry can make succeed with a terminal 4xx, never a plain exception (HTTP 500), which the Environment Server retries by dispatching the whole episode again:
ResourcesSeedRejectedError(422) for input that fails validation, such astask_dataor aTaskIdthat does not match the task row;ResourcesSessionConflictError(409) for an ID bound to another episode or task, or a closed session.
A failure that a retry may fix, such as an unavailable sandbox provider, stays a 5xx.
Score the episode.
A server whose score depends on per-rollout state answers a verify for a session it no longer holds
(never seeded, closed, or lost) with a masked sample built by lost_session_verification, never a
plain reward of 0 and never an exception that dispatches the episode again. A tool call for such a
session raises ResourcesSessionLostError (404).
Return the verify response fields for an episode whose session this server no longer holds.
The sample is masked: the environment lost the state it would measure, so a reward of 0 would read as a
policy that solved nothing. Merge the result over the request’s fields so these win, for example
BaseVerifyResponse(**(body.model_dump() | lost_session_verification("sandbox gone"))); spreading both as
keyword arguments raises TypeError when a request model that allows extra fields already carries a
reward. Use failure_kind=SESSION_EXPIRED when the server closed the session itself because its lifetime
ran out.
Each call logs a warning, because a masked sample is otherwise visible only in coverage metrics: many of them
point at a wiring fault such as a session cookie that never reaches /verify.
The payload of a Gym MCP session token whose signature verifies, or None if it does not.
The signer of Gym MCP session tokens; build it once per server.
Map a trajectory tool-call name to the server’s bare tool name.
HTTP-driven agents record bare tool names (“email_reply_email”); MCP-native agents (e.g.
Claude Code) record them namespaced per server (“mcp__workplace_assistant__email_reply_email”).
Verifiers compare trajectory names against dataset/ground-truth vocabulary, so names are
normalized before verify sees them and rollouts score identically on both transports.
Non-namespaced names pass through unchanged. When server_name is given, only that server’s
prefix is stripped (robust to tool names that themselves contain double underscores).
This runs only for servers exposed over MCP and mirrors how MCP clients namespace tool names,
so a real tool that is itself named mcp__<server>__x being stripped is accepted.