Skip to navigation

nemo_gym.server_runtime.owned_sandboxes

View as MarkdownOpen in Claude

The sandboxes a server owns: their start, lending, stop and partial-rollout checkpoints.

Every sandbox has one owner, the server that starts it. The sandbox an attempt runs in belongs to its Environment Server, which lends it to the agent and to the Resources Server: they only borrow it, through the operate-scope access access gives, and never start, lend or stop it. A Resources Server owns a sandbox of its own only for a grader that runs code in an attempt that runs without one. Every server holds an OwnedSandboxes as SimpleServer.sandboxes to start, lend and stop the sandboxes it owns. Servers move onto it one family at a time, and onto borrowing the Environment Server’s sandbox: until then, a Resources Server that lends a sandbox from its seed, or an agent that starts its own because nothing was lent, owns that sandbox. It knows sandboxes by an opaque key, the owner’s session ID or a name within it such as session/grader, and nothing about the owner’s protocol.

A sandbox is also session state outside Gym’s process. An owner that checkpoints implements its participant’s checkpoint hooks (export_session_states and friends from nemo_gym.server_runtime._checkpoint) by delegating to the same instance.

The restore point of a sandbox is an explicit snapshot taken at commit: never the live sandbox, which keeps changing once the episode continues, and never a paused state, which the backend may consume on resume.

A sandbox and a snapshot are two objects outside Gym with two lifetimes.

A sandbox lives while its owner uses it. stop stops it when its session ends or is retired, and aclose stops every one left at the server’s shutdown; a restore stops the crashed process’s sandboxes it supersedes. What a crashed process leaves running ends with the lifetime the provider gives a sandbox, the spec’s ttl_s at the latest. A provider whose sandboxes would outlive a crashed process by that much should end them sooner, for example with a lease that only the creating process renews; the provider’s documentation says how. Forks made by a restore go through the same create and get the same lifetime.

A snapshot lives while a checkpoint the controller may restore names it. No episode event deletes one: a checkpoint taken before a rollout finished still restores that rollout. Instead the owner keeps an index on disk, an empty file <state_dir>/<server>/snapshots/<checkpoint id>/<snapshot id> per snapshot (under <state_dir>/<server>/providers/<provider field>/snapshots for a server’s other provider fields), and the controller’s release decides, through delete_snapshots:

  • At commit, export snapshots every live sandbox it is asked for. The moment the service returns a snapshot’s id, its file is written, before the snapshot is awaited; then the export waits until each snapshot is ready. A snapshot that fails or does not become ready in time is taken again, up to snapshot_attempts times, and every attempt is indexed. The sandbox keeps running; the episode continues in it after the resume. The owner calls export only while no command uses the sandbox, a borrower’s included. A participant’s prepare guarantees that for a resources server whose checkpoint_verify is "wait", the default. With "replay" its /verify is admitted while a checkpoint is open, so an owner whose /verify runs commands in the sandbox, or stops it, must keep checkpoint_verify at "wait".
  • delete_snapshots receives every checkpoint the controller may still restore and deletes the snapshots indexed under any other checkpoint, removing each file once the service confirms the snapshot is gone. It returns only once it has tried every delete, so the participant that awaits it admits no commit meanwhile and a later checkpoint is never among the ones it drops. The index outlives the process, so a release deletes what a crashed process created too, including the snapshots of a commit that never finished. A failed delete keeps its file, the call raises, and the next release tries again. A release also lists this server’s snapshots by name and deletes those of dropped checkpoints that never reached the index, such as one whose process died between the service’s reply and the file write. That sweep relies on the provider keeping the name a snapshot is taken with (see SupportsSandboxSnapshot): on a provider that drops it, such a snapshot is never found.
  • After a crash, restore rebuilds each sandbox in a fresh process from its snapshot (a fork), whatever happened to the live sandbox since. It validates every state first and installs all or nothing. The superseded sandboxes are stopped afterwards, best effort and off the restore’s critical path. A restore deletes no snapshot.

Nothing but a release deletes a snapshot: the owner cannot tell which checkpoints the controller may still restore, and it does not assume the provider expires snapshots. Under a controller that never releases, every commit therefore leaves one snapshot per live sandbox, for good, and export warns once the index holds more than a few checkpoints. A job that ended without a last release leaves the snapshots of the checkpoints it had not dropped. Either way they are found by their name prefix and deleted with the provider’s own tooling.

Snapshot names are ng-<state dir>-<server>-<checkpoint>-<key>-<attempt>, each part but the attempt a short hash, so names stay within provider limits and a listing can tell the state directory, the server and the checkpoint of each snapshot. For a server’s other provider fields, <server> hashes <server>/<provider field>, which no server name spells, since a server name has no /. <state dir> is read from <state_dir>/state_dir_id, written once by the first server to use the directory, so every server and every restart that shares a state_dir shares it too. It identifies the directory, not a collection run: it is unrelated to the run_id of a rollouts manifest or an exporter.

A state_dir belongs to one job and its restarts. Two jobs that run at the same time must not share one: they would share the index and the name prefix, each one’s release would treat the other’s checkpoints as dropped, and each would delete the other’s snapshots. Give every job its own, for example with the job’s id in the path. It must be on a filesystem every restart of the server reads, outside anything the controller deletes, and the same across restarts: the index is only useful to a process that can read it. The filesystem’s flock must hold across every node that runs the server, since it serializes releases across the processes that share the index.

Module Contents

Classes

NameDescription
OwnedSandboxesThe sandboxes one server owns on one provider, by key, and their checkpoint operations.
SandboxCheckpointConfigHow a server checkpoints the sandboxes it owns.
SandboxCheckpointErrorA sandbox could not be exported or rebuilt.
SandboxCheckpointStateWhat a restore needs to rebuild one sandbox as of a checkpoint: its snapshot and its spec.
SnapshotDeleteIncompleteErrorA release could not delete every snapshot it dropped; failed counts those left for the next release.
_Entry-
_KeyLock-
_KeyLocksOne lock per key, which exists only while someone holds it or waits for it.
_RetryableSnapshotErrorOne snapshot attempt failed; error is what the export raises once no attempt is left.
_SnapshotIndexThe snapshots one server created, by the checkpoint whose export created them, as empty files.

Functions

NameDescription
_configured_state_dircheckpoint.state_dir when checkpointing is on and sets one; None otherwise. Refuses a relative path.
_name_of-
_open_indexThe ID of state_dir and the snapshot index in it of server_name’s owner on provider_field (its
_optional_semaphore-
_path_componentname as one path component of the index, which it must be used as unchanged.
_settle_sHow long a cancelled caller waits for the provider to return a handle.
_start_to_the_endOn cancellation, wait for a provider handle so the owner can stop it, then interrupt any file upload.
_suggested_ruleThe typed rule that keeps what a block without one does today, for the deprecation warning.
_wait_through_cancellationWait for the first completion or the deadline, including through repeated cancellation of the caller.
check_lendingRefuse lending a sandbox of provider, a provider or its class, when no other process can connect to it.
check_network_ruleRefuse rule unless provider, a provider or its class, can apply it when it creates a sandbox.
check_providerThe checks of OwnedSandboxes.check_provider, against a provider or its class, which startup uses so
checkpoint_state_dircheckpoint.state_dir for a server that checkpoints sandboxes; None when checkpointing is off.
name_hashThe short hash that stands for value in a snapshot name.
read_state_dir_idThe ID of state_dir, written once by the first process to ask; every later process reads it.
rule_hostsThe hosts config’s network rule allows: its model and tool servers, read from global_config, then its
sandbox_blocksEvery SandboxConfig in a server’s config, at any depth, with its dotted path.
servers_sharing_hostsFor each host config’s rule allows for its model and tool servers, the other servers in global_config
spec_from_jsonRebuild a spec from a checkpoint record written by spec_to_json.
spec_to_jsonSerialize a spec for a checkpoint record, leaving out what a fork never reads.

Data

FORK_NOT_FOUND_BACKOFF_S

FORK_NOT_FOUND_RETRIES

LOGGER

_HASH_CHARS

_LOCK_POLL_S

_MARK_ATTEMPTS

_SNAPSHOT_NAME_SUFFIX

_SPEC_JSON

_STATE_DIR_ID_FILE

_STATE_VERSION

_UNRELEASED_CHECKPOINTS_WARNING

_UNRESTORED_PROVIDER_OPTIONS

__getattr__

API

class nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes(
state_dir: str | os.PathLike[str] | None,
server_name: str,
parallelism: int = 16,
snapshot_attempts: int = 3,
snapshot_retry_delay_s: float = 5.0,
provider_config_ref: str | None = None,
owns_provider: bool = False,
max_concurrent_starts: int | None = None,
max_concurrent_stops: int | None = None,
default_metadata: collections.abc.Mapping[str, str] | None = None,
global_config: collections.abc.Mapping[str, typing.Any] | None = None,
provider_field: str | None = None
)

The sandboxes one server owns on one provider, by key, and their checkpoint operations.

A server reaches its instance as self.sandboxes (see for_server); tests and tools may build one directly. state_dir and server_name place the snapshot index at <state_dir>/<server_name>/snapshots; see the module docstring for what state_dir must be. Without a state_dir, for a server whose checkpointing is off, sandboxes are tracked and stopped but cannot be exported. parallelism bounds concurrent snapshot submits and deletes against the backend; size it with the commit deadline. max_concurrent_starts bounds concurrent starts and forks, and max_concurrent_stops concurrent stops, each unbounded by default, so a server that seeds hundreds of episodes at once starts all of their sandboxes at once, and a stop never waits behind starts. A server sets both per provider with its block’s owner_concurrency. provider_config_ref names the provider’s config block, which access hands to a borrower. With owns_provider, aclose closes the provider too; otherwise the caller that made it closes it. provider_field names the server’s config field for a provider other than its sandbox_provider, which gets its own snapshot index and snapshot names.

_background
set[Task[Any]] = set()
_default_metadata
= dict(default_metadata or {})
_entries
dict[str, _Entry] = {}
_fork_stops
= asyncio.Lock()
_index
_SnapshotIndex | None = None
_key_locks
= _KeyLocks()
_none_pending
= asyncio.Event()
_on
Callable[[str], OwnedSandboxes] | None = None
_owner
_pending
set[str] = set()
_provider_close
= asyncio.Lock()
_provider_field
_semaphore
= asyncio.Semaphore(config.parallelism)
_server_name
= _path_component(server_name, 'server name')
_snapshot_attempts
= config.snapshot_attempts
_snapshot_retry_delay_s
= config.snapshot_retry_delay_s
_start_limit
= _optional_semaphore(concurrency.starts)
_state_dir_id
str | None = None
_stop_limit
= _optional_semaphore(concurrency.stops)
_unreleased_checked_for
str | None = None
_unstopped_forks
list[AsyncSandbox] = []
_warned_untyped_network
set[tuple[str, str]] = set()
indexed_snapshots
dict[str, list[str]]

Every snapshot in the index, by checkpoint: the ones no release has deleted yet. Reads the disk.

keys
list[str]

Every key with a tracked sandbox: also one still starting, and one whose start or stop failed and that the next stop or aclose stops again.

provider
SandboxProvider

The shared provider every tracked sandbox was created with.

snapshot_name_prefix
str | None

The name prefix of every snapshot this server takes under its state_dir; None without one.

nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes.__contains__(
key: object
) -> bool

Whether key has a sandbox ready to use: not one still starting, nor one whose start failed.

nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._delete_snapshot(
checkpoint_id: str | None,
snapshot_id: str
) -> bool
async

Delete one snapshot and its index file; False if the delete failed, which keeps the file.

nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._delete_snapshots_locked(
kept: frozenset[str]
) -> int
async

Delete what kept drops; returns how many snapshots could not be deleted.

nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._export_locked(
key: str,
checkpoint_id: str
) -> dict[str, pydantic.JsonValue] | None
async
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._export_one(
key: str,
checkpoint_id: str
) -> dict[str, pydantic.JsonValue] | None
async
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._fork(
key: str,
) -> None
async
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._give_back_keys(
keys: collections.abc.Iterable[str]
) -> None
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._provider_name() -> str
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._require_open() -> None
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._snapshot_once(
key: str,
checkpoint_id: str,
attempt: int
) -> str
async

Take one snapshot and wait until it is ready.

Only the submit holds the backend semaphore: a commit waits for every snapshot to become ready at once. A failed submit or snapshot raises _RetryableSnapshotError; failing to index one raises SandboxCheckpointError.

nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._spawn(
operation: typing.Any
) -> asyncio.Task[typing.Any]
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._start_slot() -> contextlib.AbstractAsyncContextManager[typing.Any]
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._stop_at_shutdown(
keys: list[str]
) -> None
async
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._stop_fork(
) -> None
async
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._stop_forks() -> None
async

Stop every tracked fork once; one leaves the list only when its stop succeeded.

A stop that fails is logged and its fork stays for the next call; one that is cancelled leaves it too.

nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._stop_key(
key: str
) -> None
async
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._stop_sandbox(
) -> None
async
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._stop_slot() -> contextlib.AbstractAsyncContextManager[typing.Any]
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._stop_superseded(
key: str,
) -> None
async
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._stop_superseded_all(
) -> None
async
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._sweep_unindexed(
kept: frozenset[str],
indexed: set[str]
) -> list[bool]
async

Delete this server’s snapshots that the index never recorded, unless their checkpoint is kept.

nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._take_keys(
keys: collections.abc.Iterable[str]
) -> None
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._track_unstopped(
created: collections.abc.Mapping[str, nemo_gym.sandbox.api.AsyncSandbox]
) -> None

Record the forks of a restore that will not install them, before anything stops them.

nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._warn_of_unreleased_checkpoints(
checkpoint_id: str
) -> None
async

Warn when the index keeps growing: nothing but a release deletes a snapshot.

A controller that releases keeps the index at the one or two checkpoints it may restore. One that never does leaves the snapshots of every commit on the provider for good, which only shows in the provider’s storage unless it is said here. The index is listed once per checkpoint, however many exports the owner makes for it: the index is on a filesystem every node reads.

nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes._warn_untyped_network(
) -> None
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes.access(
key: str,
workdir: str,
provider_config_ref: str | None = None
async

Access to key’s current sandbox for a borrower, such as an agent that runs a harness in it.

A restore rebuilds the sandbox from its snapshot under a new id, so a borrower that kept an older access must be given the new one after a restore. The access lets the borrower operate the sandbox but not destroy it, on a provider that scopes descriptors: the owner still has to checkpoint it and stops it itself. provider_config_ref defaults to the one this instance was built with.

Raises:

  • KeyError: If key has no running sandbox: none, one still starting, or one whose start failed and whose stop failed too.
  • ValueError: If neither this call nor the instance names the provider’s config block, as for a server whose sandbox_provider is an inline block rather than a named one.
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes.aclose() -> None
async

Stop every sandbox this instance owns; call it at the server’s shutdown.

That is every key’s sandbox and every fork a failed restore left running, after the background work has ended. The instance is closed first: create, add and restore raise RuntimeError from then on, and the ones already running are waited for, so a restore that installs its forks during the shutdown has them stopped here. A sandbox whose stop fails or takes longer than STOP_TIMEOUT_S is logged and stays tracked (its key stays in keys), the others are still stopped, and calling this again tries the rest again. An instance that owns its provider closes it once every sandbox is stopped; a close that fails or is cancelled is tried again by the next call, and one that succeeded is not repeated. Snapshots are not touched: the controller may still restore from them, and only its release deletes them.

nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes.add(
key: str,
) -> None

Track a sandbox the owner started itself; spec is what a restore re-creates its fork from.

The default user and working directory are the exception: an export reads them from the sandbox, so a fork runs commands as the sandbox did when it was exported, and takes only the rest of its spec from spec. The sandbox must run on this instance’s provider without owning it (AsyncSandbox(owned.provider, spec, owns_provider=False)): the provider is shared by every sandbox, and a sandbox that owned it would close it for all of them when stopped.

nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes.check_provider(
configs: collections.abc.Iterable[nemo_gym.sandbox.config.SandboxConfig] = (),
lends: bool = False
) -> None

Refuse what this provider cannot do for its owner, at startup where the owner’s config shows the need.

Each block’s network rule is checked on its own, and lending (lends) needs a provider that reconnects. Exporting is checked at the first export of a key, and lending again at the first access, since only the owner’s code decides those.

Raises:

  • ValueError: Naming the first need the provider cannot meet.
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes.create(
key: str,
async

Start a sandbox for key on the shared provider and track it.

The key is taken from the first moment, so a second create for it is refused while the first is starting. A create of a key that an export is snapshotting waits for that export; creates of other keys do not.

The sandbox is tracked before it starts, but get, in and access show it only once its start succeeded. If the caller cancels before the provider returns a handle, the owner waits up to ready_timeout_s (zero when unset) plus STOP_TIMEOUT_S for the handle. Once it has a handle, the owner interrupts any file upload and stops the sandbox, shielded from cancellation. If the provider never returns a handle, cleanup depends on its support for ttl_s. If the stop fails, the key stays tracked for the next stop or aclose and stays unavailable to borrowers. The start’s error is raised with the stop’s as its context.

Raises:

  • ValueError: If key already has a sandbox, or one is starting, or spec sets no ttl_s.
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes.delete_snapshots(
kept: frozenset[str]
) -> None
async

Delete the snapshots of every checkpoint outside kept; returns once every delete was tried.

This is what an owner’s delete_external_state hook calls for the controller’s release. It stops no sandbox. kept is every checkpoint the controller may still restore, not the ones to delete; an empty set deletes every snapshot. The checkpoints to drop are read from the index here, so call it only while no export runs, as a participant does by admitting a release only when idle and awaiting it before it admits a commit. The deletion holds the index’s file lock, so releases of other processes that share the index wait for it. It deletes the indexed snapshots of dropped checkpoints, then lists this server’s snapshots by name and deletes those of dropped checkpoints the index never recorded. A snapshot the service deleted, or confirms gone, leaves the index; one whose delete fails stays.

Raises SnapshotDeleteIncompleteError if any delete failed, once every delete was tried, and RuntimeError if the index cannot be locked; the provider’s error if the listing fails. Whatever a failed or cancelled call left is still indexed, and the next release deletes it.

nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes.discard(
keys: collections.abc.Iterable[str]
) -> None
async

Give up the sandboxes of keys and stop them; for the forks of a restore its owner could not install.

Unlike stop, every key can be restored again at once, whether or not the stops succeed. A sandbox whose stop fails or takes longer than STOP_TIMEOUT_S is logged and joins the forks that settle, the next restore and aclose stop again. A key without a sandbox is skipped. A create, export, stop or restore of a key that is running is let finish first, so a sandbox still starting is not left running untracked.

nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes.export(
keys: collections.abc.Iterable[str],
checkpoint_id: str
) -> dict[str, dict[str, pydantic.JsonValue] | None]
async

Snapshot each key’s sandbox for checkpoint checkpoint_id and return its checkpoint state.

A key without a live sandbox, never started or already stopped (for example after the owner captured what it grades), maps to None: a restore then gives it no sandbox. That tells an owner which of its keys have nothing to restore, but it is not what the export_session_states hook returns for such a session: the hook leaves out a session the server no longer holds. An owner keyed by session ID must drop the None entries before it returns this result from the hook, or a restore brings those sessions back without a sandbox. Each snapshot is indexed under checkpoint_id as soon as it exists, and every snapshot is awaited before the result or the first failure is returned. Raises SandboxCheckpointError if a sandbox cannot be snapshotted in snapshot_attempts attempts, or a snapshot cannot be indexed, which fails the commit. Every sandbox keeps running, and the snapshots already taken are deleted by a release that does not keep checkpoint_id.

provider_field: str,
global_config: collections.abc.Mapping[str, typing.Any],
on: typing.Callable[[str], nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes] | None = None
classmethod

The instance a server holds for the provider its config names in provider_field.

config is the server’s config and global_config the merged global config, which resolves a named provider and checkpoint.state_dir. An instance for a field other than sandbox_provider gets its own snapshot index and snapshot names, kept apart from every other server’s and field’s. Without a checkpoint.state_dir the instance has no snapshot index: it creates, lends and stops sandboxes, and only export refuses, so a server that never exports, such as an agent, needs none. The instance owns the provider it creates and closes it in aclose. on gives the server’s instance for another field, which on calls.

Raises:

  • ValueError: If the config has no field provider_field or leaves it unset, or checkpoint.state_dir is relative.
  • OSError: If checkpoint.state_dir cannot be written.
classmethod

Build an instance from a server’s SandboxCheckpointConfig; the rest as in the constructor.

parallelism also bounds its starts, forks and stops, as it did before they had limits of their own, since such a server has no owner_concurrency to set them.

nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes.get(
key: str

key’s sandbox if it is ready to use, else None; after a restore it is the fork, under a new id.

A sandbox still starting, or one whose start failed and whose stop failed too, is not returned; keys still lists its key.

The same server’s instance for the provider its config names in provider_field, created on first use.

Raises:

  • RuntimeError: If no server holds this instance.
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes.restore(
states: collections.abc.Mapping[str, pydantic.JsonValue | None]
) -> None
async

Rebuild every key’s sandbox from its snapshot, all or nothing; a None state rebuilds nothing.

Every state is validated before the backend is touched. If any sandbox cannot be rebuilt, the forks this call created are stopped and SandboxCheckpointError names the key; if the call is cancelled, they are stopped in the background, which settle waits for. A fork whose stop fails or is cancelled stays tracked, and settle, the next restore and aclose stop it again. Once the forks are in place the crashed process’s sandboxes are stopped in the background, best effort; a failure there is logged and the sandbox runs out its lifetime.

nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes.settle() -> None
async

Wait for the background work, then stop again the forks an earlier restore could not stop.

The background work is the superseded sandboxes and forks a restore stops and the failed snapshots an export deletes; cancelling the wait leaves that work running. Each fork whose stop failed is then tried once more, so a process that never restores again still stops them; one that fails again is logged and stays for the next call.

nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes.snapshot_name(
checkpoint_id: str,
key: str,
attempt: int
) -> str

The name of attempt attempt to snapshot key’s sandbox for checkpoint_id.

nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes.spec(
image: str | None,
workdir: str | None,
metadata: collections.abc.Mapping[str, str] | None = None,
files: collections.abc.Mapping[str, str | bytes] | None = None

The spec of a sandbox started from config, with its network rule in the provider’s own format.

model_server and tool_servers become the hosts those servers are reachable at, which the rule allows together with allowed_hosts. metadata overrides the provider block’s and the config’s metadata. A block without a rule keeps today’s behavior, the provider’s default or its provider_options, and logs a deprecation warning that names the rule to switch to, once per config class and rule. A subclass’s own network setting, which is not a typed rule, is left to its server.

Raises:

  • ValueError: If the provider cannot apply the rule, or a server’s URL is one a sandbox cannot reach.
nemo_gym.server_runtime.owned_sandboxes.OwnedSandboxes.stop(
key: str
) -> None
async

Stop and forget key’s sandbox; a no-op for a key without one, so a retire may repeat it.

It first waits for a create, an export or a restore of the same key to finish, and stops the fork a restore installed. The whole stop is shielded from the caller’s cancellation, so a client that disconnects cannot leave the sandbox running. The wait for the key’s lock is bounded by STOP_TIMEOUT_S, and so is the provider’s stop once it has a stop slot; the wait for a slot has no limit of its own, since every stop ahead holds its slot for at most STOP_TIMEOUT_S. If the stop fails, or times out and raises TimeoutError, the key stays tracked, so a retried retire stops it again. The sandbox’s snapshots stay: a checkpoint the controller may still restore can name them, and only a release knows which.

class nemo_gym.server_runtime.owned_sandboxes.SandboxCheckpointConfig()

Bases: BaseModel

How a server checkpoints the sandboxes it owns.

model_config
= ConfigDict(extra='forbid')
parallelism
int
snapshot_attempts
int
snapshot_retry_delay_s
float
class nemo_gym.server_runtime.owned_sandboxes.SandboxCheckpointError(
key: str,
detail: str
)

Bases: RuntimeError

A sandbox could not be exported or rebuilt.

class nemo_gym.server_runtime.owned_sandboxes.SandboxCheckpointState()

Bases: BaseModel

What a restore needs to rebuild one sandbox as of a checkpoint: its snapshot and its spec.

snapshot_id is the snapshot a restore forks. descriptor names the sandbox the snapshot was taken from, so a restore can stop it; it is never restored in place. snapshot_ready_ts is the Unix time the snapshot became ready. version is the version of this record’s format; a restore refuses one it does not know.

spec is written as the fork needs it, which includes the sandbox environment (env) and each sidecar’s env and provider_options (registry credentials too) in plain text: a checkpoint directory holds whatever the sandboxes were started with.

keeps_processes says the provider’s snapshot kept the sandbox’s running processes as well as its files, so the fork starts with them running ("processes" in the provider’s capabilities.snapshot_keeps). States written before the field existed read as files only.

descriptor
dict[str, JsonValue]
keeps_processes
bool = False
model_config
= ConfigDict(extra='forbid')
provider_name
str
snapshot_id
str
snapshot_ready_ts
float
spec
dict[str, JsonValue]
version
Literal[1] = _STATE_VERSION
class nemo_gym.server_runtime.owned_sandboxes.SnapshotDeleteIncompleteError(
failed: int,
kept: frozenset[str]
)

Bases: RuntimeError

A release could not delete every snapshot it dropped; failed counts those left for the next release.

class nemo_gym.server_runtime.owned_sandboxes._Entry(
ready: bool = True
)
Dataclass
ready
bool = True
sandbox
AsyncSandbox
spec
SandboxSpec
class nemo_gym.server_runtime.owned_sandboxes._KeyLock(
lock: asyncio.Lock = asyncio.Lock(),
users: int = 0
)
Dataclass
lock
Lock = dataclasses.field(default_factory=(asyncio.Lock))
users
int = 0
class nemo_gym.server_runtime.owned_sandboxes._KeyLocks()

One lock per key, which exists only while someone holds it or waits for it.

_locks
dict[str, _KeyLock] = {}
nemo_gym.server_runtime.owned_sandboxes._KeyLocks.__len__() -> int
nemo_gym.server_runtime.owned_sandboxes._KeyLocks.locked(
key: str
) -> collections.abc.AsyncIterator[None]
async
class nemo_gym.server_runtime.owned_sandboxes._RetryableSnapshotError(
snapshot_id: str | None
)
Exception

Bases: Exception

One snapshot attempt failed; error is what the export raises once no attempt is left.

class nemo_gym.server_runtime.owned_sandboxes._SnapshotIndex(
root: pathlib.Path
)

The snapshots one server created, by the checkpoint whose export created them, as empty files.

<root>/<checkpoint id>/<snapshot id> exists from the moment the service returned the snapshot’s id until the service confirmed it deleted. Marks and unmarks are one or two filesystem calls, so several processes, such as a crashed process’s replacement or another worker, can mark without locks; releases hold <root>.lock, so two never delete the same snapshots at once.

lock_path
= root.with_name(root.name + '.lock')
nemo_gym.server_runtime.owned_sandboxes._SnapshotIndex.checkpoint_count() -> int

How many checkpoints have an indexed snapshot: the ones no release has dropped yet.

nemo_gym.server_runtime.owned_sandboxes._SnapshotIndex.locked() -> collections.abc.AsyncIterator[None]
async

Hold the release lock for the block.

The lock is tried without blocking and tried again after a pause while another release holds it, so the event loop keeps running and a cancelled wait leaves nothing behind: closing the descriptor gives the lock back wherever the block ends. Raises RuntimeError naming the lock file if the filesystem cannot lock.

nemo_gym.server_runtime.owned_sandboxes._SnapshotIndex.mark(
checkpoint_id: str,
snapshot_id: str
) -> None
nemo_gym.server_runtime.owned_sandboxes._SnapshotIndex.remove_if_empty(
checkpoint_id: str
) -> None
nemo_gym.server_runtime.owned_sandboxes._SnapshotIndex.snapshot_ids(
excluding: frozenset[str] = frozenset()
) -> dict[str, list[str]]

Every indexed snapshot, by checkpoint; the folders of the checkpoints in excluding are not read.

nemo_gym.server_runtime.owned_sandboxes._SnapshotIndex.unmark(
checkpoint_id: str,
snapshot_id: str
) -> None
nemo_gym.server_runtime.owned_sandboxes._configured_state_dir(
global_config: typing.Any
) -> pathlib.Path | None

checkpoint.state_dir when checkpointing is on and sets one; None otherwise. Refuses a relative path.

nemo_gym.server_runtime.owned_sandboxes._name_of(
provider: object
) -> str
nemo_gym.server_runtime.owned_sandboxes._open_index(
state_dir: pathlib.Path,
server_name: str,
provider_field: str | None

The ID of state_dir and the snapshot index in it of server_name’s owner on provider_field (its sandbox_provider for None), whose directory this creates if needed.

nemo_gym.server_runtime.owned_sandboxes._optional_semaphore(
limit: int | None
) -> asyncio.Semaphore | None
nemo_gym.server_runtime.owned_sandboxes._path_component(
name: str,
what: str
) -> str

name as one path component of the index, which it must be used as unchanged.

nemo_gym.server_runtime.owned_sandboxes._settle_s(
) -> float

How long a cancelled caller waits for the provider to return a handle.

nemo_gym.server_runtime.owned_sandboxes._start_to_the_end(
settle_s: float,
snapshot_id: str | None = None
) -> None
async

On cancellation, wait for a provider handle so the owner can stop it, then interrupt any file upload.

nemo_gym.server_runtime.owned_sandboxes._suggested_rule(
) -> str

The typed rule that keeps what a block without one does today, for the deprecation warning.

nemo_gym.server_runtime.owned_sandboxes._wait_through_cancellation(
futures: asyncio.Future[typing.Any] = (),
timeout_s: float
) -> None
async

Wait for the first completion or the deadline, including through repeated cancellation of the caller.

nemo_gym.server_runtime.owned_sandboxes.check_lending(
provider: object
) -> None

Refuse lending a sandbox of provider, a provider or its class, when no other process can connect to it.

A provider that reconnects only on the same host passes: whether the borrower runs there shows at its first connect.

Raises:

  • ValueError: If the provider never reconnects, or has no serialize_handle and connect to do it with.
nemo_gym.server_runtime.owned_sandboxes.check_network_rule(
provider: object,
provider_config: collections.abc.Mapping[str, typing.Any] | None = None
) -> None

Refuse rule unless provider, a provider or its class, can apply it when it creates a sandbox.

Raises:

  • ValueError: If it cannot, so no sandbox starts with open egress in place of the rule.
nemo_gym.server_runtime.owned_sandboxes.check_provider(
provider: object,
configs: collections.abc.Iterable[nemo_gym.sandbox.config.SandboxConfig] = (),
lends: bool = False,
provider_config: collections.abc.Mapping[str, typing.Any] | None = None
) -> None

The checks of OwnedSandboxes.check_provider, against a provider or its class, which startup uses so that a server checks its provider without creating it.

nemo_gym.server_runtime.owned_sandboxes.checkpoint_state_dir(
global_config: typing.Any
) -> pathlib.Path | None

checkpoint.state_dir for a server that checkpoints sandboxes; None when checkpointing is off.

Raises ValueError when checkpointing is on without it: the server could not delete the snapshots its checkpoints take, so it refuses to start rather than leak them. It must be absolute: a relative path would name a different directory for each server and each restart started from another working directory.

nemo_gym.server_runtime.owned_sandboxes.name_hash(
value: str
) -> str

The short hash that stands for value in a snapshot name.

nemo_gym.server_runtime.owned_sandboxes.read_state_dir_id(
state_dir: pathlib.Path
) -> str

The ID of state_dir, written once by the first process to ask; every later process reads it.

It identifies the directory, and so every server, restart and job that uses it; it is not the run_id of a rollouts manifest or an exporter.

nemo_gym.server_runtime.owned_sandboxes.rule_hosts(
global_config: collections.abc.Mapping[str, typing.Any]
) -> list[str]

The hosts config’s network rule allows: its model and tool servers, read from global_config, then its allowed_hosts. Nothing is connected to.

Raises:

  • ValueError: If global_config defines no host and port for a server, or a server listens on an address a sandbox cannot reach, such as a loopback.
nemo_gym.server_runtime.owned_sandboxes.sandbox_blocks(
value: typing.Any,
path: str = 'config'
) -> collections.abc.Iterator[tuple[str, nemo_gym.sandbox.config.SandboxConfig]]

Every SandboxConfig in a server’s config, at any depth, with its dotted path.

Only models, dicts, lists and tuples are walked: an OmegaConf node is not, since reading it can resolve an interpolation the server never reads.

nemo_gym.server_runtime.owned_sandboxes.servers_sharing_hosts(
global_config: collections.abc.Mapping[str, typing.Any]
) -> dict[str, list[str]]

For each host config’s rule allows for its model and tool servers, the other servers in global_config that listen on that host too: a rule allows a whole host, so a sandbox reaches them as well.

nemo_gym.server_runtime.owned_sandboxes.spec_from_json(
data: collections.abc.Mapping[str, typing.Any]

Rebuild a spec from a checkpoint record written by spec_to_json.

Raises TypeError for a key the current SandboxSpec does not know and ValueError for an invalid resources or ports value; a restore reports either as an invalid checkpoint state.

nemo_gym.server_runtime.owned_sandboxes.spec_to_json(
) -> dict[str, pydantic.JsonValue]

Serialize a spec for a checkpoint record, leaving out what a fork never reads.

Files were uploaded at creation and the snapshot has them; the snapshot also replaces the image, so the image and its registry credentials (provider_options["image_auth"]) are dropped too. Sidecars are kept whole, their image_auth included: the snapshot is of the sandbox alone, and a fork starts each sidecar from its image again.

nemo_gym.server_runtime.owned_sandboxes.FORK_NOT_FOUND_BACKOFF_S = 5.0
nemo_gym.server_runtime.owned_sandboxes.FORK_NOT_FOUND_RETRIES = 4
nemo_gym.server_runtime.owned_sandboxes.LOGGER = logging.getLogger(__name__)
nemo_gym.server_runtime.owned_sandboxes._HASH_CHARS = 8
nemo_gym.server_runtime.owned_sandboxes._LOCK_POLL_S = 0.1
nemo_gym.server_runtime.owned_sandboxes._MARK_ATTEMPTS = 10
nemo_gym.server_runtime.owned_sandboxes._SNAPSHOT_NAME_SUFFIX = re.compile(f'([0-9a-f]{{_HASH_CHARS}})-[0-9a-f]{{_HASH_CHARS}}-[1-9][0-9]*')
nemo_gym.server_runtime.owned_sandboxes._SPEC_JSON = TypeAdapter(dict[str, JsonValue])
nemo_gym.server_runtime.owned_sandboxes._STATE_DIR_ID_FILE = 'state_dir_id'
nemo_gym.server_runtime.owned_sandboxes._STATE_VERSION = 1
nemo_gym.server_runtime.owned_sandboxes._UNRELEASED_CHECKPOINTS_WARNING = 5
nemo_gym.server_runtime.owned_sandboxes._UNRESTORED_PROVIDER_OPTIONS = ('image_auth', 'snapshot_id')
nemo_gym.server_runtime.owned_sandboxes.__getattr__ = moved_names_getattr(__name__)