Skip to navigation

nemo_gym.server_runtime.base_environment_server

View as MarkdownOpen in Claude

Shared lifecycle for environment servers, and the base for those that serve each episode’s tools.

Module Contents

Classes

NameDescription
BaseEnvironmentServerExpose a typed episode protocol with shared limits and cleanup.
BaseEnvironmentServerConfigConfigure protocol-neutral episode limits.
BaseEnvironmentServerWithToolsAn Environment Server that serves each episode’s tools itself, so it needs no Resources Server.
BaseEnvironmentServerWithToolsConfigConfigure how a BaseEnvironmentServerWithTools grants and serves its episodes’ tools.
CleanupContextHold bounded process-local cleanup callbacks for one episode.
CleanupHandleClose one registered participant at a protocol boundary.
ServedToolsThe grants that give the agent one episode’s tools, and the calls it has made so far.
_CleanupEntry-
_EpisodeTokensOpenOnlyToolsRefuse a request that carries an episode token anywhere but the episode’s tools.
_OpenEpisode-
_Refusal-
_ToolOutcome-

Functions

NameDescription
_is_json-
dependency_failureTurn a failed call to another server into the episode’s failure.
handled_episode_failureThe environment’s handled episode failure: one NgFailureEvent with the local policy kept apart.
is_handled_episode_failureWhether error is an environment failure built by handled_episode_failure.
is_retryable_dependency_errorReturn whether a failed call to another server is worth another episode attempt.
is_retryable_dependency_statusReturn whether an HTTP error status from another server is worth another episode attempt.

Data

CleanupCallback

EPISODE_TOOL_SESSIONS

EpisodeRequestT

EpisodeResponseT

LOGGER

ToolTransport

_ENVIRONMENT_CHECKPOINT_MODES

_MCP_PATH

_MCP_TOOL_NAME

_RETRYABLE_CLIENT_ERROR_STATUSES

API

class nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServer()

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).

