Skip to content

feat(sandbox): borrow lent sandboxes and share harness configuration - #6417

Merged
yaoyu-33 merged 122 commits into
mainfrom
ananthsub/sandbox-borrow
Nov 25, 2026
Merged

yaoyu-33 merged 122 commits into
mainfrom
ananthsub/sandbox-borrow

Conversation

@ananthsub

@ananthsub ananthsub commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Add nemo_gym.server_runtime.borrow(access) and the shared nemo_gym.sandbox.HarnessSandboxConfig for a harness sandbox owned by an environment server or an agent.

owner → SandboxAccess → borrow() → commands / files / terminals → disconnect()

A BorrowedSandbox applies the lent user, working directory, and environment. Its lifecycle methods refuse start, stop, pause, resume, and snapshot; serialization retains operate scope. Leaving its context disconnects the client without stopping the owner's sandbox, and failed connections release their provider client under cancellation.

These are API guards: providers do not enforce operate scope, and raw .provider access can bypass them. Provider leases and repository-wide adoption remain follow-ups in #6703.

HarnessSandboxConfig types image, working directory, files, entrypoint, user, ports, and optional CPU-derived environment caps on top of SandboxConfig. It is shared across owners, including an environment server that supplies the harness sandbox when Resources lends none. An adopting agent must reject simultaneous legacy agent-level network_access and nested network settings. No existing agent recipe switches to these APIs here.

Stack

Review bottom to top: #6414 → #6415 → #6416 → #6417. Each PR targets the preceding branch; #6414 targets main. The stack includes main through d80581feb. Follow-up adoption and remaining lifecycle limits are tracked in #6703.

Validation

On the workstation, at 3c9fc158a:

  • pre-commit run --all-files: passed.
  • pytest tests/unit_tests/server_runtime/test_sandbox_borrow.py tests/unit_tests/server_runtime/test_owned_sandboxes.py tests/unit_tests/server_runtime/test_checkpoint_sandbox.py tests/unit_tests/sandbox/test_harness_config.py tests/unit_tests/sandbox/test_network_rules.py tests/unit_tests/test_public_api_facades.py tests/unit_tests/test_moved_paths.py tests/unit_tests/test_import_linter_coverage.py tests/unit_tests/test_fern_docs_links.py -n 4 --tb=short --import-mode=importlib: 1460 passed, 24 subtests passed in 244.57s (0:04:04).
  • pytest tests/unit_tests/sandbox tests/unit_tests/agents/test_outcome_policy.py tests/unit_tests/server_runtime/test_review_boundary_interfaces.py -n 4 --tb=short --import-mode=importlib: 2682 passed, 10 skipped in 45.51s.
  • npm run check in fern/: passed.
  • Scripted real Docker smoke with python:3.13-slim: passed all five checks. Exercises restricted container creation, borrowed shell and argument-list execution with lent settings, refusal of borrower stop, owner survival after disconnect, discard during create, cancellation settlement, and zero remaining containers after owner shutdown.

Preparation commits include DCO sign-off. Model rollout: N/A because no agent adopts these APIs yet; the Docker smoke is a real provider run without a model. Live E2B/OpenSandbox behavior and provider-enforced borrowing scope remain outside this validation.

@copy-pr-bot

copy-pr-bot Bot commented Nov 18, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

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]>
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the risk:high Autobot PR risk: high label Nov 18, 2026
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]>
@ananthsub
ananthsub force-pushed the ananthsub/sandbox-borrow branch from 7caa06b to ffac265 Compare November 18, 2026 23:19
@svcnvidia-nemo-ci svcnvidia-nemo-ci added feature New capabilities, enhancements, or enablement work area:agent Agent harnesses and Responses API agent behavior labels Nov 18, 2026
@hemildesai
hemildesai added this pull request to stack #6695 November 24, 2026 05:17
yaoyu-33 and others added 11 commits November 23, 2026 21:37
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]>
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]>
- 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]>
… 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]>
@yaoyu-33

Copy link
Copy Markdown
Contributor

/ok to test 4e71314

@yaoyu-33

Copy link
Copy Markdown
Contributor

Both regressions identified in the re-review were fixed in #6416 and are present on this branch at 4e71314. The argument-list documentation is restored, and the sandbox setup/rollback test executes its assertions.

