nemo_gym.server_runtime.owned_sandboxes
nemo_gym.server_runtime.owned_sandboxes
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,
exportsnapshots 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 tosnapshot_attemptstimes, and every attempt is indexed. The sandbox keeps running; the episode continues in it after the resume. The owner callsexportonly while no command uses the sandbox, a borrower’s included. A participant’s prepare guarantees that for a resources server whosecheckpoint_verifyis"wait", the default. With"replay"its/verifyis admitted while a checkpoint is open, so an owner whose/verifyruns commands in the sandbox, or stops it, must keepcheckpoint_verifyat"wait". delete_snapshotsreceives 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 (seeSupportsSandboxSnapshot): on a provider that drops it, such a snapshot is never found.- After a crash,
restorerebuilds 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
Functions
Data
_UNRELEASED_CHECKPOINTS_WARNING
API
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.
Every snapshot in the index, by checkpoint: the ones no release has deleted yet. Reads the disk.
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.
The shared provider every tracked sandbox was created with.
The name prefix of every snapshot this server takes under its state_dir; None without one.
Whether key has a sandbox ready to use: not one still starting, nor one whose start failed.
Delete one snapshot and its index file; False if the delete failed, which keeps the file.
Delete what kept drops; returns how many snapshots could not be deleted.
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.
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.
Delete this server’s snapshots that the index never recorded, unless their checkpoint is kept.
Record the forks of a restore that will not install them, before anything stops them.
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.
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: Ifkeyhas 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 whosesandbox_provideris an inline block rather than a named one.
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.
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.
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.
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: Ifkeyalready has a sandbox, or one is starting, orspecsets nottl_s.
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.
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.
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.
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 fieldprovider_fieldor leaves it unset, orcheckpoint.state_diris relative.OSError: Ifcheckpoint.state_dircannot be written.
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.
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.
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.
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.
The name of attempt attempt to snapshot key’s sandbox for checkpoint_id.
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.
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.
Bases: BaseModel
How a server checkpoints the sandboxes it owns.
Bases: RuntimeError
A sandbox could not be exported or rebuilt.
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.
Bases: RuntimeError
A release could not delete every snapshot it dropped; failed counts those left for the next release.
One lock per key, which exists only while someone holds it or waits for it.
Bases: Exception
One snapshot attempt failed; error is what the export raises once no attempt is left.
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.
How many checkpoints have an indexed snapshot: the ones no release has dropped yet.
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.
Every indexed snapshot, by checkpoint; the folders of the checkpoints in excluding are not read.
checkpoint.state_dir when checkpointing is on and sets one; None otherwise. Refuses a relative path.
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.
name as one path component of the index, which it must be used as unchanged.
How long a cancelled caller waits for the provider to return a handle.
On cancellation, wait for a provider handle so the owner can stop it, then interrupt any file upload.
The typed rule that keeps what a block without one does today, for the deprecation warning.
Wait for the first completion or the deadline, including through repeated cancellation of the caller.
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 noserialize_handleandconnectto do it with.
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.
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.
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.
The short hash that stands for value in a snapshot name.
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.
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: Ifglobal_configdefines no host and port for a server, or a server listens on an address a sandbox cannot reach, such as a loopback.
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.
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.
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.
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.