_admission
Semaphore | None = None
_checkpoint
EnvironmentParticipant | None = None
_running_cleanups
dict[int, CleanupContext] | None = None
applies_model_sampling
bool = False
checkpoint_mode
CheckpointMode = 'restart_only'
config
BaseEnvironmentServerConfig
request_model
type[EpisodeRequestT]
response_model
type[EpisodeResponseT]
nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServer._recorded_episode_failure(

A handled failure that this episode met outside run; the episode fails with it when run returns.

nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServer._unhandled_failure_response(
error: Exception
nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServer.aggregate_metrics(
asyncabstract

Aggregate per-rollout scores into task-level metrics.

nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServer.checkpoint_boundary(
state: dict[str, pydantic.JsonValue] | collections.abc.Callable[[], dict[str, pydantic.JsonValue]]
) -> None
async

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.

nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServer.checkpoint_continuation(
) -> dict[str, pydantic.JsonValue] | None

Return the protocol state this attempt continues from a checkpoint, once, or None.

nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServer.checkpoint_restart(
) -> None
async

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.

nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServer.checkpoint_step(
step_type: nemo_gym.server_runtime._checkpoint.steps.StepType
) -> contextlib.AbstractAsyncContextManager[None]

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.

nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServer.episode_timeout_seconds(
) -> float | None
async

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.

nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServer.finish_running_cleanups() -> None
async

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.

nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServer.model_post_init(
context: typing.Any
) -> None
nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServer.model_sampling_segment(
trained: bool
) -> str | None
staticmethod

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.

asyncabstract

Run one concrete environment protocol.

nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServer.run_request(
async
nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServer.setup_environment_checkpoint(
app: fastapi.FastAPI
) -> None

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.

nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServer.setup_shutdown_sweep(
app: fastapi.FastAPI
) -> None

Finish the cleanups of every episode still running when app shuts down.

Call this from any setup_webserver that builds its own app.

nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServer.setup_webserver() -> fastapi.FastAPI
nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServer.validate_response_identity(
) -> None
staticmethod
class nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerConfig()

Bases: BaseRunServerInstanceConfig

Configure protocol-neutral episode limits.

cleanup_timeout_seconds
PositiveFloat
default_episode_timeout_seconds
PositiveFloat | None = None
max_concurrent_episodes
PositiveInt | None = None
model_config
= ConfigDict(extra='forbid')
queue_timeout_seconds
PositiveFloat | None = None
nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerConfig.validate_queue_timeout() -> typing_extensions.Self
class nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerWithTools()

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/call on /mcp, where tools/list shows 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.

_episode_tokens
Optional[EpisodeTokens] = None
_open_episodes
Optional[dict[EpisodeId, _OpenEpisode]] = None
_reserved_tool_names
frozenset[str] = frozenset()
_session_owners
Optional[SessionOwners] = None
config
BaseEnvironmentServerWithToolsConfig
nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerWithTools.__init_subclass__(
kwargs: typing.Any = {}
) -> None
nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerWithTools._call_tool(
name: str,
arguments: typing.Any,
call_id: typing.Optional[str] = None
async

Run one call, under the episode’s rollout, and record it, including a call to a tool it does not have.

nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerWithTools._episode_for_token(
token: typing.Optional[str]

The open episode an episode token was granted for, or why the call is refused.

nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerWithTools._episode_session_id(
token: str
) -> typing.Optional[str]
nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerWithTools._is_tool_path(
path: str
) -> bool
nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerWithTools._mount_mcp_endpoint(
app: fastapi.FastAPI
) -> None
nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerWithTools._recorded_episode_failure(
nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerWithTools._run_tool(
name: str,
arguments: typing.Any,
call_id: typing.Optional[str] = None
async

Run one tool call on the episode, after the calls before it, whatever its transport.

nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerWithTools._tool_call_endpoint(
tool_name: str,
request: fastapi.Request
) -> fastapi.responses.JSONResponse
async
nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerWithTools.holds_session(
session_id: str
) -> bool
nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerWithTools.model_post_init(
context: typing.Any
) -> None
nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerWithTools.owned_session_routing() -> dict[str, typing.Any]
async

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.

nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerWithTools.setup_webserver() -> fastapi.FastAPI
nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerWithTools.start_episode_sandbox(
setup: collections.abc.Callable[[AsyncSandbox], collections.abc.Awaitable[None]],
name: str = 'sandbox'
async

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.

nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerWithTools.use_session_owners(
) -> None
class nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerWithToolsConfig()

Bases: BaseEnvironmentServerConfig

Configure how a BaseEnvironmentServerWithTools grants and serves its episodes’ tools.

sandbox_provider
str | dict[str, Any]
tool_call_timeout_seconds
PositiveFloat | None
tool_transports
list[ToolTransport]
nemo_gym.server_runtime.base_environment_server.BaseEnvironmentServerWithToolsConfig.validate_unique_transports(
classmethod
class nemo_gym.server_runtime.base_environment_server.CleanupContext(
cleanup_timeout_seconds: float,
failure_report: nemo_gym.core.failure_records.FailureReport = FailureReport()
)
Dataclass

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.

_cleanups
list[_CleanupEntry] = field(default_factory=list)
cleanup_timeout_seconds
float
episode_id
EpisodeId
failure_report
FailureReport = field(default_factory=FailureReport)
nemo_gym.server_runtime.base_environment_server.CleanupContext._observe_failure(
error: Exception
) -> None
nemo_gym.server_runtime.base_environment_server.CleanupContext.aclose() -> None
async
nemo_gym.server_runtime.base_environment_server.CleanupContext.register_cleanup(
name: str,
class nemo_gym.server_runtime.base_environment_server.CleanupHandle(
timeout_seconds: float
)
Dataclass

Close one registered participant at a protocol boundary.

entry
_CleanupEntry
timeout_seconds
float
nemo_gym.server_runtime.base_environment_server.CleanupHandle.close() -> None
async

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.

class nemo_gym.server_runtime.base_environment_server.ServedTools(
)
Dataclass

The grants that give the agent one episode’s tools, and the calls it has made so far.

calls
list[ToolCallRecord]
tool_accesses
list[ToolAccess]
class nemo_gym.server_runtime.base_environment_server._CleanupEntry(
name: str,
active: bool = True,
lock: asyncio.Lock = asyncio.Lock()
)
Dataclass
active
bool = True
callback
CleanupCallback
lock
Lock = field(default_factory=(asyncio.Lock))
name
str
nemo_gym.server_runtime.base_environment_server._CleanupEntry.close() -> None
async
class nemo_gym.server_runtime.base_environment_server._EpisodeTokensOpenOnlyTools(
app: typing.Any,
is_tool_path: collections.abc.Callable[[str], bool]
)

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.

nemo_gym.server_runtime.base_environment_server._EpisodeTokensOpenOnlyTools.__call__(
scope: dict[str, typing.Any],
receive: typing.Any,
send: typing.Any
) -> None
async
class nemo_gym.server_runtime.base_environment_server._OpenEpisode(
lock: asyncio.Lock = asyncio.Lock(),
running: typing.Optional[asyncio.Task] = None,
failure: typing.Optional[nemo_gym.core.typed_exceptions.NgFailureEvent] = None
)
Dataclass
calls
list[ToolCallRecord]
claims
EpisodeTokenClaims
failure
Optional[NgFailureEvent] = None
lock
Lock = field(default_factory=(asyncio.Lock))
running
Optional[Task] = None
specs
dict[str, ToolSpec]
toolset
EpisodeToolset
class nemo_gym.server_runtime.base_environment_server._Refusal(
status: int,
detail: str
)
Dataclass
detail
str
status
int
class nemo_gym.server_runtime.base_environment_server._ToolOutcome(
status: int,
output: pydantic.JsonValue,
is_error: bool
)
Dataclass
is_error
bool
output
JsonValue
status
int
nemo_gym.server_runtime.base_environment_server._is_json(
value: pydantic.JsonValue
) -> bool
nemo_gym.server_runtime.base_environment_server.dependency_failure(
error: BaseException,
terminal: bool | None = None,
name_error_type: bool = False,
fields: typing.Any = {}

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.

nemo_gym.server_runtime.base_environment_server.handled_episode_failure(
terminal: bool,
evidence: dict[str, object] | None = None,
failure_kind: str | None = None,
event_fields: typing.Any = {}

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.

nemo_gym.server_runtime.base_environment_server.is_handled_episode_failure(
error: BaseException
) -> bool

Whether error is an environment failure built by handled_episode_failure.

nemo_gym.server_runtime.base_environment_server.is_retryable_dependency_error(
error: BaseException
) -> bool

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.

nemo_gym.server_runtime.base_environment_server.is_retryable_dependency_status(
status: int
) -> bool

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.

nemo_gym.server_runtime.base_environment_server.CleanupCallback = Callable[[], Awaitable[None]]
nemo_gym.server_runtime.base_environment_server.EPISODE_TOOL_SESSIONS = SessionKind(cookie_key=None, id_field=None, seed_path=None, close_path=None, coo...
nemo_gym.server_runtime.base_environment_server.EpisodeRequestT = TypeVar('EpisodeRequestT', bound=(BaseEpisodeRequest[Any]))
nemo_gym.server_runtime.base_environment_server.EpisodeResponseT = TypeVar('EpisodeResponseT', bound=(BaseEpisodeResponse[Any]))
nemo_gym.server_runtime.base_environment_server.LOGGER = logging.getLogger(__name__)
nemo_gym.server_runtime.base_environment_server.ToolTransport = Literal['direct_http', 'mcp']
nemo_gym.server_runtime.base_environment_server._ENVIRONMENT_CHECKPOINT_MODES = ('restart_only', 'exported')
nemo_gym.server_runtime.base_environment_server._MCP_PATH = '/mcp'
nemo_gym.server_runtime.base_environment_server._MCP_TOOL_NAME = re.compile('[A-Za-z0-9_-]+')
nemo_gym.server_runtime.base_environment_server._RETRYABLE_CLIENT_ERROR_STATUSES = frozenset({408, 425, 429})