On the workstation, 658 tests passed and 3 skipped, including the borrower, harness-config and inherited network/lifecycle suites. Full pre-commit passed. A real Docker smoke verified borrower execution, owner-only shutdown, discard during create, and cleanup after cancellation. It left no containers behind.

@hemildesai

Copy link
Copy Markdown
Contributor

Third review round at 4e71314

Tracking issue: #6703

I read the commits pushed since my last comment and reran the live check on this head. The two regressions this branch inherited from #6416 are gone, and I have no new finding here.

Addressed

  • The exec() argument-list documentation is restored on this head, and tests/unit_tests/sandbox/test_sandbox.py:2554 runs its body again.
  • The new test of a Resources Server grading in a sandbox it never started covers the borrower that is not an agent.

Still open

  • Low, a question. HarnessSandboxConfig is exported from nemo_gym.sandbox, which AGENTS.md asks to keep minimal and lifecycle-only. I only want to confirm the home is deliberate.
  • "The one way" to use a lent sandbox is advisory until providers enforce scope, as the module docstring says.

Live check on this head: 18 of 18 pass against OpenSandbox, and no sandbox was left.

Live server run on this head: 16 of 16 pass. The real deepswe_external1 resources server, built in-process and driven through its HTTP routes against OpenSandbox with no model: the null run graded 0, the golden run graded 1, and its sandboxes were stopped at verify, at close and at shutdown. gym env start was not used.

hemildesai
hemildesai previously approved these changes Nov 25, 2026

@hemildesai hemildesai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving at 4e71314. The inherited regressions are gone, the live OpenSandbox check passes (18 of 18), and the deepswe_external1 server run against live sandboxes passes on this head (16 of 16). Details are in my comments above and in #6703.

Not blocking: I would still like a word on whether nemo_gym.sandbox is the intended home for HarnessSandboxConfig.

The failing CI checks are the ones marked non-blocking: the mini-SWE sandboxed conformance probe fails wherever it currently runs, including on main and on other open PRs, and the Environment Server compliance audit reports findings on agents this PR does not change, as it does on other open PRs.

yaoyu-33
yaoyu-33 previously approved these changes Nov 25, 2026

@yaoyu-33 yaoyu-33 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the borrower lifecycle and harness configuration against the updated network layer. A borrower disconnects its client on context exit, and owner-only lifecycle operations remain with the owner. The real Docker smoke exercised borrower execution, refused a borrower stop, and confirmed owner cleanup. The workstation suite passed 658 tests with three skips, and required CI passed on this head.

@yaoyu-33
yaoyu-33 requested a review from a team November 25, 2026 15:29
@yaoyu-33
yaoyu-33 dismissed stale reviews from hemildesai and themself via 18aaf30 November 25, 2026 15:56
@yaoyu-33

Copy link
Copy Markdown
Contributor

/ok to test 18aaf30

@yaoyu-33 yaoyu-33 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I rechecked the eight-file borrowing change against the updated #6416 parent. Its patch ID matches the previously reviewed version, including the import-layer rule. On this revision, 4,059 tests and 24 subtests passed, full pre-commit passed, and the live Docker smoke confirmed that the borrower could execute with the lent settings, could not stop the owner's sandbox, and disconnected without stopping it. Cancellation, discard, and owner shutdown cleaned up the containers.

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 25, 2026 16:29
@yaoyu-33
yaoyu-33 added this pull request to the merge queue Nov 25, 2026
@yaoyu-33 yaoyu-33 added ready-to-merge PR is approved, current, and waiting for final CI or merge and removed needs-review PR is ready for code review and waiting on a reviewer labels Nov 25, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/45657868185

@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 25, 2026
Base automatically changed from ananthsub/owned-sandboxes-network to main November 25, 2026 17:04
@yaoyu-33

Copy link
Copy Markdown
Contributor

/ok to test 571c416

@yaoyu-33
yaoyu-33 enabled stacked auto-merge November 25, 2026 17:24
@yaoyu-33
yaoyu-33 added this pull request to the merge queue Nov 25, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/45665074890

Merged via the queue into main with commit e0531c9 Nov 25, 2026
81 of 84 checks passed
@yaoyu-33
yaoyu-33 deleted the ananthsub/sandbox-borrow branch November 25, 2026 17:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:agent Agent harnesses and Responses API agent behavior feature New capabilities, enhancements, or enablement work ready-to-merge PR is approved, current, and waiting for final CI or merge risk:high Autobot PR risk: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants