Skip to content

feat(sandbox): AgentENV snapshots, lease and kill-at-timeout for the E2B provider - #5410

Merged
pthombre merged 8 commits into
mainfrom
pranav/envckpt-7-agentenv-provider
Nov 22, 2026
Merged

pthombre merged 8 commits into
mainfrom
pranav/envckpt-7-agentenv-provider

Conversation

@pthombre

@pthombre pthombre commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

#3757 (kill at timeout and auto-pause for the E2B provider) has merged into main; this PR builds on it.

What changed and why

AgentENV is an E2B-API sandbox service whose snapshots save the whole VM: memory, processes and disk. Sandbox checkpointing (#5265) needs a provider that can snapshot a sandbox, create a sandbox from that snapshot, and delete or list snapshots. Until now only OpenSandbox could do this. The E2B provider had none of it, and on AgentENV it also failed in several ways before any checkpoint was involved.

This PR makes the E2B provider a checkpoint-capable provider on AgentENV and fixes what a real AgentENV run needs.

Snapshot capability (SupportsSandboxSnapshot)

  • snapshot returns the SDK's snapshot id. The snapshot is usable as soon as the call returns, so wait_snapshot_ready returns at once.
  • Snapshot names are a setting (snapshots.send_names, off by default, on in agentenv.yaml), because E2B files a named snapshot as a team-wide template alias. With names on, a snapshot whose request fails or is cancelled is deleted by its name, so one the service took without Gym learning its id does not stay.
  • create_from_snapshot starts a sandbox from the snapshot. A missing snapshot raises SandboxSnapshotNotFoundError (feat(sandbox): snapshot, fork and delete for OpenSandbox, with a checkpointer #5265), so the checkpointer's fork retry works. AgentENV reports a missing snapshot as HTTP 400 rather than 404, and both are recognized.
  • delete_snapshot treats a missing snapshot as already deleted. list_snapshots filters by name on the client.
  • snapshots.keep_guest_clock (last commit; on in the AgentENV config, off by default). AgentENV sets the wall clock of a sandbox created from a snapshot to the current time, so a harness that continues in it sees the clock jump over the time the snapshot sat unused. OpenCode makes its message IDs from the clock, and the jump could put a message out of order. With the setting, create_from_snapshot asks AgentENV to keep the snapshot's clock. It sends the flag together with the create's other extension parameters, because a create's parameters replace the snapshot's. A create from a template never sends it: the template would get its build-time clock.
  • The provider declares capabilities.snapshot_keeps = {"files", "processes"} (a typed SandboxCapabilities, read with provider_capabilities(), under the names feat(sandbox): apply typed network rules through owner capabilities #6416 uses; OpenSandbox declares {"files"}). A sandbox created from an AgentENV snapshot continues the processes it was running. The next PRs use this to keep the harness running instead of relaunching it.

Lifecycle

  • Kill at timeout (feat(sandbox): support AgentENV auto-pause and resume #3757, in main): create.auto_resume: false sends kill-on-timeout explicitly. Otherwise AgentENV pauses a timed-out sandbox and never evicts it.
  • Lease (create.renew_ttl_s, the key OpenSandbox uses): sandboxes are created with the lease as their timeout, and the provider renews it up to the sandbox's lifetime. Each whole renewal is bounded at 10 s, renewals run through 64 slots, a resume grants one lease, and a lease needs create.timeout_s. If the process holding them dies, its sandboxes end one lease later rather than at their full lifetime.
  • Reachability wait (create.reachable_timeout_s): under a high create rate, AgentENV can report a sandbox as created while its gateway still answers 502. A create or fork now runs a no-op command until the sandbox is reachable, retrying only that 502 with backoff. A sandbox still unreachable at the deadline is killed and the create raises E2BCreateError. Off by default.

Fixes the E2B provider needs on AgentENV

  • Transport shim. Landed separately in fix(sandbox): correct E2B sandbox-stop errors and support e2b 2.62 #5509 and is not in this diff.
  • Command timeouts return exit code 124 with error_type="timeout", as OpenSandbox does (Local, Docker, Apptainer and Enroot return 125), and the processes a timed-out command left are killed.
  • Kills. A kill that finds no sandbox is checked again, and repeated if the sandbox still runs.
  • Unreachable sandboxes raise E2BSandboxUnreachableError from exec, and idempotent operations retry it. A 404 is never retried.
  • Network policy. provider_options.network_policy maps onto E2B's network option. A deny rule that names a host is refused, because E2B's deny list takes addresses only.
  • Sandboxes AgentENV no longer has. AgentENV answers a request about one with a 404 whose body is empty, and the SDK fails to parse that body before it checks the status. On that parse error the provider looks the sandbox up; a 404 there makes a kill count the sandbox as already gone, ends its lease renewal, and fails its snapshot with a clear "is gone" error. Without this, one sandbox that disappeared failed every later checkpoint's retire and stopped training.

Fixes from the 16-node AgentENV runs

  • Dropped command streams are reattached. A command whose output stream drops before its deadline (E2B reports it as a timeout, or as "could not be reached") is reattached by pid instead of failing. Only a timeout at the command's own deadline, or a non-zero exit, is final. A long launch, which holds one stream for the whole rollout, no longer dies with its stream.
  • New-sandbox grace period (operations.new_sandbox_grace_s, default 15 s). In a sandbox's first seconds AgentENV can answer 404 "sandbox assignment not found" for a sandbox that runs. During the period the reachability probe waits out a 404 like a 502, a kill that finds nothing is repeated, a reply the SDK cannot parse is never taken as "gone", status() reports UNKNOWN, and a renewal keeps the lease. Restored sandboxes get the same period, and a probe that gives up logs its error.
  • Quieter leases. A renewal skips a lease dropped since its round began, and a sandbox AgentENV is already killing drops its lease without a warning.
  • AgentENV sandbox lifetime 10,800 s: it must outlast the agent's timeout plus the checkpoint pause allowance. A dead process's sandboxes still end one lease later.

Image PATH in login shells (fourth commit)

  • The problem. The E2B SDK starts every command as bash -l -c and every terminal as bash -i -l. A sandbox process does start with its image's environment (AgentENV applies the image's ENV and WORKDIR), but a login shell reads /etc/profile first, and on Debian-based images that resets PATH. Tools installed outside the default PATH (/usr/local/go/bin, /usr/local/cargo/bin, /opt/conda/bin, ...) are then not found: on the mixed AgentENV blend, swemer Go and Rust tasks graded 0 with go: command not found, and agents hit the same wall in their tool calls.
  • The fix (create.restore_login_env, off by default, on in agentenv.yaml). Each new sandbox, including one created from a snapshot, gets /etc/profile.d/zz-nemo-gym-env.sh. Every login shell sources it last, and it restores the environment the shell started with: its variables as they were, and PATH with its starting entries first, then any the profile added. Shells other than bash return at its first line. A sandbox whose hook cannot be written is killed and the create fails, rather than grading with the wrong PATH.

Config and tooling

  • An AgentENV provider config for the E2B provider, set through the standard E2B environment variables.
  • A cleanup tool that lists the snapshots and sandboxes a run left behind and deletes them only when asked.
  • Provider docs.

Found in the review of this PR and fixed here (last commit)

  • list_snapshots returns SandboxSnapshotInfo, the type the snapshot contract of feat(sandbox): snapshot, fork and delete for OpenSandbox, with a checkpointer #5265 and the checkpointer's sweep expect; it returned dicts, so with names sent every release would have failed in the sweep. A snapshot taken without a name has name=None, a listing that fails raises SandboxSnapshotError, and with names off and a prefix given the service is not asked at all, since nothing can match.
  • A cancelled create no longer leaks its sandbox. A create cancelled while the new sandbox was probed, or its login hook written, left the sandbox running with a lease that renewed it for its whole lifetime. The lease is dropped at once and the sandbox is killed off the cancel's path; aclose waits, with a bound, for those kills.
  • A lease is dropped only after two renewal rounds in a row found no sandbox. A gateway replica can answer "not found" for a sandbox that runs, and one such answer used to end the lease of a healthy sandbox.
  • Snapshot errors are the contract's: E2BSnapshotError is a SandboxSnapshotError, a missing snapshot carries its id, and a delete that fails raises SandboxSnapshotError.
  • scripts/agentenv_cleanup.py refuses an empty snapshot prefix and metadata with an empty key or value (either selected everything the key can see), checks each listed sandbox's metadata itself, turns on listing by name itself, and takes only a checkpointer's snapshot prefix (ng-<state dir id>-). It loads the e2b SDK itself.
  • Docs and configs list renew_ttl_s, reachable_timeout_s, new_sandbox_grace_s and the snapshots section, and say that the reachability probe waits out a 404 as well as a 502.

A known departure from the snapshot contract. Listing by a name prefix is off by default (snapshots.list_by_name: false), also in agentenv.yaml: the listing reads every snapshot the key can see, a checkpoint release waits for it, and on AgentENV cell 3 no snapshot listing answered within 180 s on 2026-11-21. The contract's release-by-prefix sweep then finds nothing on E2B; the checkpointer still deletes the snapshots it has indexed, by id, and a named snapshot whose request returned no id is deleted by its name. Names themselves stay off in e2b.yaml. The README, the configs and the docs say so.

Changes from the second review (last commit, bbbea7855a)

  • Lease: the renew_ttl_s key; each whole renewal bounded at 10 s, lookup included; 64 renewal slots instead of fixed batches; a resume grants one lease and renewals follow the resumed SDK handle; a lease without a lifetime is rejected.
  • Snapshots: the typed SandboxCapabilities; names on for AgentENV with delete-by-name for a request that returned no id; list_by_name and operations.snapshot_list_timeout_s; delete_snapshot counts an empty-body 404 as deleted once a lookup confirms it.
  • Create: restore_login_env off by default; the hook write is repeated while a new sandbox answers "not found" in its grace period; a REST create cancelled during its connect kills the sandbox off the cancel's path; a deny rule under defaultAction: deny is refused; a network_policy that replaces create.network is warned about once.
  • Login hook under errexit: the suggested || : alone does not help. bash ends the shell at export SHELLOPTS=... whatever follows it, so the hook skips bash's read-only variables and keeps || : for exports that fail for other reasons.
  • Housekeeping: expired grace periods are forgotten; aclose cancels and names cleanup it gave up on; agentenv_cleanup.py takes only a checkpointer's prefix; agentenv.yaml is an overlay on e2b.yaml.
  • Not changed, by decision: a lease shortened by a borrowed connection (the SDK only lengthens a running sandbox's timeout on connect); scheduling drift of renewal rounds; the reachability deadline on a slow probe; a post-create 404 reported as a missing snapshot; spec validation on forks; the 1% deadline tolerance; empty PATH entries in the hook; checking --snapshot-ids against a listing; the e2b SDK floor.

How it works

sequenceDiagram
  participant K as Sandbox checkpointer (PR 5265)
  participant P as E2B provider
  participant A as AgentENV
  K->>P: snapshot(sandbox)
  P->>A: create_snapshot
  A-->>P: snapshot id (ready)
  P-->>K: id, and wait_snapshot_ready returns at once
  Note over K: crash, new job
  K->>P: create_from_snapshot(id, spec)
  P->>A: create(template=id)
  alt snapshot exists
    A-->>P: sandbox, same processes, the snapshot's clock with keep_guest_clock
  else missing
    A-->>P: 400 template not found
    P-->>K: SandboxSnapshotNotFoundError, then the checkpointer retries
  end
  K->>P: delete_snapshot(id) on release
Loading

Where this sits in the stack

This stack checkpoints environment-server episodes whose agent harness runs in a sandbox the resources server lends. #5264, #5265 and #5266 have merged, and the rest of the stack is rebased onto main after them. #5265 to #5331 add checkpoints for OpenCode and the SWE servers on OpenSandbox. #5410 to #5413 add AgentENV (E2B API, VM memory snapshots), where a restored sandbox still runs the harness's processes, so OpenCode continues in place instead of being relaunched. Each PR's diff shows only that PR's change.

  1. feat(checkpoint): protocol for harnesses that borrow a sandbox #5264: feat(checkpoint): protocol for harnesses that borrow a sandbox (merged)
  2. feat(sandbox): snapshot, fork and delete for OpenSandbox, with a checkpointer #5265: feat(sandbox): snapshot, fork and delete for OpenSandbox, with a checkpointer (merged)
  3. feat(swebench): checkpoint the task sandboxes of episode sessions #5266: feat(swebench): checkpoint the task sandboxes of episode sessions (merged)
  4. feat(swebench): typed sessions on the owner base with capture-once verify #5267: feat(swebench): typed sessions on the owner base with capture-once verify
  5. feat(opencode): pause at checkpoints and resume after a crash #5268: feat(opencode): pause at checkpoints and resume after a crash
  6. test(checkpoint): end-to-end harness scenarios, SWE-bench recipe, docs #5269: test(checkpoint): end-to-end harness scenarios, SWE-bench recipe, docs
  7. feat(swe): checkpoint the episode sessions of the repository-task servers #5331: feat(swe): repository-task servers on the sandbox owner base
  8. feat(sandbox): AgentENV snapshots, lease and kill-at-timeout for the E2B provider #5410: feat(sandbox): AgentENV snapshots, lease and kill-at-timeout for the E2B provider (this PR)
  9. feat(checkpoint): hold-pause a harness when the sandbox snapshot keeps its processes #5411: feat(checkpoint): hold-pause a harness when the sandbox snapshot keeps its processes
  10. feat(agent-utils): resume a supervised harness in place after a restore that kept its processes #5412: feat(agent-utils): resume a supervised harness in place after a restore that kept its processes
  11. feat(opencode): resume OpenCode in place on sandboxes whose snapshots keep processes #5413: feat(opencode): resume OpenCode in place on sandboxes whose snapshots keep processes

Issue

No tracking issue exists. This adds AgentENV as a checkpoint-capable sandbox provider for the stack above, so SWE training runs on AgentENV can checkpoint and resume their sandboxes.

Validation

Second-review commit, head bbbea7855a on main (Slurm, one node each, rl-gym CI container; nothing ran on a login node):

  • Job 9243883: ruff format and ruff check clean on nemo_gym/sandbox, the cleanup script and their tests; import-linter 2 contracts kept; 2263 passed and 1 failed across test_e2b_provider.py, test_opensandbox_provider.py, test_agentenv_cleanup.py, tests/unit_tests/config, the public-API, moved-paths, packaging, import-linter-coverage and docs-link tests. The failure is test_real_sdk_user_agent_and_call_shapes: the job's venv has e2b 2.62.0, outside the pinned >=2.46.0,<2.51.0.
  • Live checks against AgentENV cell 3 on 2026-11-21, with this branch's provider (jobs 9241040, 9241235, 9241686, 9241892, 9242007):
    • Every snapshot listing (unfiltered, limit=100, by sandboxID, by name) and the template listing timed out at 180 s; the provider's listing failed with a timeout.
    • A named snapshot is looked up and deleted by its name alone, with e2b 2.62.0 and 2.46.0. A lookup of a name that does not exist answers 404.
    • A named snapshot request cancelled 0 to 0.55 s into a 0.6 to 0.9 s request left no snapshot in 5 of 5 cases with no cleanup, and none in 8 of 8 with an immediate delete by name.
    • Everything the checks created was deleted and confirmed gone.
  • Not run on this head: a rollout with a model on AgentENV, an existing E2B config such as OSWorld, pre-commit run --all-files, and the stack above this PR, which still reads snapshot_keeps_processes and lease_s until it is restacked.

Earlier validation, on previous heads:

Head 937c63b37b, on #5331 4d24b91c8e. The stack was rebased onto main after #5266 merged. Tests ran as Slurm jobs on one node each, in the rl-gym CI container with the repository's dev dependencies; nothing ran on a login node. In that container main itself has 179 failures and 13 errors in the core unit suite (job 9188100), so results are compared with main's list by test id. Two test files that hang there, on main too, are left out: tests/unit_tests/test_slurm_control.py and tests/unit_tests/benchmarks/test_agentic_vbench_staging.py.

  • Stack tip 3d0e643db9, which includes this PR (jobs 9188099, 9188102): import-linter clean; ruff check and ruff format --check clean; all ten server suites pass; the core suite differs from main's list only by tests that fail from run to run on either side.
  • This head (jobs 9188114, 9188115): the test areas the stack touches (OpenCode, SWE-bench, swe_rebench, agents, server runtime, sandbox, models) differ from main only by tests that fail when the node is loaded and pass when their file runs alone (test_harness_pause.py::test_a_hold_before_the_launch_is_not_added_to_the_deadline_again_by_a_later_pause, test_exec_transport.py::test_confirmed_cleanup_cancels_stuck_transport) and test_docker_compose.py tests that fail from run to run on main too. The whole core suite was run per level on the previous base (feat(swebench): checkpoint the task sandboxes of episode sessions #5266's head before it was squash-merged), with the same result; on this base it ran on the tip only.
  • Process-level checkpoint e2e on the stack tip (jobs 9188102, 9188735, NEMO_GYM_CHECKPOINT_E2E=1): harness scenarios 11 passed, sandbox 6, sequences 4, fake backend 1, test_checkpoint_e2e.py 45 passed and 12 skipped.
  • Rebase: main's E2B changes since the last version (accepting resource_requests, the not-running check in exec) are kept as main has them, with this PR's unreachable-sandbox handling after main's check; main's E2B tests pass unedited.
  • Tests added in the review: the typed listing, the cancelled create, the two-round lease rule, the network policy on a fork through the REST create, the cleanup script's selection, and that the shipped configs build a provider.
  • Review: three reviewers and a second pass that separated what is certain from the code from hardening that rests on unverified AgentENV behaviour; only the first kind is fixed here.
  • Not run on this head: any live test against AgentENV. In particular the network rule on a sandbox created from a snapshot, the two-round lease rule and the typed snapshot errors are covered by unit tests against fakes only.
  • Not run: pre-commit run --all-files; any live sandbox, real-model or training run on this head.
  • Earlier evidence, not repeated on this head (previous versions of the stack, which had their own sandbox owner base and set the clock back inside the sandbox; snapshots.keep_guest_clock had unit tests only):
    • Live tests against AgentENV covering snapshot, fork (same processes, continuous uptime), lease expiry, kill-at-timeout, concurrent creates and snapshots, and cleanup.
    • Checkpoint and resume at 8 and 16 nodes; two 16-node runs, a checkpoint run and a restore from its checkpoint, committed every checkpoint with no sandbox loss.
    • Login-shell PATH: a survey of 644 templates across the five SWE routes (106 lose a tool without the hook, none with it); golden patches through the real graders (all 16 tasks that graded 0 resolved, 10 controls unchanged); an A/B over 400 sandboxes showing no change in first-command 502s.
  • Training run, on the stack two rebases ago (e62ed9ca9a), not repeated on this head: 16-node full-SWE run on AgentENV, Slurm job 9048275 (2 h, five routes, 8 Gym replicas), compared with reference job 8760594 on an earlier stack. 3 training steps (2981 s, 2567 s, 670 s; reference 2948 s, 2606 s, 681 s); 8 rollout checkpoints saved, 0 failed (reference 7 / 0); checkpoint save median 57 s, Gym commit median 50 s (reference 65 s and 48 s); 351 full 16-rollout batches, median 730 s (reference 347, 720 s); no snapshot, fork, anti-cheat, base-commit or patch-extract failures. The AgentENV gateway returned about four times as many 502s as in the reference; on the servers of this stack each was a retried first attempt and none exhausted its retries. Not exercised: the run had no crash, so no restore and no resume in place ran; scale_swe is not on the checkpoint layer.

Follow-ups, not in this PR:

  • A fork that fails after AgentENV created the sandbox (hook write, reachability) can be reported as "snapshot not found"; to be fixed together with the hook-write and connect grace.
  • Hardening of command reattach and lease renewal that rests on AgentENV behaviour not yet confirmed.
  • status() never reports STOPPED.
  • The 120 s reachability wait runs inside the checkpointer's concurrency limit; kept as is.

Compatibility

  • E2B users without checkpointing: renew_ttl_s, restore_login_env and reachable_timeout_s are off unless set, and snapshots are taken only when a checkpointer asks; auto_resume keeps main's default (feat(sandbox): support AgentENV auto-pause and resume #3757).
  • A command stream that drops before the command's deadline is reattached instead of raising a timeout.
  • operations.new_sandbox_grace_s defaults to 15 s; 0 turns the grace period off.
  • AgentENV config: the sandbox lifetime is 10,800 s.
  • Timed-out commands now return exit code 124 with error_type="timeout" instead of raising, as OpenSandbox does.
  • e2b SDK: the >=2.46 constraint is unchanged. 2.62 works with the transport shim of fix(sandbox): correct E2B sandbox-stop errors and support e2b 2.62 #5509. The wait for a sandbox the gateway cannot reach yet matches SandboxUnreachableException, which e2b has from 2.53; raising the floor is left to a separate PR.
  • Login shells keep the image's PATH only with create.restore_login_env: true, which agentenv.yaml sets: each sandbox then gets /etc/profile.d/zz-nemo-gym-env.sh, and agents find toolchains they could not find before. It is off by default, so other E2B configs are unchanged.
  • snapshots.keep_guest_clock is off by default and on in the AgentENV config. A kept clock lags real time by as long as the snapshot sat unused, so TLS checks and signed requests made from the sandbox can fail after a long gap.
  • Snapshot names are no longer sent by default; agentenv.yaml sends them. Listing snapshots by a name prefix needs snapshots.list_by_name: true.
  • agentenv.yaml holds only what AgentENV changes and pulls in e2b.yaml through config_paths; it is still passed alone.
  • snapshot_keeps_processes is replaced by capabilities.snapshot_keeps; nothing on main read it.
  • list_snapshots returns SandboxSnapshotInfo instead of dicts, and raises SandboxSnapshotError when the listing fails.
  • A network deny rule that names a host is refused on E2B at create.
  • scripts/agentenv_cleanup.py refuses an empty snapshot prefix and empty metadata keys or values.

🤖 Generated with Claude Code

@pthombre pthombre added feature New capabilities, enhancements, or enablement work area:sandbox Sandbox providers, isolation, and sandbox runtime contracts complexity:high Cross-component or shared-contract change with a large review surface labels Oct 31, 2026
@copy-pr-bot

copy-pr-bot Bot commented Oct 31, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

if self._create.reachable_timeout_s is not None:
try:
await self._wait_reachable(sandbox, self._create.reachable_timeout_s)
except Exception as exc:

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.

If create is cancelled during the reachable wait, this except Exception does not run, because CancelledError is a BaseException. The lease was already started, so does that sandbox stay up for its full lifetime with nobody holding it? On the deadline path, sandbox.kill returning false also skips the recheck inside _kill. Should every way out of this wait, including cancel, drop the lease and kill through _kill?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed earlier in this PR, and tightened in bbbea7855a: a cancelled create drops its lease and kills the sandbox in a task of its own, which aclose waits for. There is now a test that cancels through an anyio cancel scope with a kill that suspends (test_a_create_cancelled_through_a_cancel_scope_still_kills_the_sandbox).

"""Nothing to wait for: an E2B snapshot is usable once ``snapshot`` returns."""
return None

async def delete_snapshot(self, snapshot_id: str) -> None:

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.

An AgentENV 404 with an empty body arrives as JSONDecodeError, which _is_not_found does not match, so _with_retries retries it. This only swallows _is_not_found, so a snapshot that is already gone looks like it would raise instead of counting as deleted. Kill and snapshot recover in _gone_behind_unparsed_reply, but only after those retries. Should this parse error count as not-found before any retry?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in bbbea7855a. delete_snapshot now treats the unparsed reply as deleted once a lookup of the template answers 404, and raises otherwise (test_a_delete_answered_with_an_empty_404_counts_as_deleted_only_for_a_snapshot_gone). The lookup still runs after the configured retries; I left the retry policy alone because the same error is deliberately retried for kill.

@pthombre
pthombre force-pushed the pranav/envckpt-7-agentenv-provider branch from 9509c84 to e560939 Compare November 3, 2026 06:40
@pthombre
pthombre force-pushed the pranav/envckpt-7-agentenv-provider branch from e560939 to 68eeb28 Compare November 5, 2026 20:07
@pthombre

pthombre commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

Being rebased onto current main, after #5264 and #5265 (already rebased). Until this branch is pushed, its diff still shows their old commits. Not ready for review yet.

@pthombre
pthombre force-pushed the pranav/envckpt-7-agentenv-provider branch from d87df61 to 10022d4 Compare November 12, 2026 20:35
@pthombre
pthombre force-pushed the pranav/envckpt-7-agentenv-provider branch 2 times, most recently from 117e2ef to 937c63b Compare November 20, 2026 08:29
pthombre and others added 5 commits November 21, 2026 16:19
…anding it over

At 16-node scale (hundreds of creates in a few minutes) AgentENV reported sandboxes as created while its gateway
still answered 502 "the sandbox could not be reached": 129 first commands failed, the anti-cheat scrub silently
skipped, and the rows that went into retry blocked every rollout checkpoint's drain. With
`create.reachable_timeout_s`, a create or fork runs a no-op command until the gateway reaches the sandbox, retrying
only that 502 with a doubling delay. Running the no-op again is always safe, unlike the caller's own commands, which
stay unretried. A sandbox still unreachable at the deadline is killed and the create raises E2BCreateError. Off by
default; agentenv.yaml sets 120 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
…d streams

Fixes from the 16-node AgentENV runs, in the E2B provider and the AgentENV config.

- A command's output stream that drops before the command's deadline is reattached by pid. E2B reports a dropped
  stream, and "could not be reached", as a TimeoutException, which used to end the command: OpenCode's launch was
  then stopped and the rollout started over although the sandbox and the harness were fine. A timeout at the
  deadline stays final (exit 124), and so does a non-zero exit.
- New-sandbox grace period (`operations.new_sandbox_grace_s`, default 15 s from the create): in a sandbox's first
  seconds AgentENV can answer 404 "sandbox assignment not found" for a sandbox that runs. The reachability probe
  waits out a 404 like a 502; a kill that finds nothing is repeated until it finds the sandbox; a reply the SDK
  cannot parse is never taken as "gone"; status() reports UNKNOWN; a renewal keeps the lease. Restored sandboxes
  get the same period. A probe that gives up logs its error, and its kill no longer leaks the sandbox on a 404.
- Lease renewal skips a lease dropped since the round began, and a sandbox AgentENV is already killing ("invalid
  state Killing") drops its lease at INFO instead of a warning every round.
- The resource-request warning is logged once per process; later templates at DEBUG.
- AgentENV sandbox lifetime 3600 s -> 10800 s: it must outlast the agent's timeout plus the checkpoint pause
  allowance, or a long rollout's sandbox is killed under it. A dead process's sandboxes still end one lease later.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
…mands in

The E2B SDK starts every command as `bash -l -c` and every terminal as `bash -i -l`. A sandbox process does
start with its image's environment (AgentENV applies the image's ENV and WORKDIR), but a login shell reads
/etc/profile first, and on Debian-based images that resets PATH. Tools installed outside the default PATH
(/usr/local/go/bin, /usr/local/cargo/bin, /opt/conda/bin, ...) are then not found: on the mixed AgentENV
blend, swemer Go and Rust tasks graded 0 with "go: command not found", and agents hit the same wall.

Each new sandbox, including one created from a snapshot, now gets /etc/profile.d/zz-nemo-gym-env.sh
(`create.restore_login_env`, on by default). Every login shell sources it last, and it restores the
environment the shell started with (/proc/$$/environ): variables as they were, PATH with its starting
entries first and any the profile added after them. Shells other than bash return at its first line. A
sandbox whose hook cannot be written is killed and the create fails, rather than grading with the wrong
PATH.

Measured on AgentENV before this change:
- 644 templates across the five SWE routes: with the hook, the provider's commands, nested login and
  non-login shells and terminals resolve the same binaries as a container on every template; without it,
  106 lose a tool.
- Golden patches through the real graders: 16 tasks broken today (11 known plus 5 sampled Go/Rust) are
  resolved; 38 controls unchanged.
- OpenCode 1.17.11's bash tool gets the image's PATH again. The hook survives snapshot and restore. It costs
  one file write per create (~0.2 s) and ~0.5 ms per login shell.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
…om a snapshot

AgentENV sets the wall clock of a sandbox created from a snapshot to the current time, so a harness that
continues in it sees the clock jump over the time the snapshot sat unused. OpenCode makes its message IDs from
the clock, and the jump could put a message out of order.

With snapshots.keep_guest_clock, create_from_snapshot sends customExtensionParams {keepGuestClock: true}
together with create.custom_extension_params (a create's parameters replace the snapshot's), and the guest keeps
the snapshot's clock. A create from a template never sends it: the template would get its build-time clock. The
REST create's error now carries its HTTP status, so a missing snapshot is still reported as
SandboxSnapshotNotFoundError on that path. On in the AgentENV config, off by default.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
…eak a sandbox whose create is cancelled

Found in a review of the AgentENV snapshot support.

- `list_snapshots` returned dicts where the snapshot contract, and the checkpointer's sweep, expect
  `SandboxSnapshotInfo`: with names sent, every release would have failed in the sweep. It now returns the
  contract's type, with `name=None` for a snapshot taken without a name, matches any of a snapshot's names,
  raises `SandboxSnapshotError` when the listing fails, and does not ask the service at all when names are not
  sent and a prefix is given, since nothing can match.
- A create cancelled while the new sandbox was probed or its login hook written left the sandbox running, and
  its lease kept renewing it for its whole lifetime. The lease is now dropped at once and the sandbox is killed
  off the cancel's path; `aclose` waits, with a bound, for those kills.
- A lease is dropped only after two renewal rounds in a row found no sandbox: a gateway replica can answer
  "not found" for a sandbox that runs, and one such answer used to end the lease of a healthy sandbox.
- Snapshot errors are the contract's: `E2BSnapshotError` is a `SandboxSnapshotError`, a missing snapshot carries
  its id, and a delete that fails raises `SandboxSnapshotError`.
- A `network_policy` deny rule that names a host is refused: E2B's deny list takes addresses only.
- `scripts/agentenv_cleanup.py` refuses an empty snapshot prefix and metadata with an empty key or value, which
  selected everything the key can see, checks each listed sandbox's metadata itself, and lists snapshots with
  names on. It loads the e2b SDK itself, so `require_e2b_sdk` is no longer exported from `nemo_gym.sandbox`.
- Names stay off by default. The README, the configs and the docs now say that this departs from the snapshot
  contract and what a release then cannot find. They also list `lease_s`, `reachable_timeout_s` and the
  `snapshots` section, and say that the reachability probe waits out a 404 as well as a 502.
- Tests: the three tests of the real SDK's shapes accept e2b 2.6x (wrapped API transport, `keep_memory` default,
  `/v2` connect), and new tests cover the listing, the cancelled create, the lease, the network policy on a fork
  through the REST create, the cleanup script's selection, and that the shipped configs build a provider.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
@pthombre
pthombre force-pushed the pranav/envckpt-7-agentenv-provider branch from fa2b87e to d5ee8ae Compare November 22, 2026 00:20
Lease:
- Rename create.lease_s to create.renew_ttl_s, the key OpenSandbox uses, and reject it without create.timeout_s.
- Bound each whole renewal at 10 s, lookup included, and renew through a pool of 64 slots instead of fixed batches.
- Resume a leased sandbox with one lease, capped by its remaining lifetime, and renew the resumed SDK handle.

Snapshots:
- Declare what a snapshot keeps as a typed SandboxCapabilities.snapshot_keeps, read with provider_capabilities(),
  in place of the untyped snapshot_keeps_processes attribute.
- agentenv.yaml sends snapshot names. A named snapshot whose request fails or is cancelled is deleted by its name,
  off the caller's path.
- Listing by a name prefix gets its own switch, snapshots.list_by_name (off), and a budget,
  operations.snapshot_list_timeout_s: a checkpoint release waits for the listing, and a cell's may not answer.
- delete_snapshot counts an empty-body 404 as deleted once a lookup confirms it.

Create:
- restore_login_env is off by default and on in agentenv.yaml.
- The login-shell hook write is repeated while a new sandbox answers "not found" in its grace period.
- The hook skips bash's read-only variables and passes over an export that fails, so an inherited errexit does
  not end the shell.
- A REST create cancelled during its connect kills the sandbox off the cancel's path.
- A deny rule under defaultAction deny is refused, and a network_policy that replaces create.network is warned
  about once.
- Expired grace periods are forgotten, and aclose cancels and names the cleanup it gave up on.

Config and tooling:
- agentenv.yaml holds only what AgentENV changes and pulls in e2b.yaml.
- agentenv_cleanup.py requires a checkpointer's snapshot prefix (ng-<state dir id>-), reports a failed delete and
  deletes the rest.

Signed-off-by: Pranav Thombre <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
@pthombre
pthombre force-pushed the pranav/envckpt-7-agentenv-provider branch from b39611f to bbbea78 Compare November 22, 2026 05:19
@pthombre

Copy link
Copy Markdown
Contributor Author

/ok to test bbbea78

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 22, 2026 05:20
@pthombre

Copy link
Copy Markdown
Contributor Author

Replies to the ten findings in the automated review, by title. Changes are in bbbea7855a.

Finding Outcome
Keep borrowed connections from shortening the owner's lease Not changed. The SDK's connect only lengthens a running sandbox's timeout: its docstring (e2b 2.62) says "For running sandboxes, the timeout will update only if the new timeout is longer than the existing one". A borrower's 300 s default therefore does not shorten a 1200 s lease.
Dropping supplied names defeats recovery of unindexed snapshots Changed, differently from the suggestion. agentenv.yaml now sends names, and a named snapshot whose request fails or is cancelled is deleted by its name. Listing by prefix has its own switch, off by default: on AgentENV cell 3 every snapshot listing timed out at 180 s on 2026-11-21, and a checkpoint release waits for that listing. Details are in the thread on agentenv.yaml and in the description.
Enforce the reachability deadline around the awaited probe Not changed in this PR.
A post-create 404 is reported as a missing snapshot Not changed in this PR; it stays in the description's follow-ups.
Resume bypasses the new lease timeout Fixed. A leased sandbox resumes with one lease, capped by its remaining lifetime, and renewals follow the resumed SDK handle. A failed resume keeps the handle and the lease.
Snapshot forks skip unsupported-spec validation Not changed in this PR.
Reject explicit deny rules that this branch discards Fixed as suggested, with tests on the SDK create and the REST fork path.
Ignored export failures can terminate every login command Fixed, but the suggested || : alone does not do it. I traced it in bash 5.2: the shell ends at export SHELLOPTS=... whatever follows the command. The hook now skips bash's read-only variables (SHELLOPTS, BASHOPTS, BASH_VERSINFO, EUID, PPID, UID) and keeps || : for exports that fail for other reasons, such as a name that is no identifier. A variable a profile itself made read-only is still not covered.
Retain empty PATH components when restoring the starting PATH Not changed. The hook is now off by default, and the rewrite replaces the tested core of a script that every login shell sources.
Cap early-deadline tolerance independently of command duration Not changed in this PR.

@pthombre

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Every inline thread has a reply, and the changes are in bbbea7855a. On the three points here:

One way to declare what a snapshot keeps. Done with #6416's names: SnapshotContent, SandboxCapabilities.snapshot_keeps and a provider_capabilities() reader. #6416 can add its other fields without renaming anything. #5411 and #5413 switch their readers when they are restacked onto this head; until then they still read snapshot_keeps_processes and lease_s.

Overlap on the E2B provider. Nothing changed here for #5460, #5339 or #6458. Whichever of these lands second rebases onto the first; for #5460 that includes settling which PR owns operations.new_sandbox_grace_s and _new_until.

Evidence on this head.

  • Run: the unit suites and lint in Slurm (job 9243883), and live checks of snapshot naming, lookup and delete by name, cancelled snapshot requests and the snapshot listing against AgentENV cell 3. The numbers are in the description's Validation section.
  • Not run: a rollout with a model on AgentENV covering a snapshot, a restore and a kill at timeout, and an existing E2B config such as OSWorld.
  • The change of defaults you were concerned about is smaller now: restore_login_env is off by default, so the login hook only applies where a config asks for it.

The two stale description lines are fixed: the transport shim is credited to #5509, and the timeout line says 124 matches OpenSandbox while Local, Docker, Apptainer and Enroot return 125.

@github-actions

github-actions Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

@pthombre
pthombre requested a review from macandro96 November 22, 2026 06:51
) from error
raise
finally:
if sent_name is not None and not snapshot_id:

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.

[P2] Do not delete an existing snapshot after a rejected request

With snapshots.send_names: true (the shipped AgentENV config), take a snapshot named checkpoint-1, then request another snapshot with that name. AgentENV rejects the second request with HTTP 400 AliasConflict, but this finally still deletes checkpoint-1, destroying the first valid restore point. I reproduced that sequence through this provider with a fake implementing AgentENV's alias-conflict and delete semantics. AgentENV rejects an already-owned alias, and deletion resolves the supplied alias to its owning snapshot.

Could cleanup skip definitive rejections such as alias conflicts, and only delete a snapshot attributable to this request? Please add a regression test that a successful named snapshot survives a rejected duplicate request.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 509e3e85ec. A snapshot request the service refused with a client error (HTTP 4xx other than 408) took no snapshot, so its name is now left alone; the delete by name still runs after a cancel, a timeout, a 5xx, or a reply with no status, where the service may have taken the snapshot.

test_a_named_snapshot_survives_a_refused_request_for_the_same_name uses a fake with AgentENV's two behaviours (a taken name is refused with 400 AliasConflict, and a delete by name deletes the snapshot that holds it) and asserts the first snapshot is still there. The README notes the rule.

unreachable = getattr(e2b, "SandboxUnreachableException", None)
if isinstance(unreachable, type) and isinstance(error, unreachable):
return True
return getattr(error, "status_code", None) == 502 or str(error).startswith("502:")

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.

Deferring the SDK upgrade still leaves the shipped AgentENV config exposed: it enables both reachable_timeout_s and restore_login_env, while the supported SDK range remains >=2.46.0,<2.51.0. A gateway 502 in that range becomes a plain TimeoutException, so _is_unreachable returns false and the probe/hook fails immediately. This is failure on the first attempt, rather than the wait simply being inactive.

I reproduced the hook path with the actual e2b 2.46 files.write and an HTTPX mock returning 502: one HTTP request, immediate TimeoutException, still inside the grace period. The real SDK RPC mapper likewise makes the reachability probe fail after one attempt. Both 2.46 and 2.50 have this mapping.

Could we either add bounded retry handling compatible with the supported SDKs or update the dependency range and locks here? The real-mapper regression test should accompany whichever fix lands, so the AgentENV configuration works with the dependencies this PR installs.

…p a snapshot whose name a refused request reused

An e2b SDK without SandboxUnreachableException (the pinned 2.46 to 2.50) reports a gateway 502 as a
TimeoutException built by format_sandbox_timeout_exception. The provider did not read that as "unreachable",
so with agentenv.yaml one 502 failed a create on the first reachability probe or login-shell hook write, and a
502 on a command was not raised as E2BSandboxUnreachableError. The provider now reads it as unreachable, by the
text the SDK's own formatter appends. Tests drive a 502 through the installed SDK's mappers.

With snapshots.send_names, a snapshot request that ended without an id had its name deleted. A request the
service refused with a client error took no snapshot, and AgentENV refuses a name that is already taken, so
the delete removed the snapshot that held the name. Such a request now leaves the name alone.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
@pthombre

Copy link
Copy Markdown
Contributor Author

/ok to test 509e3e8

@pthombre
pthombre added this pull request to the merge queue Nov 22, 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/45081505792

Merged via the queue into main with commit 3298b25 Nov 22, 2026
80 of 83 checks passed
@pthombre
pthombre deleted the pranav/envckpt-7-agentenv-provider branch November 22, 2026 23:25
hemildesai added a commit that referenced this pull request Nov 22, 2026
…ilience

main (#5410) added its own new-sandbox grace period: `_start_grace` and
`_in_grace`, a kill that is repeated, status UNKNOWN, and an opt-in
reachability probe (`create.reachable_timeout_s`). This branch keeps only
what main does not have, on main's helpers:

- a command start the gateway did not route is sent again, inside the
  command's deadline;
- file calls are retried on the unrouted 404 and on a 502;
- create waits for a health check inside the grace period when
  `create.reachable_timeout_s` is unset. A cancelled create is cleaned
  up by main's handler.

A command whose start is never routed before its deadline now reports a
timeout (exit 124), as main reports every timeout at the deadline.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Hemil Desai <[email protected]>
yaoyu-33 added a commit that referenced this pull request Nov 24, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:sandbox Sandbox providers, isolation, and sandbox runtime contracts complexity:high Cross-component or shared-contract change with a large review surface feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer risk:high Autobot PR risk: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants