Repository navigation
feat(environment): start and lend a sandbox for each single-agent-turn attempt - #6700
Conversation
A client that disconnects cancels its request, and every later await in it. An unshielded stop in the request's cleanup then raises before the provider closes the sandbox, which runs on until its ttl_s. nemo_gym.sandbox.stop_sandbox(), in the sandbox package's utils, shields the stop from that cancellation and bounds it in time, so a hung provider cannot hold the request either. A timed-out stop raises TimeoutError, which owners treat like any other failed stop. It also accepts a Compose group, which harbor owns. LentSandboxes, the swebench sandbox session base and deepswe_external1 each had a copy of this stop; they now use the shared one. Signed-off-by: Ananth Subramaniam <[email protected]>
Every sandbox has one owner, the server that starts it, but each server
family owns its sandboxes through its own design. Gym already has a class
that tracks a server's sandboxes by key, stops them, lends them with operate
scope and snapshots them for checkpoints: SandboxSessionCheckpointer, which
no server uses yet.
It becomes the public nemo_gym.server_runtime.OwnedSandboxes, in its own
module (nemo_gym/server_runtime/owned_sandboxes.py) since it is no longer
checkpoint-only, and every SimpleServer holds one as self.sandboxes:
- created on first use from the server's sandbox_provider and
checkpoint.state_dir, so a server without sandboxes builds nothing
- self.sandboxes.on("<field>") gives the instance for a second provider
field, with its own server name for the snapshot index
- run_webserver wraps the app's lifespan so the shutdown stops what every
instance still owns, after the server's own shutdown code
- access() lends through the provider block the instance was built from
- the instance owns the provider it creates and closes it once every
sandbox is stopped; it reads the config the server was started with
- the shutdown sweep runs after the server's own shutdown, is bounded
(150 s in all), refuses to build new instances once it began, and is
documented next to server_shutdown_timeout_seconds
The glossary gains "sandbox owner" and "lend / borrow", and its existing
"Owner" (the worker that holds a session) points away from them.
The class is renamed directly without an alias: it merged on 2026-11-16 and
is in no release.
Signed-off-by: Ananth Subramaniam <[email protected]>
OwnedSandboxes becomes the one path for every sandbox start and stop, so it takes on the jobs that servers copied into their own session code: - One stop: stop() is shielded from the caller's cancellation and bounded by STOP_TIMEOUT_S from the moment it is called, its waits for the key's lock and for a stop slot included, so a client that disconnects cannot leave the sandbox running and nothing can hold the stop forever. A stop that fails or times out keeps the key, as before. - Tracking before start: create() tracks the sandbox before it starts. A start that fails or is cancelled after the provider returned the sandbox is stopped, shielded. If that stop fails too, the key stays tracked for the next stop or aclose(), an export leaves the half-started sandbox out, and create() raises the start's error with the stop's as its context. AsyncSandbox.start now keeps the start's error the same way when its own rollback stop fails. A start cancelled before the provider returned the sandbox leaves nothing to stop; ttl_s reclaims it. - Their own start and stop limits: parallelism (16 by default) bounded creates, stops, snapshots and deletes alike, which would let a server seeding 512 episodes start only 16 sandboxes at a time. Starts and forks now take max_concurrent_starts and stops take max_concurrent_stops, both unbounded by default and set per provider with the block's owner_concurrency, so a stop never waits behind starts. parallelism bounds only snapshot submits and deletes. - Exclusion per key: a create, a stop, an export and a restore of one key hold that key's lock. An export snapshots a sandbox only once its start finished, a stop waits for the export or restore of its key and then stops what is there, and other keys go on. A restore takes its keys' locks in sorted order. A key's lock exists only while someone holds or waits for it. Signed-off-by: Ananth Subramaniam <[email protected]>
Each sandbox's egress rule was set five different ways, and about 20 servers set none. A typed rule in its config block makes every sandbox's egress visible, and the owner applies it when the sandbox starts. - SandboxConfig gains network (inherit, no_network, model_only, model_and_tools, hosts_only), model_server, tool_servers and allowed_hosts, checked for consistency at load. A block that sets network and also a provider's own network option is refused. A subclass's own network setting, such as partner_if's tool sandbox, is left alone. - SandboxConfig.spec() takes network_options, the provider options that apply the rule, and refuses a restricted rule without them: only the owner builds them, so a block that asks for restricted egress never starts a sandbox with the provider's default egress. network_options replaces Gym#6179's OpenSandbox-only network_policy parameter, which is in no release; whichever of the two lands second drops network_policy. - Each provider class declares a frozen SandboxCapabilities: what its snapshots keep, the network rules it can apply, whether it reconnects always, only on the same host or never, and whether it closes by label. OpenSandbox applies every rule through its egress policy, built by the same helper as restricted_network_policy. Docker applies no_network as --network none, or leaves it to a provider block that already sets it. - OwnedSandboxes.spec() turns model_server and tool_servers into reachable hosts, read from the config the server was started with, asks the provider for its options for the rule and builds the spec. A block without a rule keeps today's behavior and logs one deprecation warning naming the rule that keeps it. - check_provider() refuses a rule the provider cannot apply, and lending on a provider that never reconnects. SimpleServer runs it at startup from the provider's class, for servers that set lends_sandboxes and, when sandbox_provider is the only provider field, for every typed block, whose model and tool servers it also resolves to hosts from the config, without connecting to them; access() refuses lending again at first use. - The sandbox docs describe the rule. Signed-off-by: Ananth Subramaniam <[email protected]>
An agent that is lent a sandbox connects to it through its own copy of the borrow-or-own branch, and gets the sandbox to stop as easily as to run in. Only an operate-scope descriptor kept it from stopping a sandbox the environment still grades in, and no provider enforces that. borrow(access) in nemo_gym.agents.utils is the one way to use a lent sandbox. It resolves the provider, connects with the descriptor, and returns a BorrowedSandbox: - commands and terminal sessions run as the access's user in its workdir, with its env under each call's own - stop, start, pause, resume and snapshot raise BorrowedSandboxError: they are the owner's - serialize() gives only operate scope, and access() passes the lent access on for a harness that borrows the sandbox again in a subprocess - disconnect(), and leaving an async-with block, release the client shielded from cancellation and bounded, as does a failed connect AgentSandboxConfig types the sandbox an agent starts for itself when nothing is lent, with the keys agent recipes set today (image, workdir, files, entrypoint, user, ports and derive_cpu_env, off by default as in most agents) on top of SandboxConfig and its network rule. Other SandboxSpec keys a recipe may set, such as sidecars, are refused; each agent that moves onto the config warns about them for one release first. No checked-in agent, benchmark or environment recipe sets one today. No agent moves onto them here: that is each agent family's own change, and the harness guide changes with the first one. Signed-off-by: Ananth Subramaniam <[email protected]>
Resolve against main: - Drop this branch's earlier copy of the shielded stop (stop_sandbox() in nemo_gym.sandbox.utils and its test): #6410 merged a different version that puts the shield and limit in AsyncSandbox.stop(timeout_s=...). The sandbox package, LentSandboxes, the swebench session base and deepswe_external1 take main's code; OwnedSandboxes stops through AsyncSandbox.stop. - #5266 exports the checkpointer under its old name: its server, conformance helper and test move to OwnedSandboxes in owned_sandboxes, and the public API serves SandboxCheckpointConfig, SandboxCheckpointError and checkpoint_state_dir from there. No release shipped the old name. - The glossary keeps main's sandbox lease and capabilities rows beside the owner and lend/borrow rows. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
Brings in origin/main through the parent. Keeps this branch's stop: shielded and bounded as a whole, the wait for a stop slot included. It passes STOP_TIMEOUT_S to AsyncSandbox.stop, whose own shield (#6410) would otherwise hold a stop for its 120 s default past a shorter configured limit. The superseded-sandbox stop does the same. STOP_TIMEOUT_S now comes from nemo_gym.sandbox.api. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
…xes-network Brings in origin/main through the parents. Main added SandboxCapabilities with snapshot_keeps and provider_capabilities() in #5410; this branch added its own SandboxCapabilities. They become one class: main's, with this branch's network_rules, reconnect and close_by_label, its NetworkRule and Reconnect defined before it. E2B and OpenSandbox declare one capabilities each (E2B keeps main's files-and-processes snapshots). The owner's private _capabilities() copy gives way to provider_capabilities(). Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
Brings in origin/main through the parents; the glossary keeps main's sandbox lease and capabilities rows beside this branch's lend/borrow row. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
…n attempt When the Resources Server lends no sandbox, single_agent_turn can now start one per attempt through its OwnedSandboxes, with a typed network rule such as model_only. It lends the sandbox to the agent in the seed, lends the same sandbox to /verify as ng_sandbox_access after the agent closes, and stops it in the episode's cleanup on every path. A sandbox that cannot start fails the attempt as a retryable infrastructure failure before the agent runs; nothing falls back to the host. The feature is opt-in through sandbox_provider and sandbox_config, so existing configs behave as before. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
OwnedSandboxes.for_server created the provider before it read checkpoint.state_dir, so a refused config (checkpointing on without a state_dir) left a provider nobody closes, and every later self.sandboxes built another. The provider block and state_dir are now resolved first. An owner on the local provider, which runs commands as host processes, logs a warning. The self.sandboxes docstring and the glossary say what is true today: no server owns its sandboxes through it yet, it is used from the event loop, and a borrower is an agent or a Resources Server grading in the sandbox. The test imports names from their defining modules. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
create() let a cancellation cut the provider's start short and relied on ttl_s to reclaim what the provider had made. Not every provider applies ttl_s: on Enroot a create cancelled half a second in left its container on the node with nothing tracking it (seen in a lifecycle smoke). The start now runs to its end, shielded and bounded by STOP_TIMEOUT_S, so the create's rollback has a handle to stop; only a start still running after that is cut short. A main test of a stop that waits for its turn held the snapshot semaphore, which stops no longer take since they got their own limit; it now holds the stop limit. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
- stop() took STOP_TIMEOUT_S for its key's lock, again for a stop slot, and AsyncSandbox.stop, which shields itself from enclosing deadlines since #6410, took a third: up to three limits in all. One deadline now covers the whole stop, and the provider's stop gets only the time that is left. - create() refuses a spec without ttl_s: the shutdown sweep is bounded and a crash runs none, so ttl_s is what ends a sandbox its owner never stops. - access() lends only a running sandbox. A key is tracked from before its start, so a key still starting, or one whose start and stop both failed, raised a RuntimeError from the sandbox, or lent a broken one. - An instance built with from_config, as swebench's checkpoint server builds it, keeps parallelism as the bound of its starts, forks and stops. They bounded them before they got limits of their own, and such a server has no owner_concurrency to set. swebench's close test holds the stop limit, which stops take now, instead of the snapshot semaphore. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
… after close - A stop waiting for a stop slot no longer counts that wait against STOP_TIMEOUT_S. Every stop ahead holds its slot for at most that long, and cutting queued stops short under load (1000 sandboxes, 16 slots) left most of them running until their ttl_s. The wait for the key's lock and the provider's stop are each bounded by STOP_TIMEOUT_S, without the extra nested limits the previous commit removed. - A create queued for a start slot when aclose() began now raises instead of starting a sandbox after the shutdown sweep has begun. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
…xes-network Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
…ry entry for the rule - critpt's agentic execution server built its SandboxSpec from the whole SandboxConfig dump, which now also holds the network rule's fields, so its startup failed with an unexpected keyword. It takes only the fields a SandboxSpec has, and refuses a typed rule it would not apply. - ECS reconnects through the owner's tunnel on the same host, so it declares same_host, not never; Daytona's connect takes a bare id, so it declares never; bwrap, added on main after this branch, declares same_host. Lending also refuses a provider with no serialize_handle and connect, whatever it declares. A test keeps every built-in provider's reconnect in step with its methods, and the design table lists every built-in provider. - close_by_label is dropped: no provider sets it and nothing reads it. - The startup check runs before the dry-run return, so a dry run reports a rule the provider cannot apply. It imports from the defining modules. - The glossary gains "Network rule" (naming the network_access fields it replaces) and the capabilities entry names network_rules and reconnect. The sandbox page says which refusals happen at startup and which at the first spec(), and that a rule allows a server's whole host. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
…egress at startup - Declare the verify field once, as BaseVerifyRequest.sandbox_access (wire name ng_sandbox_access, excluded from dumps), and drop it from the verify reply, so a verifier that echoes its request never stores it. - Refuse at startup a network rule that blocks the tools an episode grants, and build the provider at startup, so a bad block fails startup. - Stop an attempt sandbox only where this server built a provider, so an episode whose Resources Server lent the sandbox builds none in cleanup. - A sandbox that cannot be lent to the verifier is a retryable infrastructure failure. - Require ttl_s to exceed the episode and cleanup timeouts. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
…w from server_runtime - BorrowedSandbox.stop and disconnect dropped the timeout_s keyword that AsyncSandbox.stop and disconnect take since #6410. SandboxSession, which every sandboxed agent closes through, releases a sandbox it does not own with disconnect(timeout_s=...), so a borrowed sandbox raised TypeError at close and its client was never released. stop(timeout_s=...) now refuses like stop(), and the disconnect override is gone: AsyncSandbox.disconnect is shielded and bounded itself, and the override's own 60 s limit could not cut the inner shielded one short anyway. - borrow(), BorrowedSandbox and BorrowedSandboxError move to nemo_gym.server_runtime, beside OwnedSandboxes, and its public API serves them: a Resources Server grading in a lent sandbox borrows it too, and server_runtime cannot import nemo_gym.agents. AgentSandboxConfig joins nemo_gym.agents' public API. - A failed connect's client close no longer replaces the connect's error or a cancellation. access() passes on the access the sandbox was lent with instead of serializing it again. A command that keeps background services runs as the lent user: that provider call reads no sandbox default. - Docstrings: a borrower installs its runtime as the lent user unless a command names another; the repository check is planned, not in place; the OpenCode and Pi sandboxed agents turn CPU caps on in code. - Tests import from the defining modules; the AgentSandboxConfig tests sit beside their module in tests/unit_tests/agents/. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
Running it before the dry-run return broke servers whose config a test mocks (test_dry_run_skips_webserver_spinup); the check stays where the PR put it. critpt's new test stubs the execution sessions instead of building a Docker provider, so it runs on hosts without Docker. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
|
/ok to test b0bf5a9 |
|
Smoke for this PR's Environment Server side (attempt sandbox started, lent to the agent and to |
…attempt-sandbox Signed-off-by: yaoyu-33 <[email protected]> # Conflicts: # fern/versions/latest/pages/about/concepts/key-terminology.mdx
Signed-off-by: yaoyu-33 <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
/ok to test 2804dda |
hemildesai
left a comment
There was a problem hiding this comment.
Reviewed at 2804dda4de, and tested as part of the stack (#6700, #6701, #6752) merged with main. No correctness findings: the cleanup order, the cancelled-start path, the restart before the sandbox exists and the verifier access all hold up.
Nit
- This PR introduces "attempt sandbox" in code, config and the README, but the glossary row for it arrives only in #6752.
AGENTS.mdasks for the term in the same PR that introduces the concept.
Evidence
environment_servers/single_agent_turn/tests: 346 pass on the stack merged with main.- Live:
single_agent_turnat #6752 merged with main, against an OpenSandbox deployment, with real sandbox groups and a scripted agent and Resources Server that borrow what they are lent and run commands in it. 27 of 27 checks pass.
| Verifier mode | Result |
|---|---|
shared, task with tools |
The agent runs in its group's working directory; /verify borrows the same group and reads the agent's file |
separate, task with tools |
The agent's group is deleted before /verify; the verifier gets a fresh group without the agent's file |
separate, agent that runs in process |
The agent is lent nothing; only the verifier's group starts |
none, task with tools |
The agent's group is deleted before /verify, which is lent nothing |
In every case the agent's group (model_only) and a separate verifier's group (no_network) could not resolve an outside host, and every group was deleted after the episode.
Not covered: a rollout with a model.
CI
The red checks at this head are non-blocking and not from this change:
- Harness conformance: the openclaw job passes its tests and then hits the 5-minute limit of its validation step. The miniswe_sandboxed job fails in "Run full scenario suite", as it did on main at
c559d23a23.
🤖 Generated with Claude Code
athitten
left a comment
There was a problem hiding this comment.
One blocking gap: this server's venv cannot import the OpenSandbox or E2B SDK, so the README example fails every attempt in a gym env start launch. The lifecycle held up in my runs: one sandbox per attempt, stopped after the agent closes and after /verify on success, failure, timeout and cancel. The other comments are non-blocking docs and tests. The server suite passes at this head (316). Merged with current main, where the conflicts are additive, it also passes (324).
Signed-off-by: yaoyu-33 <[email protected]>
…cement Signed-off-by: yaoyu-33 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
|
/ok to test f3d0381 |
Signed-off-by: yaoyu-33 <[email protected]>
|
/ok to test e29b699 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/46762715830 |
Gym #6700 made SingleAgentTurnEnvironmentServer._verify read handles.attempt_sandbox; the training-contract test's fake handles lacked it. Signed-off-by: Paul Furgale <[email protected]>
What
With
sandbox_providerandsandbox_configset,single_agent_turnowns one sandbox per attempt. It starts the sandbox, lends it to the agent and then to/verify, and stops it on every path. The Resources Server and the agent only borrow it.Why
The sandbox design makes the Environment Server the single owner of each attempt's sandbox, so no agent loop or grader runs on a host. This PR adds that owner to
single_agent_turn. It builds onOwnedSandboxes(#6414), typed network rules (#6416) andborrow()(#6417), all on main.Highlighted steps are this PR. Steps 5–6 are the agent's (Simple Agent in #6701), and the dashed steps are follow-ups.
sandbox_providersandbox_provideris set/verifymodel_only) or cannot lend (local). Also refuses a rule that blocks the tools the episode grants.Follow-ups (from the sandbox design):
sandbox_config./verifyborrows the attempt's sandbox, with its rule.Issue: none. Rollout evidence: mcqa A/B on 10 attempts: in-process 0.7, sandboxed 0.7; provider down fails at seed; no leftover sandboxes.
🤖 Generated with Claude Code