Skip to content

fix(sandbox): shield and bound AsyncSandbox.stop and the other releases - #6410

Merged
ananthsub merged 1 commit into
mainfrom
ananthsub/sandbox-shielded-stop
Nov 19, 2026
Merged

ananthsub merged 1 commit into
mainfrom
ananthsub/sandbox-shielded-stop

Conversation

@ananthsub

@ananthsub ananthsub commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Makes AsyncSandbox.stop() itself shielded from the request's cancellation and bounded in time, so every sandbox owner gets that stop without calling a helper.

A client that disconnects cancels its request, and anyio then cancels every later await in it. An unshielded stop in the request's cleanup raises before the provider closes the sandbox, which then runs until its ttl_s.

  • AsyncSandbox.stop(*, timeout_s=STOP_TIMEOUT_S) runs under anyio.CancelScope(shield=True) and anyio.fail_after(timeout_s). None means no limit, and a timed-out stop raises TimeoutError, which owners treat like any other failed stop. A failed or timed-out stop stays retryable.
  • AsyncSandbox.disconnect() gets the same shield and bound, since a borrower that is cancelled must still release its client.
  • The private terminal sessions that pty.exec opens for a one-shot command close the same way.
  • What a cut-short provider call started no longer outlives it:
    • The Docker, Apptainer and Enroot command runners killed a command's process group only on their own command timeout. A cancelled call now kills the group too, and reaps it shielded and bounded, before the cancellation goes on. This matters because the stop's 120 s limit is shorter than Docker's 180 s command timeout, so a hung docker rm -f would otherwise keep running after the stop gave up.
    • A Docker terminal session is marked closed before its in-container cleanup, so a later close does nothing. Its local release, which kills the docker client and closes the terminal, is now shielded and finishes even when the close's limit ends the in-container cleanup.
  • AsyncSandboxCompose.stop(), which harbor owns, stays shielded and has no limit of its own by default: each member's stop is bounded, and members stop one after another, so a healthy group could need longer than one member's limit. A caller may pass timeout_s. A stop the caller gives up on keeps running in the background and a retry joins it; if it fails there, it is logged and the next stop starts again, rather than being reported as a never-retrieved task exception.
  • LentSandboxes, the swebench sandbox session base, deepswe_external1, opencode_search's agent runs, mm_coding_training's renderer and opencode_sandboxed_agent each had a private shielded stop. They now call sandbox.stop(), and their cancellation tests run the real stop over the fake provider.

The shield holds against anyio cancel scopes, which is how a disconnect cancels a request, and against an enclosing anyio deadline. Callers that bounded a stop with asyncio.timeout or wait_for kept the stop's 120 s default inside their own limit, so a longer configured limit was cut to 120 s. They now pass their limit as timeout_s:

  • officeqa, pdf_analyst_qa and critpt_custom_grader (whose policy allows up to 3600 s)
  • swebench_pro and terminal_bench_2_1
  • the hermes, collab_intel and simple_strands agents
  • the owned stop and the borrowed disconnect in the agent sandbox session
  • the sandbox checkpointer's stops, which also drop their own STOP_TIMEOUT_S
  • scale_swe, which waits for a stop without ever cutting it short, passes None

nemo_gym.sandbox.testing adds a fake provider for tests of code that owns or borrows sandboxes. Tests drive a real AsyncSandbox over it and script the provider's close, so the stop's guarantees hold in the test as in production. The swebench, deepswe_external1 and LentSandboxes tests use it in place of mocking the sandbox's stop. Test fakes of stop() and disconnect() in other servers and agents now take the new keyword argument: agentic_mme, chartography, visual_coding_opencode, gdpval, vibench, enterpriseops_gym, scale_swe, collab_intel, simple_strands, the agent sandbox session, and the agents built on it (codex, pi, hermes, opencode, openclaw, nooa, cline, copilot, goose, kilocode, kimi_code, pool, prime, qwen_code, stirrup and langchain_deepagents). The sandbox guide documents the stop's shield and limit, what a retry after a failed stop does, and the test fake. LentSandboxes and the swebench session base use the one STOP_TIMEOUT_S.

First unit of the sandbox ownership stack. Related: #6236 inlines a shielded stop in swebench's DockerContainer.cleanup; once both land, it can call stop() directly.

How it works

A client that disconnects cancels its request's cancel scope. Before, the stop in the request's cleanup was cancelled with it:

flowchart LR
  subgraph before["Before"]
    direction TB
    a1["Client disconnects"] --> a2["anyio cancels the request scope"]
    a2 --> a3["await sandbox.stop raises CancelledError<br/>before the provider closes the sandbox"]
    a3 --> a4["Sandbox runs until its ttl_s"]
  end
  subgraph after["After"]
    direction TB
    b1["Client disconnects"] --> b2["anyio cancels the request scope"]
    b2 --> b3["sandbox.stop runs shielded"]
    b3 -->|"provider closes it"| b4["Sandbox stopped"]
    b3 -->|"no answer within timeout_s"| b5["TimeoutError,<br/>the stop can be retried"]
  end
  before ~~~ after
Loading

Where the shield lives. Three owners carried a private shielded stop and every other owner had none; now the sandbox's own stop and release carry it:

flowchart LR
  subgraph before["Before"]
    direction TB
    l1["LentSandboxes"] --> p1["private shielded stop"]
    w1["swebench session base"] --> p2["private shielded stop"]
    d1["deepswe_external1"] --> p3["private shielded stop"]
    o1["every other owner"] --> u1["unshielded sandbox.stop"]
  end
  subgraph after["After"]
    direction TB
    l2["LentSandboxes"] --> s2["AsyncSandbox.stop<br/>shielded, bounded by timeout_s"]
    w2["swebench session base"] --> s2
    d2["deepswe_external1"] --> s2
    o2["every other owner"] --> s2
    r2["borrowers"] --> s3["AsyncSandbox.disconnect<br/>shielded, bounded"]
    x2["pty.exec one-shot command"] --> s4["private terminal session close<br/>shielded, bounded"]
    h2["harbor"] --> s5["AsyncSandboxCompose.stop<br/>shielded, a retry joins it"]
  end
  before ~~~ after
Loading

Where this sits in the stack

This is one PR in a stack of PRs that implement Milestone 1 of the sandbox ownership design: every sandbox has one owner, the server that starts it, which stops it on every path, and every other user borrows it. Each PR is one commit, and its base is the branch of the PR before it, so each diff shows only that PR's change. Two lines start from #6410: the stop fixes for servers as they are today (#6411 to #6413), and the owner component servers move onto (#6414 to #6417). The stop fixes are based on main and depend on nothing else. The owner component line (#6414 to #6417) waits on #5266 and is on hold until the session lifecycle RFC, which may change it. The highlighted box is this PR.

flowchart LR
  M["PR 5266<br/>sandbox checkpointer"]
  U1["PR 6410<br/>shielded, bounded<br/>AsyncSandbox.stop"]
  U2["PR 6411<br/>gdpval failed-seed<br/>sandbox"]
  U3["PR 6412<br/>browser record kept<br/>until it closes"]
  U4["PR 6413<br/>vibench shielded<br/>scratch removal"]
  U5["PR 6414<br/>public<br/>OwnedSandboxes"]
  U6["PR 6415<br/>lifecycle<br/>under load"]
  U7["PR 6416<br/>typed<br/>network rule"]
  U8["PR 6417<br/>borrow and<br/>AgentSandboxConfig"]
  U1 --> U2 --> U3 --> U4
  U1 --> U5 --> U6 --> U7 --> U8
  M -.->|"PR 6414 rebases onto it"| U5
  classDef this fill:#fde68a,stroke:#b45309,stroke-width:2px,color:#1f2937
  class U1 this
Loading
  1. fix(sandbox): shield and bound AsyncSandbox.stop and the other releases #6410 (ananthsub/sandbox-shielded-stop): fix(sandbox): shield and bound AsyncSandbox.stop and the other releases (this PR)
  2. fix(gdpval): keep a failed seed's sandbox until a stop succeeds #6411 (ananthsub/sandbox-stop-untracked-owners): fix(gdpval): keep a failed seed's sandbox until a stop succeeds
  3. fix(interactive_browser): drop a browser's record only after it closes #6412 (ananthsub/sandbox-stop-keep-record): fix(interactive_browser): drop a browser's record only after it closes
  4. fix(vibench): remove a released session's scratch files shielded #6413 (ananthsub/sandbox-stop-retried-owners): fix(vibench): remove a released session's scratch files shielded
  5. feat(sandbox): expose the shared OwnedSandboxes owner #6414 (ananthsub/owned-sandboxes): feat(sandbox): make the sandbox checkpointer the public OwnedSandboxes
  6. feat(sandbox): stop, start and export owned sandboxes safely under load #6415 (ananthsub/owned-sandboxes-lifecycle): feat(sandbox): stop, start and export owned sandboxes safely under load
  7. feat(sandbox): apply typed network rules through owner capabilities #6416 (ananthsub/owned-sandboxes-network): feat(sandbox): typed network rule and provider capabilities for owners
  8. feat(sandbox): borrow lent sandboxes and share harness configuration #6417 (ananthsub/sandbox-borrow): feat(agents): borrow lent sandboxes and type the agent's own sandbox

Validation

  • pre-commit run --files <changed files> on the unit's diff (ruff, ruff-format, import-linter, guardwords).
  • pytest -n 16 tests/unit_tests, in a venv with CI's extras. The test_docker_pty.py pid-record tests and the test_tool_telemetry failures happen here on main too: the first depend on the host, and the second fail at the base commit.
  • Server and agent tests of every caller this PR changes or that fakes stop() or disconnect(), including every server and agent built on the agent sandbox session: swebench, deepswe_external1, swebench_pro, terminal_bench_2_1, officeqa, pdf_analyst_qa, critpt_custom_grader's sandbox domain, scale_swe, enterpriseops_gym, harbor, chartography, visual_coding_opencode, agentic_mme, gdpval, vibench, hermes_sandboxed_agent, collab_intel_agent, copilot_agent and simple_strands_agent, plus the servers built on LentSandboxes and the swebench session base.
  • pi_agent's pinned-Pi tests fail locally because the local Pi install runs on Node 20; CI runs them.
  • The new tests cover a stop and a disconnect in a cancelled request, the time limit of each release (stop, disconnect, the one-shot terminal session and a Compose group with a caller's limit), a retry after a time-out, no limit, a failed close, a start cancelled during its upload, the Compose group's shield and retry, and a Compose stop that fails after its caller gave up. Removing any of those shields or limits fails a test. Each caller that passes its own limit has a test that fails if the limit is dropped. Removing the shield from stop() also fails the swebench, deepswe_external1 and LentSandboxes tests.
  • Tests also cover a close limit longer than 120 s reaching both the owned stop and the borrowed disconnect, a stop cut short while docker rm -f hangs (the stand-in command is killed and the retry succeeds), a cancelled Apptainer and Enroot command being killed, and a Docker terminal close whose in-container cleanup outlasts its limit still releasing the client and the terminal. Each fails with its fix removed.

Rollouts

N/A: the stop call is the same; only its behavior under cancellation and a hung provider changes, which unit tests cover.

Compatibility and benchmark impact

stop() and disconnect() take a new keyword-only timeout_s, defaulting to STOP_TIMEOUT_S (120 s), a new public name in nemo_gym.sandbox. A stop that used to hang on an unresponsive provider now raises TimeoutError after 120 s, unless the caller passes a longer timeout_s. A subclass or test fake that overrides stop() without timeout_s breaks for callers that pass it, as LentSandboxes and the call sites above do; the ones in this repository are updated. No benchmark result changes.

Checklist

  • I have read the contributing guidelines.
  • The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs.
  • Tests added or updated and pass locally.
  • Documentation added or updated, or N/A with justification: the sandbox guide is updated.
  • Pre-commit checks pass locally, run on this unit's changed files.
  • New source files include the required Apache-2.0 SPDX header.
  • All commits have DCO sign-off (git commit -s).

@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.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added bug Something isn't working risk:high Autobot PR risk: high labels Nov 18, 2026
@ananthsub
ananthsub force-pushed the ananthsub/sandbox-shielded-stop branch from 0c508c8 to ff939b5 Compare November 18, 2026 23:19
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the area:sandbox Sandbox providers, isolation, and sandbox runtime contracts label Nov 18, 2026
@ananthsub
ananthsub force-pushed the ananthsub/sandbox-shielded-stop branch from ff939b5 to 6ae610b Compare November 19, 2026 05:51
@ananthsub ananthsub changed the title fix(sandbox): add one shielded, bounded stop for sandbox owners fix(sandbox): shield and bound AsyncSandbox.stop and the other releases Nov 19, 2026
@ananthsub
ananthsub force-pushed the ananthsub/sandbox-shielded-stop branch from 6ae610b to 0bac6ac Compare November 19, 2026 15:03
@ananthsub
ananthsub marked this pull request as ready for review November 19, 2026 15:03
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 19, 2026 15:04
@github-actions

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

@svcnvidia-nemo-ci svcnvidia-nemo-ci added the needs-review PR is ready for code review and waiting on a reviewer label Nov 19, 2026

@svcnvidia-nemo-ci svcnvidia-nemo-ci 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.

SHIP WITH CARE

I found three RISKs in timeout cleanup and propagation, plus one documentation NOTE. The new deadlines can leave provider-side CLI processes or host terminal resources behind, and borrowed agent sessions still truncate longer cleanup budgets.

I reviewed all changed files and traced the affected provider and session-release paths. The acceptance checks below are proposed; I did not execute tests in this read-only review.


Inline comments (escaped v1):

  • nemo_gym/sandbox/providers/docker/provider.py line 359: RISK: The new outer deadline bypasses CLI process cleanup.

    For a hung docker rm -f, the new stop() deadline expires after 120 seconds, before Docker's default command timeout of 180 seconds. That cancellation exits _run() without entering its asyncio.TimeoutError handler, so the process-group kill and reap never run. The caller gets TimeoutError, but the CLI process can stay alive. Each retry can leave another process behind. The same gap exists in Apptainer's runner and Enroot's runner.

    Could you make cancellation terminate and reap the subprocess in all three runners, then re-raise cancellation so the facade reports its timeout and keeps the sandbox retryable? Reaping must survive the expired anyio scope and remain bounded. Preserve successful output, existing internal-timeout error messages, Apptainer's graceful-timeout behavior, and already-missing resource deletion success. Changing only the exception tuple is insufficient because subsequent cleanup awaits also run inside the cancelled scope; the complete patch needs provider-specific handling.

    Proposed regression: use a stand-in binary that records its PID and waits indefinitely, then stop a prepared real AsyncSandbox with timeout_s=0.05. Expect TimeoutError and termination of the recorded process. Make the next invocation succeed and verify that retry completes. Exercise the equivalent Apptainer and Enroot cancellation paths, while retaining their ordinary command-timeout assertions. These checks have not been executed.

  • nemo_gym/sandbox/providers/docker/pty.py line 703: RISK: A timed-out private-session close can permanently abandon local terminal resources.

    When a one-shot Docker PTY's in-container cleanup exceeds STOP_TIMEOUT_S, the new helper cancels close(). Its finally calls _end_local() inside the expired anyio scope. Cancellation at the pending-writer or task join can exit before the client is killed and terminal descriptors are closed. _closed was already set, so subsequent close() and abandon() return without finishing release. The provider's stale-session cleanup then discards that session without recovering its resources.

    Could you make DockerPtySession.close() and _end_local() cancellation-safe together? Expiring remote cleanup must not lose ownership of unfinished local cleanup. Finish that release through a bounded cancellation-safe phase, or keep a retryable finalizer that subsequent close/abandon calls join. Preserve recorded-PID validation and the distinction between normal close and container-removal abandon(). Also preserve the ordering that settles pending writers before closing their FD. An unconditional unbounded shield is not a complete correction because it would defeat the new time bound; the exact finalization mechanism needs provider-level changes.

    Proposed regression: drive public one-shot pty.exec() through a real DockerPtySession over a local stand-in process, with in-container cleanup outlasting a shortened deadline. After timeout, require the client to be terminated and descriptors released, or verify that a retained finalizer completes release before the session is discarded. Retain the pending-writer regression: both writers fail before FD reuse, and the fresh terminal receives none of their input. Also retain normal one-shot output and exit codes. These are proposed checks, not executed results.

  • nemo_gym/agents/utils/sandbox_session.py line 544: RISK: Borrowed sessions still lose cleanup budgets longer than 120 seconds.

    The owned branch now forwards timeout, but this borrowed branch calls disconnect() without it. With close(timeout=300) and a provider client release taking 150 seconds, the new default deadline raises after 120 seconds even though the caller allowed 300. Before this change, the enclosing asyncio.timeout(timeout) supplied the limit. This affects harnesses using the shared SandboxSession with borrowed sandboxes.

    Could you forward the limit here too?

                    await self.sandbox.disconnect(timeout_s=timeout)
    

    Keep the enclosing asyncio.timeout(timeout): it still makes directory removal and disconnect share the caller's budget. Keep borrowed release non-destructive, and keep the owned branch using stop(timeout_s=timeout). Update the disconnect side effect in the interruption test to accept the keyword.

    Proposed acceptance: extend test_completed_execution_captures_once_before_release to assert disconnect(timeout_s=...) receives a value above 120 when that larger close budget is supplied. Cover a shorter budget as well. Retain the interruption test's capture-before-release assertion and test_release_failure_retries_without_recollecting's single capture across a failed release and retry. The source invariant is that both owned and borrowed releases receive the caller's timeout. I have not executed these checks.

  • fern/versions/latest/pages/infrastructure/sandbox/index.mdx line 350: NOTE: Could you distinguish teardown failure from client-release failure here? The implementation marks the sandbox stopped before awaiting provider.aclose(). If that release fails or times out, the sandbox stays stopped and retrying stop() retries only client release. The current statement says otherwise.

    Suggested replacement:

    - A failed or timed-out stop raises and remains retryable. If provider teardown already succeeded, the sandbox stays stopped and a later `stop()` retries only client release; otherwise it retries teardown.
    

    Static acceptance: ensure this wording matches the two failure stages without changing their implementation. Retain the existing client-close retry test, which asserts one remote close and two client-release attempts. This is source reasoning, not a test result.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

@ananthsub
ananthsub force-pushed the ananthsub/sandbox-shielded-stop branch from 0bac6ac to bba82a9 Compare November 19, 2026 15:31

@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.

SHIP WITH CARE

Thanks, this is a clear improvement. Moving the shield and the bound into AsyncSandbox.stop() removes the three private helpers, and the semantics hold up:

  • A cancelled caller still gets its cancellation after the stop.
  • A stop that hits timeout_s cancels the provider close and leaves _stopped/_closed unset, so a retry calls close again.
  • A repeated stop is a no-op.
  • A partial stop retries only aclose.
  • The Compose group stop joins an in-flight task.

What needs attention:

  • The red Server suite comes from this PR (inline). SandboxSession.release now passes timeout_s, and three agent test fakes that replace stop with a no-kwarg callable weren't updated: codex_agent, pi_agent and hermes_agent.
  • NOTE: two places still wrap a stop in a native timeout, which the new docs advise against:
    • server_runtime/_checkpoint/sandbox.py (_stop_sandbox, _stop_superseded) still uses asyncio.timeout(STOP_TIMEOUT_S) with its own STOP_TIMEOUT_S = 120.0. That's harmless today, but it's a second constant to keep in sync.
    • The borrowed path of SandboxSession.release still runs disconnect() inside asyncio.timeout(timeout). If timeout exceeds 120 s, the inner default caps it at 120 s; passing disconnect(timeout_s=timeout) would match the owned path.

@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team November 19, 2026 15:32
@ananthsub
ananthsub force-pushed the ananthsub/sandbox-shielded-stop branch from bba82a9 to 9c699e6 Compare November 19, 2026 15:55
@ananthsub
ananthsub requested a review from a team as a code owner November 19, 2026 15:55

@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 5c278b2. The agent test fakes are fixed, and both of my notes are addressed: the checkpointer now uses the shared STOP_TIMEOUT_S via stop(timeout_s=...), and the borrowed release passes disconnect(timeout_s=timeout). The new kill_cancelled_command (kill the group on cancel, then a shielded, bounded reap) closes the gap where a cancelled CLI stop left the command running. Required CI is green; the only failure is the non-blocking compliance check.

@ananthsub
ananthsub merged commit 290641a into main Nov 19, 2026
97 of 99 checks passed
@ananthsub
ananthsub deleted the ananthsub/sandbox-shielded-stop branch November 19, 2026 16:42
adil-a added a commit that referenced this pull request Nov 19, 2026
Resolve the Docker provider conflict with #6410: keep this branch's split of
_run into _run_in_slot and kill a cancelled docker command there, as main does.

Signed-off-by: Adil Asif <[email protected]>
copy-pr-bot Bot pushed a commit that referenced this pull request Nov 21, 2026
… stops

main's #6410 gives AsyncSandbox.stop a timeout_s keyword, and lending now
passes it. The `stopped` fixture (also used by video_qa_rubric's agentic
tests) wraps the real stop, so it takes and forwards the keyword, as
main's other session tests do since #6410.

Signed-off-by: Guo Chen <[email protected]>
d-molinari added a commit that referenced this pull request Nov 21, 2026
Main's #6410 changed the stopped fixture from AsyncSandbox.stop calls to the closes the
provider made. A start cut before the provider returned its sandbox's id leaves nothing
to close, so the hung-start test now expects none, as the ERROR line it checks says.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
d-molinari added a commit that referenced this pull request Nov 21, 2026
…ndbox.stop does

Main's #6410 moved the shielded, bounded stop into AsyncSandbox.stop(timeout_s=...),
which LentSandboxes now calls. The tests' FakeSandbox.stop took no timeout_s and had no
shield, so a seed or close cancelled during a stop failed or hung. FakeSandbox.stop now
takes timeout_s and shields its provider-side _stop, as AsyncSandbox.stop does, and the
tests that slow down, refuse or hang a stop patch _stop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
d-molinari added a commit that referenced this pull request Nov 21, 2026
Main's #6410 changed the stopped fixture from AsyncSandbox.stop calls to the closes the
provider made. A start cut before the provider returned its sandbox's id leaves nothing
to close, so the hung-start test now expects none, as the ERROR line it checks says.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
d-molinari added a commit that referenced this pull request Nov 21, 2026
…ndbox.stop does

Main's #6410 moved the shielded, bounded stop into AsyncSandbox.stop(timeout_s=...),
which LentSandboxes now calls. The tests' FakeSandbox.stop took no timeout_s and had no
shield, so a seed or close cancelled during a stop failed or hung. FakeSandbox.stop now
takes timeout_s and shields its provider-side _stop, as AsyncSandbox.stop does, and the
tests that slow down, refuse or hang a stop patch _stop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
yaoyu-33 added a commit to cg1177/Gym that referenced this pull request Nov 21, 2026
…video QA on stock opencode_agent, with Video-MME v2 / Video-MME agentic benchmarks (NVIDIA-NeMo#6315)

* refactor(video): import nemo_gym names from their public packages

The four video servers and their tests imported the pre-0.8 module paths
(nemo_gym.base_resources_server, config_types, global_config, openai_utils,
server_utils), which still import with a deprecation warning. They now import
each name from its package's public API, as scripts/migrate_imports.py writes
it; `migrate_imports.py --check` reports nothing for these folders.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* feat(video): optional judge-model answer extraction for Video-MME v2, Video-MME and LVBench

Add answer_policy llm_extraction_v1 to the shared video MCQA scoring. A judge model
(any OpenAI-compatible chat model behind a Gym model server, called through call_judge on
/v1/chat/completions) reads which option a final answer gives; the verifier scores that
option against the gold label. The judge sees the prompt's text (no media) and the final
answer (no reasoning), never the gold label.

- A "none" reading is the new outcome no_choice (a measured zero); an empty final answer
  stays no_answer and is not sent.
- A failed judge call or a reply that names no option raises a judge failure: Gym's judge
  failsafe masks the row and keeps it with its answer in the failures file, so the frozen
  cohort counts the task as missing until it is judged again.
- The judged grading, verify response included, runs in observe_llm_judge_grading, so Gym
  binds the graded response and reward to the judge's reply.
- The cohort declares the policy; a server whose cohort uses it refuses to start without
  judge_model_server. The rule policies stay the default and never call a judge.
- prepare_single_turn and prepare.py take a prompt style: boxed (default) or the
  benchmark's bare-letter prompt (videomme_v2, videomme_v1, lvbench).
- New configs <benchmark>_single_turn_llm_extraction.yaml for the three benchmarks: the
  single-turn config plus an openai_model judge (judge_base_url, judge_api_key,
  judge_model_name).

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(video): sandbox image with frame-sampling video tools for OpenCode

Adds resources_servers/video_mcqa/sandbox_image: a Dockerfile and the video
tools it installs in /opt/video-mcqa.

- video_tools.mjs: an OpenCode 1.17.11 plugin with watch_video and view_image.
  It runs `python3 -I -m video_tools.cli` once per call and returns the
  images as tool attachments. It also caps the tool images that one episode
  sends (400 MiB of base64 by default): from the result that would pass the cap
  on, results show a notice in place of their images, the same in every
  request. The tools take plain JSON Schema arguments, so the plugin imports
  only Node's standard library.
- video_tools: watch_video samples the center of each of num_frames equal bins
  of [start, end), takes the latest source frame not after each sampling time,
  resizes by area to the requested long edge rounded down to the model's grid
  (patch_size / downsample_ratio, 28 px by default) and returns
  JPEG frames (quality 95, 4:4:4) with "This is a video:" and one
  "Frame i sampled at t seconds:" line per frame. Per-frame and per-call pixel
  caps refuse a request instead of shrinking it. view_image returns an image
  file unchanged.
- Dockerfile: OpenCode 1.17.11 and its plugin dependencies with the pins of
  visual_coding_opencode, the static FFmpeg 7.0.2 build pinned by SHA-256,
  Python 3.13 with NumPy 2.4.6, Pillow 12.3.0 and Pydantic 2.13.5.

Tests cover the sampling, rounding, limits and text, the decode (seek against
the sequential reference), the program's JSON replies, and the plugin under
Node with a stand-in program. video_mcqa's environment gains NumPy and
Pillow for these tests, and Gym's sandbox extra for the lending that follows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* feat(video): agentic Video-MME v2, Video-MME and LVBench on stock opencode_agent

Adds an agentic config to each of the three benchmarks. The stock
opencode_agent runs each question through a single_agent_turn_legacy
Environment Server, in a sandbox that the benchmark's resources server lends the
episode, as visual_coding_opencode does. The sandbox image is
video_mcqa/sandbox_image, and OpenCode loads its video tools plugin from there.

video_mcqa/sandbox.py lends the sandbox for the video_mcqa and videomme_v2
servers (the videomme_v1 and lvbench servers inherit it). At each seed it:

- refuses (422) a row whose video_binding.source is not a regular file under
  the configured video_roots;
- starts the sandbox with the video tools' configuration (tools.json, from the
  server's video_tools settings) and two checksum lists;
- uploads the video with nemo_gym.sandbox.upload_path;
- runs one command in the sandbox: the image's video tools must have this
  repository's SHA-256 and the video the row's SHA-256 (422 otherwise), then
  the video becomes read-only and the tools check their configuration and
  FFmpeg.

A command result with an error_type or the -1 sentinel, and any other failure,
stops the sandbox and raises, so the Environment Server runs the episode again.
The episode's close stops the sandbox. Grading never reads the sandbox.

The verifiers read the stock agent's outcome: in the agentic setting a failed
or incomplete response that reaches verify is an execution_failure scored 0,
from the response's own status, so a replayed row scores the same. This
replaces the video_execution_failure metadata key, which only the removed
opencode_video_agent set. Single-turn scoring is unchanged.

prepare.py names the video at --sandbox-root/sandbox_path (default /testbed)
in agentic prompts. The three servers gain agentic example rows and cohorts,
and their environments Gym's sandbox extra. READMEs describe the image, the
tools, seeding, the single-upload size limit of the providers and the thinking
switch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* docs(video): agentic example rollouts with Nemotron 3 Nano Omni

One rollout per agentic example row of the VideoMME-v2, VideoMME-v1 and
LVBench servers, from nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16 on
one GPU (vLLM 0.32.0rc1.dev190) through the stock opencode_agent, with
OpenSandbox sandboxes from the video MCQA sandbox image. The shared README
gives the serving flags, the commands and the outcomes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* fix(videomme_v2): let the questions of one group keep their own levels

The Video-MME-v2 annotation gives every question its own level; the first
three questions of a logic group can have a level other than the group's
last question. The official scorer counts per-level accuracy by each
question's own level and scores a group under the level of its last
question.

validate_metric_cohort no longer requires every task level to equal its
group's level. When a cohort lists task_levels, each group's level must be
the level of its last question, /L<n>/raw_acc counts questions by their
task level, /L<n>/nonlinear_score counts groups by the group level, and the
verifier checks a result's level against its task level, so rows that carry
their own question level are scored instead of refused. A cohort without
task_levels behaves as before: each question takes its group's level.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(video): let the sandbox tools read OpenCode's temporary files; drawtext, ripgrep and ImageMagick in the image

- view_image and watch_video also read regular files under video_tools.scratch_roots,
  by default /tmp/opencode: OpenCode's bash tool keeps temporary files there, such
  as frames or contact sheets the model made, and the tools refused them. A
  relative path still starts at the workspace, a symlink that leads out of these
  directories is refused, and the text names such a file by its absolute path.
  The tool descriptions are unchanged.
- The image's FFmpeg 7.0.2 is now the static build of mwader/static-ffmpeg, pinned
  by image digest and by the binaries' SHA-256. watch_video gets the same frames as
  with the previous 7.0.2 build (identical JPEG bytes on 50 requests over 7
  videos); the new build also has libharfbuzz and fontconfig, so the model's
  drawtext works, with fontconfig and DejaVu for its default font.
- ImageMagick for the model's montage and convert, with the URW fonts its labels
  default to, one thread (MAGICK_THREAD_LIMIT=1).
- ripgrep stays (OpenCode's grep and glob run it offline). The build checks
  drawtext, ripgrep and montage.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* revert(video): the video tools and sandbox image before the scratch-file change

This reverts commit cc13a8f: view_image and
watch_video read files under the workspace only, not OpenCode's /tmp/opencode;
the image's FFmpeg 7.0.2 is the johnvansickle.com static build again, without
drawtext; and the image has no ImageMagick. The tree is again the one of
2f336e9.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* feat(openqa-rubric): open-ended video QA graded against each question's rubric

A resources server for open-ended questions about a video, for RL training. The policy sees the video and the
question; a judge model grades the final answer against the question's weighted-points rubric (criteria worth
weight_points that add up to 100, and contradictions with a penalty and a score cap). The judge gets the question,
the rubric and the final answer (no video, reasoning or reference answer) and returns a strict-JSON judgment; the
server accepts it only when its points, applied contradictions and total add up, and the reward is the score / 100.

The judge is any OpenAI-compatible chat model with JSON-schema structured output behind a judge ModelServerRef
(judge_base_url, judge_api_key, judge_model_name), called through call_judge. A rejected judgment, a timeout and a
408/429/5xx reply are tried again up to judge_max_attempts; when every attempt fails, Gym's judge failsafe masks the
row and keeps the answer for judge-only recovery. A failed model call is a masked infrastructure failure; a
single-turn tool call or a failed agent run is an execution failure worth 0. empty_answer_reward (training only)
sets the reward of an attempt that produced output but no final answer; an empty response stays 0, as Gym's agents
require for execution_failure_reward_zero.

Single-turn config (simple_agent, single_agent_turn_legacy) with five invented example rows on video_mcqa's
synthetic clips, task_data schema, prepare_single_turn, README with the RL setup, tests with a scripted judge, and
the component lock. video_mcqa's final_answer_text (the answer after any reasoning block) is now public so this
server shares it.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(video): judge-read answers for the agentic configs

<benchmark>_agentic_llm_extraction.yaml, listed after <benchmark>_agentic.yaml,
gives the agentic resources server the judge model of llm_extraction_v1. The
judge server listens on 127.0.0.1: the lent sandbox may reach every port of the
policy model server's host and must not reach a judge.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(video): agentic rows with the benchmarks' own letter prompts

prepare_agentic and prepare.py --prompt now write an agentic row in a
benchmark's own letter wording: a first line that names the video in the
sandbox (Video: /testbed/videos/<file>), then the single-turn letter prompt.
Read its answers with llm_extraction_v1. The boxed prompt stays the default.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(openqa-rubric): example rollouts with Nemotron 3 Nano Omni

One rollout per example row from nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16 on one GPU (vLLM
0.32.0rc1.dev190+g3f1bcfd82, the model card's video settings, default sampling), the same served model also judging
for this example only. Three answers earn full points, one earns 60 of 100 (the direction but not the square), and on
the counter the model runs out of output tokens (empty_answer, 0); the bar's first judgment was rejected by the
arithmetic check and the second accepted. example_metrics.json from gym dataset collate (example_validation). The
README records the commands. A failed judge attempt is now logged with its reason, never the answer.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(video): agentic Video-MME v2 and Video-MME benchmarks from the authors' annotations

benchmarks/videomme_v2_agentic and benchmarks/videomme_v1_agentic run the
agentic configs of the videomme_v2 and videomme_v1 resources servers with
judge-read answers. prepare.py downloads the authors' annotation at a pinned
revision and checks its SHA-256 (VIDEOMME_V2_PARQUET / VIDEOMME_V1_PARQUET name
a local copy), then binds each question to its video by the SHA-256 that the
source directory's FILES.sha256 lists, reading no video; the resources server
checks that hash in the sandbox. Rows ask in the benchmark's letter wording
after a line that names the video in the sandbox, and a judge model
(gpt-6.1-sol at max reasoning effort by default) reads the chosen option.

Video-MME v2 rows keep each question's own level and the cohort groups the four
questions of each video under the level of the fourth, which the videomme_v2
server accepts with the per-question levels merged from NVIDIA-NeMo#6290.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(openqa-rubric): which video URLs and vLLM judges work

The policy's model server reads the video URL: http(s) and data URLs, or a file:// URL the server may read (vLLM's
--allowed-local-media-path). A vLLM-served judge works through the config's openai_model server, as in the example
rollouts.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(video-qa-rubric): rename openqa_rubric to video_qa_rubric

The server grades open-ended questions about a video and builds on
video_mcqa (its row types, final-answer reading and example clips), so
its name now says so. Renamed: the folder resources_servers/
video_qa_rubric and configs/video_qa_rubric.yaml with the keys
video_qa_rubric, video_qa_rubric_judge, video_qa_rubric_single_turn and
video_qa_rubric_single_turn_environment; the VideoQARubric* classes;
the project gym-resources-servers-video-qa-rubric (uv.lock differs only
in that name); the failure kinds video_qa_rubric:*; the example task
IDs video_qa_rubric:example-N; the rows in README.md and the
environment list.

The example rollouts carry the renamed task IDs, agent and environment
names; the model's input and output, the judgments and the rewards are
unchanged. What the judge receives is unchanged too: the system and
user messages and the structured output's schema and its name.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(video-qa-rubric): import DatasetConfig from nemo_gym.config

nemo_gym.config_types is the path from before 0.8.0; it still imports,
with a deprecation warning, until 0.10.0. Server tests import public
names from the package's public API, as scripts/migrate_imports.py
writes them (its --check is now clean for this server).

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(video-qa-rubric): read failed agent runs from the response status, as video_mcqa does

video_qa_rubric decided an agent run had failed from the
video_execution_failure response metadata key, which only the removed
opencode_video_agent set; this branch removed the key from video_mcqa,
so video_qa_rubric could not even be imported here. It now uses
video_mcqa's response_failure, like the Video-MME v2 server: in the
agentic setting a failed or incomplete response that reaches verify is
an execution_failure scored 0, read from the response's own status, so
a replayed row scores the same. In the single-turn setting a failed
model call stays a masked infrastructure_failure and a tool call an
execution_failure; only the failure reasons now use video_mcqa's
wording.

The failed-run test covers failed and incomplete runs, and a new test
checks that a failed model call is masked only in the single-turn
setting. The README's outcome table says the same.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(video_mcqa): the judge reads each row's question; question sets, frame rows, empty-answer reward

Make video_mcqa the shared base that the video multiple-choice benchmarks and
other question sets fill with data and configuration.

- Each row's verifier_metadata keeps the question as asked: question (its
  text) and options (the option texts in label order). VerifierMetadata and
  the task-data schemas require both, and prepare_single_turn, prepare_agentic
  and prepare.py write them. A row without them is refused: rows prepared
  before this change are prepared again, and nothing falls back to the
  request.
- The llm_extraction_v1 judge builds its prompt from those two fields and the
  final answer only. It no longer reads the text of the model's request
  (scoring.prompt_text is gone), so the video, its frames and anything else in
  the prompt never reach it. videomme_v2 uses the same judge path.
- A cohort may be a question set instead of a benchmark (question_set.py,
  QuestionSetCohort): two to 26 options, task IDs outside the benchmarks'
  scopes, no level or group, accuracy under the set's name. A training set
  runs on the shared verifier this way. The VideoMME-v1 and LVBench servers
  refuse such a cohort.
- prepare_single_turn(..., frames=[(label, image_url), ...]) and
  task.video_parts send a video as labelled frames (input_image parts) instead
  of one input_video part.
- empty_answer_reward (unset by default, which scores 0): the reward of an
  attempt that produced output but no final answer, for example a training
  penalty. Accuracy still counts the attempt as no_answer.
- The shared rows take any number of options; VideoMME-v1 and LVBench check
  their four choices in their own task_data.py.
- configs/video_mcqa_single_turn_llm_extraction.yaml: the shared verifier with
  the answer judge. The committed example rows and rollouts gain the two
  fields; nothing else in them changes.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(video): the agentic example rows keep each question's text and options

NVIDIA-NeMo#6238 makes every video_mcqa row keep the question as asked (question, and
options in label order) in verifier_metadata. The agentic Video-MME v2,
Video-MME and LVBench examples gain the two fields, rebuilt with
prepare_agentic from the same questions; nothing else in the rows or in the
recorded rollouts changes. The benchmark wrappers write them through
prepare_agentic.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(video-qa-rubric): agentic open-ended video questions with OpenCode and the video tools

configs/video_qa_rubric_agentic.yaml runs video_qa_rubric's open-ended questions
agentically, with the agent, sandbox image, video tools and sandbox settings of
the agentic Video-MME v2, Video-MME and LVBench configs: the stock
opencode_agent through a single_agent_turn_legacy Environment Server, a
sandbox per episode that holds the row's video, and the rubric judge on
127.0.0.1 (the sandbox may reach every port of the policy model's host).

- The resources server and its config take video_mcqa's VideoSandboxServer
  bases: with sandbox_provider set, each agentic episode's seed lends a sandbox
  with the row's video, checked by SHA-256; without it nothing changes. The
  sandbox extra joins the server's dependencies (uv.lock regenerated).
- task.prepare_agentic(task_id, question, rubric, video_path=...) builds an
  agentic row's user turn (the question and the video's path in the sandbox,
  never the rubric); the row adds video_binding, which the task-data schema
  now declares.
- data/example_agentic.jsonl: the five example questions and rubrics, each
  clip bound by path instead of inlined.
- Tests: rows, bindings, the committed examples, the config against the
  agentic Video-MME v2 config, and the lent sandbox on the local provider.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* build(video-mcqa): sandbox image on the node:22 image the training data was generated in

The agentic video training data was generated in the full node:22 Debian bookworm image
(node@sha256:363e1587..., node 22.23.3) with the tools added at run time. The sandbox image now
uses that image too, pinned by digest (the node:22.23.3-bookworm tag has been rebuilt since), so
that evaluation and RL run in the same system: its shell, ImageMagick, git, compilers and other
programs.

The former final stage becomes the `tools` stage, unchanged apart from its base, which is now
pinned by digest so that Python's files stay the same; the last stage copies its /usr/local
(Python 3.13 with NumPy, Pillow and Pydantic, FFmpeg 7.0.2), /opt/opencode, /opt/video-mcqa and
/usr/bin/rg into the node image as root-owned files, sets the same thread limits and locale, and
makes /testbed and /testbed/work. The video tools, OpenCode and their pins are unchanged.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(video-mcqa): agentic OpenCode keeps its own tools and runs sh, as in the training data

The agentic configs of videomme_v2, videomme_v1, lvbench and video_qa_rubric now run OpenCode's
tools as the rollouts our agentic video training data came from did, so the model sees the same tools
at evaluation and in RL:

- No `tools` overrides: OpenCode offers its own tools, webfetch and task included, besides
  watch_video and view_image. webfetch fails in a sandbox that reaches only the model server, as it
  did then. OpenCode 1.17.11 offers websearch only with a search provider enabled, so it is not
  offered, as then.
- The lent sandbox sets SHELL=/bin/sh (`sandbox_config.env`). OpenCode's shell tool runs commands
  with the shell SHELL names, bash when it is unset, and names that shell in the tool's
  description ("Shell: sh").

With these configs, the tools in the first request of an OpenCode 1.17.11 run in the sandbox image
have the names, descriptions and parameters of the tool block of the training trajectories.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(video-mcqa): agentic OpenCode ends a run on a third identical tool call, as in the training data

The agentic configs of videomme_v2, videomme_v1, lvbench and video_qa_rubric set OpenCode's doom_loop
permission to ask, OpenCode's default and the setting of the rollouts our agentic video training data
came from, instead of allow.

OpenCode 1.17.11 asks for doom_loop when the last three parts of one model response are calls of the
same tool with identical input. `opencode run` rejects every request that would ask, and this
rejection ends the run without an answer, as it did when the training data was generated. With
allow, the third call ran and the model went on. The same call repeated across separate responses
does not reach that check, with either setting.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* fix(video-mcqa): the sandbox tools read OpenCode's temporary files; drawtext, montage and annotate work in the image

- view_image and watch_video also read regular files under video_tools.scratch_roots,
  by default /tmp/opencode: OpenCode's bash tool keeps temporary files there, such as
  frames or contact sheets the model made, and the tools refused them. A relative path
  still starts at the workspace, a symlink that leads out of these directories is
  refused, and the text names such a file by its absolute path. The tool descriptions
  are unchanged.
- FFmpeg 7.0.2 is now the static build of mwader/static-ffmpeg, pinned by image digest
  and by the binaries' SHA-256. watch_video gets the same frames as with the
  johnvansickle.com 7.0.2 build (identical JPEG bytes on 50 requests); the new build
  also has libharfbuzz and fontconfig, so the model's drawtext works, with the image's
  DejaVu font.
- The image gets the URW fonts that ImageMagick's labels and annotations default to
  (Helvetica). Without them, montage and convert -annotate abort in the node:22 image.
- The build checks drawtext, ripgrep, montage with a label and convert -annotate.

The tool code is that of cc13a8f, which c44e06a reverted; the node:22 image already
has ImageMagick, fontconfig and DejaVu.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* fix(video-mcqa): agentic OpenCode no longer offers webfetch

The agentic configs of videomme_v2, videomme_v1, lvbench and video_qa_rubric turn off
OpenCode's webfetch tool (`tools: {webfetch: false}`), so the model is not offered it. The
lent sandbox reaches only the policy model server, so every webfetch call failed with a
transport error, as in the rollouts our agentic video training data came from.

The other tools stay as in that training data: bash (on sh), edit, glob, grep, read, skill,
task, todowrite and write, with watch_video and view_image. doom_loop stays at ask and
compaction off.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* feat(video-mcqa): watch_video's text for frames attached after the tool results

For an OpenAI-compatible provider, OpenCode sends the images of all the tool
results of one response after those results, in one user message ("Attached
media from tool result:"), in call order. watch_video's text was written for
images placed right after their labels: "This is a video:" and one "Frame i
sampled at t seconds:" line per frame, each ending in a colon that the model
sees nothing after.

watch_video's text now says what was sampled (the frame count, the number of
distinct frames when the video holds some, the video, the window, the spacing,
the frame size and the visual tokens), that the frames are attached after the
tool results in this order, and each frame's sampling time:

  Sampled 42 frames of videos/a.mp4 from 120.00 s to 240.00 s, one every 2.86 s, at 616×336 (11088 visual tokens).
  The 42 frames are attached after the tool results, in this order:
  Frame 1: 121.43 s
  Frame 2: 124.29 s
  ...

The lines about source PTS and the largest gap between distinct source frames
are dropped. watch_video's description adds that the images of several tool
calls in one response follow in call order. The frame rules and the frames are
unchanged; view_image is unchanged.

The text and the description come from the image's video tools, so the sandbox
image needs a rebuild: the seed check refuses an image whose tools differ.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* fix(video-mcqa): saved rule-scored results without the question; a non-string judge choice

Aggregating results saved before rows carried the question and its options
raised TypeError: VerifierMetadata required both. They are optional again,
given together or not at all. The rule policies and aggregation never read
them, so such boxed_only_v1 results aggregate and replay as before. Under
llm_extraction_v1 the judge reads them, so that policy refuses a row
without them before any judge call.

A judge reply {"choice": null} was read as the string "None" and scored
as no_choice, a measured zero. A choice that is not a string is now an
unusable reply: Gym's judge failsafe masks the row for rejudging.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* fix(video-qa-rubric): grade the last assistant message; empty_answer_reward only rewards no answer

With empty_answer_reward set, the answer also had to be the last thing the
model produced, and that rule missed a response ending on reasoning after
the answer: [answer, reasoning] graded the answer instead of giving the
configured reward. The rule is gone: the final answer is always the text
of the last assistant message after its reasoning, whatever comes after
it, as in video_mcqa. empty_answer_reward stays, as video_mcqa's option:
the reward of an attempt that produced output but no final answer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* feat(video-mcqa): cap the tool images an episode sends by count too

Every request sends the episode's earlier tool images again. The plugin
capped them by max_tool_media_bytes (400 MiB of base64) only, so small
frames could pass that and still exceed the model server's image limit
per request: two watch_video results of 150 small frames make a request
with 300 images, over the 256 that the README's vLLM example allowed.

max_tool_media_images (ToolSettings, default 8192) caps their number the
same way: from the tool result whose images would pass either limit on,
each result shows the notice in place of its images, the same in every
request, and earlier results keep theirs. The README's vLLM example now
takes 8192 images per request, and the README says to change the two
together.

The plugin and video_tools/contract.py are files of the sandbox image, so
the image needs a rebuild: the seed check refuses an image whose tools
differ.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* fix(video-mcqa): read a relative cohort_manifest from the Gym root

The agentic Video-MME benchmarks (benchmarks/videomme_v1_agentic,
benchmarks/videomme_v2_agentic) default the cohort manifest to their
prepared file, benchmarks/<name>/data/<name>_cohort.json, a path from the
Gym root. Gym starts each resources server in its own directory, and the
servers read the path as given, so a run with the benchmarks' default
stopped at server start with FileNotFoundError. Runs that passed an
absolute path were not affected.

The video_mcqa server (videomme_v1, lvbench, question sets) and the
videomme_v2 server now resolve the path with _resolve_under_cwd_or_install,
as tavily_search and hle_web_tools resolve their files: an absolute path is
used as given, and a relative one is looked up under NEMO_GYM_EXTRA_ROOTS,
the working directory, then the Gym root. The sandbox image's files do
not change, so an image built from the previous commit still passes the
seed check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* build(video-qa-rubric): refresh component lock against main

Signed-off-by: yaoyu-33 <[email protected]>

* build(video-mcqa): refresh the video servers' component locks against main

Relocked with uv 0.13.4 on top of main's upgraded locks (NVIDIA-NeMo#6528):
lvbench, video_mcqa, videomme_v1, videomme_v2 and video_qa_rubric. Each
lock only gains the packages of this branch's dependencies (nemo-gym's
sandbox extra, and pillow 12.3.0 in video_mcqa); python-dateutil is
2.9.0.post0 again, as in main's other locks with the sandbox extra.

Signed-off-by: Guo Chen <[email protected]>

* test(video-mcqa): pass the stop limit through the fixture that counts stops

main's NVIDIA-NeMo#6410 gives AsyncSandbox.stop a timeout_s keyword, and lending now
passes it. The `stopped` fixture (also used by video_qa_rubric's agentic
tests) wraps the real stop, so it takes and forwards the keyword, as
main's other session tests do since NVIDIA-NeMo#6410.

Signed-off-by: Guo Chen <[email protected]>

* test(video-mcqa): run the agentic Video-MME prepare tests with the video_mcqa server tests

The tests import both benchmarks' prepare.py and, through them, the
video_mcqa and videomme_v2 server modules, so in the core suite they
added those modules to the core coverage measurement. The video_mcqa
server tests, which cover those modules, now run them. The tests are
unchanged.

Signed-off-by: Guo Chen <[email protected]>

---------

Signed-off-by: Guo Chen <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: yaoyu-33 <[email protected]>
ehosseiniasl pushed a commit to ehosseiniasl/Gym that referenced this pull request Nov 21, 2026
…swer level grading and video media preloaded in the sandbox image (NVIDIA-NeMo#6460)

* refactor(video): import nemo_gym names from their public packages

The four video servers and their tests imported the pre-0.8 module paths
(nemo_gym.base_resources_server, config_types, global_config, openai_utils,
server_utils), which still import with a deprecation warning. They now import
each name from its package's public API, as scripts/migrate_imports.py writes
it; `migrate_imports.py --check` reports nothing for these folders.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* feat(video): optional judge-model answer extraction for Video-MME v2, Video-MME and LVBench

Add answer_policy llm_extraction_v1 to the shared video MCQA scoring. A judge model
(any OpenAI-compatible chat model behind a Gym model server, called through call_judge on
/v1/chat/completions) reads which option a final answer gives; the verifier scores that
option against the gold label. The judge sees the prompt's text (no media) and the final
answer (no reasoning), never the gold label.

- A "none" reading is the new outcome no_choice (a measured zero); an empty final answer
  stays no_answer and is not sent.
- A failed judge call or a reply that names no option raises a judge failure: Gym's judge
  failsafe masks the row and keeps it with its answer in the failures file, so the frozen
  cohort counts the task as missing until it is judged again.
- The judged grading, verify response included, runs in observe_llm_judge_grading, so Gym
  binds the graded response and reward to the judge's reply.
- The cohort declares the policy; a server whose cohort uses it refuses to start without
  judge_model_server. The rule policies stay the default and never call a judge.
- prepare_single_turn and prepare.py take a prompt style: boxed (default) or the
  benchmark's bare-letter prompt (videomme_v2, videomme_v1, lvbench).
- New configs <benchmark>_single_turn_llm_extraction.yaml for the three benchmarks: the
  single-turn config plus an openai_model judge (judge_base_url, judge_api_key,
  judge_model_name).

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(video): sandbox image with frame-sampling video tools for OpenCode

Adds resources_servers/video_mcqa/sandbox_image: a Dockerfile and the video
tools it installs in /opt/video-mcqa.

- video_tools.mjs: an OpenCode 1.17.11 plugin with watch_video and view_image.
  It runs `python3 -I -m video_tools.cli` once per call and returns the
  images as tool attachments. It also caps the tool images that one episode
  sends (400 MiB of base64 by default): from the result that would pass the cap
  on, results show a notice in place of their images, the same in every
  request. The tools take plain JSON Schema arguments, so the plugin imports
  only Node's standard library.
- video_tools: watch_video samples the center of each of num_frames equal bins
  of [start, end), takes the latest source frame not after each sampling time,
  resizes by area to the requested long edge rounded down to the model's grid
  (patch_size / downsample_ratio, 28 px by default) and returns
  JPEG frames (quality 95, 4:4:4) with "This is a video:" and one
  "Frame i sampled at t seconds:" line per frame. Per-frame and per-call pixel
  caps refuse a request instead of shrinking it. view_image returns an image
  file unchanged.
- Dockerfile: OpenCode 1.17.11 and its plugin dependencies with the pins of
  visual_coding_opencode, the static FFmpeg 7.0.2 build pinned by SHA-256,
  Python 3.13 with NumPy 2.4.6, Pillow 12.3.0 and Pydantic 2.13.5.

Tests cover the sampling, rounding, limits and text, the decode (seek against
the sequential reference), the program's JSON replies, and the plugin under
Node with a stand-in program. video_mcqa's environment gains NumPy and
Pillow for these tests, and Gym's sandbox extra for the lending that follows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* feat(video): agentic Video-MME v2, Video-MME and LVBench on stock opencode_agent

Adds an agentic config to each of the three benchmarks. The stock
opencode_agent runs each question through a single_agent_turn_legacy
Environment Server, in a sandbox that the benchmark's resources server lends the
episode, as visual_coding_opencode does. The sandbox image is
video_mcqa/sandbox_image, and OpenCode loads its video tools plugin from there.

video_mcqa/sandbox.py lends the sandbox for the video_mcqa and videomme_v2
servers (the videomme_v1 and lvbench servers inherit it). At each seed it:

- refuses (422) a row whose video_binding.source is not a regular file under
  the configured video_roots;
- starts the sandbox with the video tools' configuration (tools.json, from the
  server's video_tools settings) and two checksum lists;
- uploads the video with nemo_gym.sandbox.upload_path;
- runs one command in the sandbox: the image's video tools must have this
  repository's SHA-256 and the video the row's SHA-256 (422 otherwise), then
  the video becomes read-only and the tools check their configuration and
  FFmpeg.

A command result with an error_type or the -1 sentinel, and any other failure,
stops the sandbox and raises, so the Environment Server runs the episode again.
The episode's close stops the sandbox. Grading never reads the sandbox.

The verifiers read the stock agent's outcome: in the agentic setting a failed
or incomplete response that reaches verify is an execution_failure scored 0,
from the response's own status, so a replayed row scores the same. This
replaces the video_execution_failure metadata key, which only the removed
opencode_video_agent set. Single-turn scoring is unchanged.

prepare.py names the video at --sandbox-root/sandbox_path (default /testbed)
in agentic prompts. The three servers gain agentic example rows and cohorts,
and their environments Gym's sandbox extra. READMEs describe the image, the
tools, seeding, the single-upload size limit of the providers and the thinking
switch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* docs(video): agentic example rollouts with Nemotron 3 Nano Omni

One rollout per agentic example row of the VideoMME-v2, VideoMME-v1 and
LVBench servers, from nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16 on
one GPU (vLLM 0.32.0rc1.dev190) through the stock opencode_agent, with
OpenSandbox sandboxes from the video MCQA sandbox image. The shared README
gives the serving flags, the commands and the outcomes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* fix(videomme_v2): let the questions of one group keep their own levels

The Video-MME-v2 annotation gives every question its own level; the first
three questions of a logic group can have a level other than the group's
last question. The official scorer counts per-level accuracy by each
question's own level and scores a group under the level of its last
question.

validate_metric_cohort no longer requires every task level to equal its
group's level. When a cohort lists task_levels, each group's level must be
the level of its last question, /L<n>/raw_acc counts questions by their
task level, /L<n>/nonlinear_score counts groups by the group level, and the
verifier checks a result's level against its task level, so rows that carry
their own question level are scored instead of refused. A cohort without
task_levels behaves as before: each question takes its group's level.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(video): let the sandbox tools read OpenCode's temporary files; drawtext, ripgrep and ImageMagick in the image

- view_image and watch_video also read regular files under video_tools.scratch_roots,
  by default /tmp/opencode: OpenCode's bash tool keeps temporary files there, such
  as frames or contact sheets the model made, and the tools refused them. A
  relative path still starts at the workspace, a symlink that leads out of these
  directories is refused, and the text names such a file by its absolute path.
  The tool descriptions are unchanged.
- The image's FFmpeg 7.0.2 is now the static build of mwader/static-ffmpeg, pinned
  by image digest and by the binaries' SHA-256. watch_video gets the same frames as
  with the previous 7.0.2 build (identical JPEG bytes on 50 requests over 7
  videos); the new build also has libharfbuzz and fontconfig, so the model's
  drawtext works, with fontconfig and DejaVu for its default font.
- ImageMagick for the model's montage and convert, with the URW fonts its labels
  default to, one thread (MAGICK_THREAD_LIMIT=1).
- ripgrep stays (OpenCode's grep and glob run it offline). The build checks
  drawtext, ripgrep and montage.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* revert(video): the video tools and sandbox image before the scratch-file change

This reverts commit cc13a8f: view_image and
watch_video read files under the workspace only, not OpenCode's /tmp/opencode;
the image's FFmpeg 7.0.2 is the johnvansickle.com static build again, without
drawtext; and the image has no ImageMagick. The tree is again the one of
2f336e9.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* feat(openqa-rubric): open-ended video QA graded against each question's rubric

A resources server for open-ended questions about a video, for RL training. The policy sees the video and the
question; a judge model grades the final answer against the question's weighted-points rubric (criteria worth
weight_points that add up to 100, and contradictions with a penalty and a score cap). The judge gets the question,
the rubric and the final answer (no video, reasoning or reference answer) and returns a strict-JSON judgment; the
server accepts it only when its points, applied contradictions and total add up, and the reward is the score / 100.

The judge is any OpenAI-compatible chat model with JSON-schema structured output behind a judge ModelServerRef
(judge_base_url, judge_api_key, judge_model_name), called through call_judge. A rejected judgment, a timeout and a
408/429/5xx reply are tried again up to judge_max_attempts; when every attempt fails, Gym's judge failsafe masks the
row and keeps the answer for judge-only recovery. A failed model call is a masked infrastructure failure; a
single-turn tool call or a failed agent run is an execution failure worth 0. empty_answer_reward (training only)
sets the reward of an attempt that produced output but no final answer; an empty response stays 0, as Gym's agents
require for execution_failure_reward_zero.

Single-turn config (simple_agent, single_agent_turn_legacy) with five invented example rows on video_mcqa's
synthetic clips, task_data schema, prepare_single_turn, README with the RL setup, tests with a scripted judge, and
the component lock. video_mcqa's final_answer_text (the answer after any reasoning block) is now public so this
server shares it.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(video): judge-read answers for the agentic configs

<benchmark>_agentic_llm_extraction.yaml, listed after <benchmark>_agentic.yaml,
gives the agentic resources server the judge model of llm_extraction_v1. The
judge server listens on 127.0.0.1: the lent sandbox may reach every port of the
policy model server's host and must not reach a judge.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(video): agentic rows with the benchmarks' own letter prompts

prepare_agentic and prepare.py --prompt now write an agentic row in a
benchmark's own letter wording: a first line that names the video in the
sandbox (Video: /testbed/videos/<file>), then the single-turn letter prompt.
Read its answers with llm_extraction_v1. The boxed prompt stays the default.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(openqa-rubric): example rollouts with Nemotron 3 Nano Omni

One rollout per example row from nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16 on one GPU (vLLM
0.32.0rc1.dev190+g3f1bcfd82, the model card's video settings, default sampling), the same served model also judging
for this example only. Three answers earn full points, one earns 60 of 100 (the direction but not the square), and on
the counter the model runs out of output tokens (empty_answer, 0); the bar's first judgment was rejected by the
arithmetic check and the second accepted. example_metrics.json from gym dataset collate (example_validation). The
README records the commands. A failed judge attempt is now logged with its reason, never the answer.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(video): agentic Video-MME v2 and Video-MME benchmarks from the authors' annotations

benchmarks/videomme_v2_agentic and benchmarks/videomme_v1_agentic run the
agentic configs of the videomme_v2 and videomme_v1 resources servers with
judge-read answers. prepare.py downloads the authors' annotation at a pinned
revision and checks its SHA-256 (VIDEOMME_V2_PARQUET / VIDEOMME_V1_PARQUET name
a local copy), then binds each question to its video by the SHA-256 that the
source directory's FILES.sha256 lists, reading no video; the resources server
checks that hash in the sandbox. Rows ask in the benchmark's letter wording
after a line that names the video in the sandbox, and a judge model
(gpt-6.1-sol at max reasoning effort by default) reads the chosen option.

Video-MME v2 rows keep each question's own level and the cohort groups the four
questions of each video under the level of the fourth, which the videomme_v2
server accepts with the per-question levels merged from NVIDIA-NeMo#6290.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(openqa-rubric): which video URLs and vLLM judges work

The policy's model server reads the video URL: http(s) and data URLs, or a file:// URL the server may read (vLLM's
--allowed-local-media-path). A vLLM-served judge works through the config's openai_model server, as in the example
rollouts.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(video-qa-rubric): rename openqa_rubric to video_qa_rubric

The server grades open-ended questions about a video and builds on
video_mcqa (its row types, final-answer reading and example clips), so
its name now says so. Renamed: the folder resources_servers/
video_qa_rubric and configs/video_qa_rubric.yaml with the keys
video_qa_rubric, video_qa_rubric_judge, video_qa_rubric_single_turn and
video_qa_rubric_single_turn_environment; the VideoQARubric* classes;
the project gym-resources-servers-video-qa-rubric (uv.lock differs only
in that name); the failure kinds video_qa_rubric:*; the example task
IDs video_qa_rubric:example-N; the rows in README.md and the
environment list.

The example rollouts carry the renamed task IDs, agent and environment
names; the model's input and output, the judgments and the rewards are
unchanged. What the judge receives is unchanged too: the system and
user messages and the structured output's schema and its name.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(video-qa-rubric): import DatasetConfig from nemo_gym.config

nemo_gym.config_types is the path from before 0.8.0; it still imports,
with a deprecation warning, until 0.10.0. Server tests import public
names from the package's public API, as scripts/migrate_imports.py
writes them (its --check is now clean for this server).

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(video-qa-rubric): read failed agent runs from the response status, as video_mcqa does

video_qa_rubric decided an agent run had failed from the
video_execution_failure response metadata key, which only the removed
opencode_video_agent set; this branch removed the key from video_mcqa,
so video_qa_rubric could not even be imported here. It now uses
video_mcqa's response_failure, like the Video-MME v2 server: in the
agentic setting a failed or incomplete response that reaches verify is
an execution_failure scored 0, read from the response's own status, so
a replayed row scores the same. In the single-turn setting a failed
model call stays a masked infrastructure_failure and a tool call an
execution_failure; only the failure reasons now use video_mcqa's
wording.

The failed-run test covers failed and incomplete runs, and a new test
checks that a failed model call is masked only in the single-turn
setting. The README's outcome table says the same.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(video_mcqa): the judge reads each row's question; question sets, frame rows, empty-answer reward

Make video_mcqa the shared base that the video multiple-choice benchmarks and
other question sets fill with data and configuration.

- Each row's verifier_metadata keeps the question as asked: question (its
  text) and options (the option texts in label order). VerifierMetadata and
  the task-data schemas require both, and prepare_single_turn, prepare_agentic
  and prepare.py write them. A row without them is refused: rows prepared
  before this change are prepared again, and nothing falls back to the
  request.
- The llm_extraction_v1 judge builds its prompt from those two fields and the
  final answer only. It no longer reads the text of the model's request
  (scoring.prompt_text is gone), so the video, its frames and anything else in
  the prompt never reach it. videomme_v2 uses the same judge path.
- A cohort may be a question set instead of a benchmark (question_set.py,
  QuestionSetCohort): two to 26 options, task IDs outside the benchmarks'
  scopes, no level or group, accuracy under the set's name. A training set
  runs on the shared verifier this way. The VideoMME-v1 and LVBench servers
  refuse such a cohort.
- prepare_single_turn(..., frames=[(label, image_url), ...]) and
  task.video_parts send a video as labelled frames (input_image parts) instead
  of one input_video part.
- empty_answer_reward (unset by default, which scores 0): the reward of an
  attempt that produced output but no final answer, for example a training
  penalty. Accuracy still counts the attempt as no_answer.
- The shared rows take any number of options; VideoMME-v1 and LVBench check
  their four choices in their own task_data.py.
- configs/video_mcqa_single_turn_llm_extraction.yaml: the shared verifier with
  the answer judge. The committed example rows and rollouts gain the two
  fields; nothing else in them changes.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(video): the agentic example rows keep each question's text and options

NVIDIA-NeMo#6238 makes every video_mcqa row keep the question as asked (question, and
options in label order) in verifier_metadata. The agentic Video-MME v2,
Video-MME and LVBench examples gain the two fields, rebuilt with
prepare_agentic from the same questions; nothing else in the rows or in the
recorded rollouts changes. The benchmark wrappers write them through
prepare_agentic.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(video-qa-rubric): agentic open-ended video questions with OpenCode and the video tools

configs/video_qa_rubric_agentic.yaml runs video_qa_rubric's open-ended questions
agentically, with the agent, sandbox image, video tools and sandbox settings of
the agentic Video-MME v2, Video-MME and LVBench configs: the stock
opencode_agent through a single_agent_turn_legacy Environment Server, a
sandbox per episode that holds the row's video, and the rubric judge on
127.0.0.1 (the sandbox may reach every port of the policy model's host).

- The resources server and its config take video_mcqa's VideoSandboxServer
  bases: with sandbox_provider set, each agentic episode's seed lends a sandbox
  with the row's video, checked by SHA-256; without it nothing changes. The
  sandbox extra joins the server's dependencies (uv.lock regenerated).
- task.prepare_agentic(task_id, question, rubric, video_path=...) builds an
  agentic row's user turn (the question and the video's path in the sandbox,
  never the rubric); the row adds video_binding, which the task-data schema
  now declares.
- data/example_agentic.jsonl: the five example questions and rubrics, each
  clip bound by path instead of inlined.
- Tests: rows, bindings, the committed examples, the config against the
  agentic Video-MME v2 config, and the lent sandbox on the local provider.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* build(video-mcqa): sandbox image on the node:22 image the training data was generated in

The agentic video training data was generated in the full node:22 Debian bookworm image
(node@sha256:363e1587..., node 22.23.3) with the tools added at run time. The sandbox image now
uses that image too, pinned by digest (the node:22.23.3-bookworm tag has been rebuilt since), so
that evaluation and RL run in the same system: its shell, ImageMagick, git, compilers and other
programs.

The former final stage becomes the `tools` stage, unchanged apart from its base, which is now
pinned by digest so that Python's files stay the same; the last stage copies its /usr/local
(Python 3.13 with NumPy, Pillow and Pydantic, FFmpeg 7.0.2), /opt/opencode, /opt/video-mcqa and
/usr/bin/rg into the node image as root-owned files, sets the same thread limits and locale, and
makes /testbed and /testbed/work. The video tools, OpenCode and their pins are unchanged.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(video-mcqa): agentic OpenCode keeps its own tools and runs sh, as in the training data

The agentic configs of videomme_v2, videomme_v1, lvbench and video_qa_rubric now run OpenCode's
tools as the rollouts our agentic video training data came from did, so the model sees the same tools
at evaluation and in RL:

- No `tools` overrides: OpenCode offers its own tools, webfetch and task included, besides
  watch_video and view_image. webfetch fails in a sandbox that reaches only the model server, as it
  did then. OpenCode 1.17.11 offers websearch only with a search provider enabled, so it is not
  offered, as then.
- The lent sandbox sets SHELL=/bin/sh (`sandbox_config.env`). OpenCode's shell tool runs commands
  with the shell SHELL names, bash when it is unset, and names that shell in the tool's
  description ("Shell: sh").

With these configs, the tools in the first request of an OpenCode 1.17.11 run in the sandbox image
have the names, descriptions and parameters of the tool block of the training trajectories.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(video-mcqa): agentic OpenCode ends a run on a third identical tool call, as in the training data

The agentic configs of videomme_v2, videomme_v1, lvbench and video_qa_rubric set OpenCode's doom_loop
permission to ask, OpenCode's default and the setting of the rollouts our agentic video training data
came from, instead of allow.

OpenCode 1.17.11 asks for doom_loop when the last three parts of one model response are calls of the
same tool with identical input. `opencode run` rejects every request that would ask, and this
rejection ends the run without an answer, as it did when the training data was generated. With
allow, the third call ran and the model went on. The same call repeated across separate responses
does not reach that check, with either setting.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* fix(video-mcqa): the sandbox tools read OpenCode's temporary files; drawtext, montage and annotate work in the image

- view_image and watch_video also read regular files under video_tools.scratch_roots,
  by default /tmp/opencode: OpenCode's bash tool keeps temporary files there, such as
  frames or contact sheets the model made, and the tools refused them. A relative path
  still starts at the workspace, a symlink that leads out of these directories is
  refused, and the text names such a file by its absolute path. The tool descriptions
  are unchanged.
- FFmpeg 7.0.2 is now the static build of mwader/static-ffmpeg, pinned by image digest
  and by the binaries' SHA-256. watch_video gets the same frames as with the
  johnvansickle.com 7.0.2 build (identical JPEG bytes on 50 requests); the new build
  also has libharfbuzz and fontconfig, so the model's drawtext works, with the image's
  DejaVu font.
- The image gets the URW fonts that ImageMagick's labels and annotations default to
  (Helvetica). Without them, montage and convert -annotate abort in the node:22 image.
- The build checks drawtext, ripgrep, montage with a label and convert -annotate.

The tool code is that of cc13a8f, which c44e06a reverted; the node:22 image already
has ImageMagick, fontconfig and DejaVu.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* fix(video-mcqa): agentic OpenCode no longer offers webfetch

The agentic configs of videomme_v2, videomme_v1, lvbench and video_qa_rubric turn off
OpenCode's webfetch tool (`tools: {webfetch: false}`), so the model is not offered it. The
lent sandbox reaches only the policy model server, so every webfetch call failed with a
transport error, as in the rollouts our agentic video training data came from.

The other tools stay as in that training data: bash (on sh), edit, glob, grep, read, skill,
task, todowrite and write, with watch_video and view_image. doom_loop stays at ask and
compaction off.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* feat(video-qa-rubric): reference-answer level grading, per-subset scores, and video media preloaded in the sandbox image

video_qa_rubric: each row's verifier_metadata.grading names its protocol.
Rows without it keep the weighted-points rubric, its request model and
its checks unchanged. A reference_levels row carries a reference answer
and a rubric of any JSON object; the judge reads them with the question
and the final answer through the server's reference_levels settings (a
question set's own system prompt and user template, and its top level)
and must reply with exactly {"score", "reason"}; the reward is the
level over the top level. A server without these settings refuses such
rows. Rows that name a subset also get each subset's mean rubric score
and the mean over the subsets in the metrics. The row builders take the
text after the video, the protocol, the reference answer and the subset,
and an agentic row's whole text for videos the image already holds.

video_mcqa: an agentic row can name media that its sandbox image
already holds (preloaded_media: the image's name in the server's
sandbox_preloaded_images, the image's catalog and its SHA-256, and host
files to copy in). The seed starts the sandbox from that image, uploads
nothing, and checks in the sandbox the video tools, the catalog's
SHA-256 and the size of every file it lists, moves the catalog out of
the model's media root and makes the copied files read-only. Each image
lends its own sandboxes; rows with an uploaded video are unchanged.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(benchmarks): MM-Lifelong v1.1 single-turn and agentic as video_qa_rubric question sets

mm_lifelong_v1_1: the 1,023 questions of day_test, week_test and
month_val with frozen rubrics. prepare.py reads the annotations at a
pinned revision of the Hugging Face dataset (downloading what is
missing) and checks them against the release's checksums, whose own
SHA-256 is pinned; the model sees each split as one MP4 of 256 frames at
the centres of equal bins, taken from the release's frame cache that the
user downloads (each shard read is checked), with the question as it
is. grading.yaml is the dataset's grader on video_qa_rubric's
reference_levels protocol: its prompt and template, the reference
answer, 0-5 levels, one completion; each split is a subset, so the
metrics give the split scores and their mean.

mm_lifelong_v1_1_agentic: the same questions answered by OpenCode with
the video tools in a sandbox whose image holds the split's original
videos (preloaded media). The videos are not redistributed:
sandbox_image/build.py checks the user's copy against the sizes and
SHA-256 the Hub keeps, writes the image's catalog and the dataset
runner's catalog that the model reads, and builds one image per split on
the video tools' image. Rows ask with the runner's description of the
inputs and its time-coordinates note.

The grader prompt and the runner's note are MIT-licensed text of the
dataset; the notice is in third-party-notices.md and ATTRIBUTIONS.md.

Signed-off-by: Guo Chen <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* feat(video-mcqa): watch_video's text for frames attached after the tool results

For an OpenAI-compatible provider, OpenCode sends the images of all the tool
results of one response after those results, in one user message ("Attached
media from tool result:"), in call order. watch_video's text was written for
images placed right after their labels: "This is a video:" and one "Frame i
sampled at t seconds:" line per frame, each ending in a colon that the model
sees nothing after.

watch_video's text now says what was sampled (the frame count, the number of
distinct frames when the video holds some, the video, the window, the spacing,
the frame size and the visual tokens), that the frames are attached after the
tool results in this order, and each frame's sampling time:

  Sampled 42 frames of videos/a.mp4 from 120.00 s to 240.00 s, one every 2.86 s, at 616×336 (11088 visual tokens).
  The 42 frames are attached after the tool results, in this order:
  Frame 1: 121.43 s
  Frame 2: 124.29 s
  ...

The lines about source PTS and the largest gap between distinct source frames
are dropped. watch_video's description adds that the images of several tool
calls in one response follow in call order. The frame rules and the frames are
unchanged; view_image is unchanged.

The text and the description come from the image's video tools, so the sandbox
image needs a rebuild: the seed check refuses an image whose tools differ.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* fix(video-mcqa): saved rule-scored results without the question; a non-string judge choice

Aggregating results saved before rows carried the question and its options
raised TypeError: VerifierMetadata required both. They are optional again,
given together or not at all. The rule policies and aggregation never read
them, so such boxed_only_v1 results aggregate and replay as before. Under
llm_extraction_v1 the judge reads them, so that policy refuses a row
without them before any judge call.

A judge reply {"choice": null} was read as the string "None" and scored
as no_choice, a measured zero. A choice that is not a string is now an
unusable reply: Gym's judge failsafe masks the row for rejudging.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* fix(video-qa-rubric): grade the last assistant message; empty_answer_reward only rewards no answer

With empty_answer_reward set, the answer also had to be the last thing the
model produced, and that rule missed a response ending on reasoning after
the answer: [answer, reasoning] graded the answer instead of giving the
configured reward. The rule is gone: the final answer is always the text
of the last assistant message after its reasoning, whatever comes after
it, as in video_mcqa. empty_answer_reward stays, as video_mcqa's option:
the reward of an attempt that produced output but no final answer.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* feat(video-mcqa): cap the tool images an episode sends by count too

Every request sends the episode's earlier tool images again. The plugin
capped them by max_tool_media_bytes (400 MiB of base64) only, so small
frames could pass that and still exceed the model server's image limit
per request: two watch_video results of 150 small frames make a request
with 300 images, over the 256 that the README's vLLM example allowed.

max_tool_media_images (ToolSettings, default 8192) caps their number the
same way: from the tool result whose images would pass either limit on,
each result shows the notice in place of its images, the same in every
request, and earlier results keep theirs. The README's vLLM example now
takes 8192 images per request, and the README says to change the two
together.

The plugin and video_tools/contract.py are files of the sandbox image, so
the image needs a rebuild: the seed check refuses an image whose tools
differ.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* fix(mm-lifelong-v1-1): the image gets only the release's videos; overall score wording

build.py built the image from the local videos/<domain>/ folder itself,
so each week day folder went in whole, with any local file that the
verified catalog does not list (a partial download, notes). The build now
reads a temporary folder in the output directory that holds only the
catalog's files, as hard links to the local copy (copies when the output
directory is on another file system), with the source folders' times. The
script lists the other local files and leaves them out.

Without such files the image is the same as before: from invented week
and month videos, the old and the new script give the same layers on one
builder, and on fresh builds the same entries apart from the parent
folders' build times, which also differ between two fresh builds of the
old script.

mm_lifelong_v1_1/config.yaml said the dataset's overall score is the mean
of the split scores. It pools all 1,023 questions (mean/rubric_score); the
mean of the three split scores is a separate metric. Comment only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* fix(video-mcqa): read a relative cohort_manifest from the Gym root

The agentic Video-MME benchmarks (benchmarks/videomme_v1_agentic,
benchmarks/videomme_v2_agentic) default the cohort manifest to their
prepared file, benchmarks/<name>/data/<name>_cohort.json, a path from the
Gym root. Gym starts each resources server in its own directory, and the
servers read the path as given, so a run with the benchmarks' default
stopped at server start with FileNotFoundError. Runs that passed an
absolute path were not affected.

The video_mcqa server (videomme_v1, lvbench, question sets) and the
videomme_v2 server now resolve the path with _resolve_under_cwd_or_install,
as tavily_search and hle_web_tools resolve their files: an absolute path is
used as given, and a relative one is looked up under NEMO_GYM_EXTRA_ROOTS,
the working directory, then the Gym root. The sandbox image's files do
not change, so an image built from the previous commit still passes the
seed check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Guo Chen <[email protected]>

* build(video-qa-rubric): refresh component lock against main

Signed-off-by: yaoyu-33 <[email protected]>

* build(video-mcqa): refresh the video servers' component locks against main

Relocked with uv 0.13.4 on top of main's upgraded locks (NVIDIA-NeMo#6528):
lvbench, video_mcqa, videomme_v1, videomme_v2 and video_qa_rubric. Each
lock only gains the packages of this branch's dependencies (nemo-gym's
sandbox extra, and pillow 12.3.0 in video_mcqa); python-dateutil is
2.9.0.post0 again, as in main's other locks with the sandbox extra.

Signed-off-by: Guo Chen <[email protected]>

* test(video-mcqa): pass the stop limit through the fixture that counts stops

main's NVIDIA-NeMo#6410 gives AsyncSandbox.stop a timeout_s keyword, and lending now
passes it. The `stopped` fixture (also used by video_qa_rubric's agentic
tests) wraps the real stop, so it takes and forwards the keyword, as
main's other session tests do since NVIDIA-NeMo#6410.

Signed-off-by: Guo Chen <[email protected]>

* test(video-mcqa): run the agentic Video-MME prepare tests with the video_mcqa server tests

The tests import both benchmarks' prepare.py and, through them, the
video_mcqa and videomme_v2 server modules, so in the core suite they
added those modules to the core coverage measurement. The video_mcqa
server tests, which cover those modules, now run them. The tests are
unchanged.

Signed-off-by: Guo Chen <[email protected]>

* test(video-qa-rubric): run the MM-Lifelong v1.1 tests with the video_qa_rubric server tests

The tests import the benchmarks' prepare.py and the video_qa_rubric
server modules, so in the core suite they added those modules to the
core coverage measurement. The video_qa_rubric server tests, which
cover those modules, now run them. The tests are unchanged; they keep
their repository root at parents[3].

Signed-off-by: Guo Chen <[email protected]>

---------

Signed-off-by: Guo Chen <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: yaoyu-33 <[email protected]>
yaoyu-33 added a commit that referenced this pull request Nov 24, 2026
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]>
yaoyu-33 added a commit that referenced this pull request Nov 24, 2026
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]>
yaoyu-33 added a commit that referenced this pull request Nov 24, 2026
- 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]>
yaoyu-33 added a commit that referenced this pull request Nov 24, 2026
…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]>
d-molinari added a commit that referenced this pull request Nov 24, 2026
Main's #6410 changed the stopped fixture from AsyncSandbox.stop calls to the closes the
provider made. A start cut before the provider returned its sandbox's id leaves nothing
to close, so the hung-start test now expects none, as the ERROR line it checks says.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
d-molinari added a commit that referenced this pull request Nov 24, 2026
…ndbox.stop does

Main's #6410 moved the shielded, bounded stop into AsyncSandbox.stop(timeout_s=...),
which LentSandboxes now calls. The tests' FakeSandbox.stop took no timeout_s and had no
shield, so a seed or close cancelled during a stop failed or hung. FakeSandbox.stop now
takes timeout_s and shields its provider-side _stop, as AsyncSandbox.stop does, and the
tests that slow down, refuse or hang a stop patch _stop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
nemo-autobot-origin Bot pushed a commit to svcnemo-autobot/Gym that referenced this pull request Nov 25, 2026
…ad (NVIDIA-NeMo#6415)

* fix(sandbox): add one shielded, bounded stop for sandbox owners

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]>

* feat(sandbox): make the sandbox checkpointer the public OwnedSandboxes

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]>

* feat(sandbox): stop, start and export owned sandboxes safely under load

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]>

* fix(sandbox): build no provider for a refused owner config

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]>

* fix(sandbox): stop a create cancelled inside the provider's start

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]>

* fix(sandbox): bound a whole owned stop by one limit and require ttl_s

- 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
  NVIDIA-NeMo#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]>

* style(sandbox): sort the swebench checkpoint server's imports

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): do not cut a queued owned stop short, and start nothing 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]>

* fix(sandbox): settle cancelled starts and forks, and stop running sandboxes first at shutdown

- A cancelled caller now waits for its start through any further
  cancellation, bounded by the spec's readiness wait plus a stop's limit
  (a slow Enroot create took longer than one stop's limit), and stops the
  sandbox the start produced before the cancellation goes on. Restore forks
  take the same path: a restore cancelled inside a fork's create left the
  fork running untracked.
- aclose() stops the sandboxes that are running before it waits for creates
  still pending, which may now take their whole start to settle.
- The rollback of a failed start is a module function again, so a test that
  drives AsyncSandbox.start_with_setup over a mocked sandbox sees its stop.
  The litmus_agent and deepswe_external1 tests expect the start's error,
  with the failed stop as its context, as this PR documents.
- The parallelism description and the superseded stop's comment say what
  the code does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): try each key once per aclose

The shutdown's second pass, after pending creates settle, stops only the keys
the first pass did not try, so a key whose stop failed stays tracked for the
next call as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): defer owner checkpoint state and preserve old imports

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): keep the old checkpointer name and let non-exporting servers own sandboxes

- SandboxSessionCheckpointer, exported from nemo_gym.server_runtime before the
  rename, resolves to OwnedSandboxes with a deprecation warning (removed in 0.10.0).
- self.sandboxes no longer needs checkpoint.state_dir: a server that never exports,
  such as an agent, gets an instance without a snapshot index, and only export says
  the directory is missing. A relative or unwritable state_dir is still refused,
  now before the provider is built.
- New lines in the moved module and its tests use X | None.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): serialize discard with pending starts and hide unready entries

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): show an owned sandbox only once it is ready, and let discard wait for its keys

- get(), `in`, access() and export now agree: a sandbox still starting, or one whose
  start failed and whose stop failed too, is none of theirs. keys still lists it, so a
  stop or aclose stops it.
- discard() takes each key's lock, in the order a restore takes them, so a key whose
  create is still starting is discarded once the start ends instead of leaving the
  sandbox running untracked.
- Glossary: owner concurrency.
- Test start_with_setup's own rollback: a setup that raises and a stop that fails.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): assert unready entries remain cleanup-only

Signed-off-by: yaoyu-33 <[email protected]>

* fix(swebench): forget tracked sandboxes after their stop

Signed-off-by: yaoyu-33 <[email protected]>

* style(swebench): format checkpoint tracking guard

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): validate owner metadata before constructing a provider

Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): shorten the stop limit where a cancelled restore's fork hangs on purpose

The cancelled restore now lets the fork run for the stop limit before it cuts it
short, so the test waited the full 120 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): keep metadata validation in the network layer

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format provider resolver cases

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): keep each provider field's snapshots apart and retry a failed provider close

- The owner on a server's other provider field kept its snapshot index and names
  under "<server>.<field>", which a server named that way also uses: the two
  releases then deleted each other's retained snapshots. Such an owner now keeps
  its index under <server>/providers/<field>/ and hashes "<server>/<field>" into
  its snapshot names; no server name has a "/". The sandbox_provider owner keeps
  its paths and names.
- The provider counts as closed only once its close succeeded, one close at a
  time, so aclose retries a close that failed or was cancelled and never repeats
  one that succeeded.
- Regressions: overlapping snapshot ids across the two owners, an unwritable
  state_dir from a real checkpoint config, and failed, cancelled and concurrent
  provider closes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): publish owned starts only after file setup succeeds

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): register the checkpoint compatibility alias once

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format the server ownership declaration

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): track and throttle cancelled start rollbacks

Signed-off-by: yaoyu-33 <[email protected]>

* docs(sandbox): say the Environment Server owns the attempt's sandbox and others borrow it

The owner description named a Resources Server as a lender of the attempt's sandbox on equal terms with the
Environment Server. The Environment Server owns the sandbox an attempt runs in and lends it to the agent and to
the Resources Server; a Resources Server owns a sandbox only for a grader that runs code in an attempt without one.
Today's Resources lenders and agent-owned harness sandboxes are described as what moves onto it. An export also
waits for borrowers' commands, not only the owner's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): check named provider references at server startup

Resolve an explicitly configured sandbox_provider while loading the server config so an absent named block stops launch before a rollout is dispatched. Preserve defaults used by optional backends and keep provider construction lazy. Report only the type when a reference points at a scalar setting.

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): stop cancelled starts once the provider returns a handle

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): resolve named providers when launching the server

Allow standalone server schemas to be inspected before the operator composes a provider block. Check the reference before launching a worker or returning from a dry run. Exercise both the schema-only load and actual startup with the same configuration.

Signed-off-by: yaoyu-33 <[email protected]>

---------

Signed-off-by: Ananth Subramaniam <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Signed-off-by: svcnemo-autobot <[email protected]>
Co-authored-by: yaoyu-33 <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: svcnemo-autobot <[email protected]>
ehosseiniasl pushed a commit to ehosseiniasl/Gym that referenced this pull request Nov 25, 2026
…VIDIA-NeMo#6416)

* fix(sandbox): add one shielded, bounded stop for sandbox owners

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]>

* feat(sandbox): make the sandbox checkpointer the public OwnedSandboxes

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]>

* feat(sandbox): stop, start and export owned sandboxes safely under load

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]>

* feat(sandbox): typed network rule and provider capabilities for owners

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]>

* fix(sandbox): build no provider for a refused owner config

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]>

* fix(sandbox): stop a create cancelled inside the provider's start

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]>

* fix(sandbox): bound a whole owned stop by one limit and require ttl_s

- 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
  NVIDIA-NeMo#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]>

* style(sandbox): sort the swebench checkpoint server's imports

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): do not cut a queued owned stop short, and start nothing 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]>

* fix(sandbox): true reconnect capabilities, critpt specs, and a glossary 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]>

* fix(sandbox): keep the provider check after the dry-run return

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]>

* fix(sandbox): settle cancelled starts and forks, and stop running sandboxes first at shutdown

- A cancelled caller now waits for its start through any further
  cancellation, bounded by the spec's readiness wait plus a stop's limit
  (a slow Enroot create took longer than one stop's limit), and stops the
  sandbox the start produced before the cancellation goes on. Restore forks
  take the same path: a restore cancelled inside a fork's create left the
  fork running untracked.
- aclose() stops the sandboxes that are running before it waits for creates
  still pending, which may now take their whole start to settle.
- The rollback of a failed start is a module function again, so a test that
  drives AsyncSandbox.start_with_setup over a mocked sandbox sees its stop.
  The litmus_agent and deepswe_external1 tests expect the start's error,
  with the failed stop as its context, as this PR documents.
- The parallelism description and the superseded stop's comment say what
  the code does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): try each key once per aclose

The shutdown's second pass, after pending creates settle, stops only the keys
the first pass did not try, so a key whose stop failed stays tracked for the
next call as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): check the provider before the dry-run return

A dry run now reports a rule the provider cannot apply, as it reports an
unsupported num_workers. The dry-run test's mocked config sets no
sandbox_provider.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): defer owner checkpoint state and preserve old imports

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): keep the old checkpointer name and let non-exporting servers own sandboxes

- SandboxSessionCheckpointer, exported from nemo_gym.server_runtime before the
  rename, resolves to OwnedSandboxes with a deprecation warning (removed in 0.10.0).
- self.sandboxes no longer needs checkpoint.state_dir: a server that never exports,
  such as an agent, gets an instance without a snapshot index, and only export says
  the directory is missing. A relative or unwritable state_dir is still refused,
  now before the provider is built.
- New lines in the moved module and its tests use X | None.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): serialize discard with pending starts and hide unready entries

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): validate portable network access before serving requests

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): show an owned sandbox only once it is ready, and let discard wait for its keys

- get(), `in`, access() and export now agree: a sandbox still starting, or one whose
  start failed and whose stop failed too, is none of theirs. keys still lists it, so a
  stop or aclose stops it.
- discard() takes each key's lock, in the order a restore takes them, so a key whose
  create is still starting is discarded once the start ends instead of leaving the
  sandbox running untracked.
- Glossary: owner concurrency.
- Test start_with_setup's own rollback: a setup that raises and a stop that fails.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* docs(sandbox): clarify portable network options and legacy subclass settings

Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): assert unready entries remain cleanup-only

Signed-off-by: yaoyu-33 <[email protected]>

* fix(swebench): forget tracked sandboxes after their stop

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): check the declared sandbox blocks at startup and tighten the network rule

- A server lists the blocks it starts through self.sandboxes in
  owned_sandbox_blocks, with the config field naming each block's provider.
  Startup checks each listed block against that provider, and refuses a
  restricted rule in any other SandboxConfig of the config, nested ones too,
  since nothing would apply it. This replaces picking provider fields by their
  name suffix.
- Startup logs the other servers that share a host a rule allows.
- allowed_hosts takes a host name, '*.' and a domain, or an IP address or CIDR
  block; a URL, a port, a path or a loopback address is refused.
- A subclass's own network setting refuses model_server, tool_servers and
  allowed_hosts, which would do nothing beside it.
- SandboxConfig.spec takes NetworkRuleOptions built for the block's own rule,
  so no plain mapping stands in for a restricted rule.
- E2B applies every rule through its network_policy mapping; Docker's
  no_network also checks the provider's create.extra_run_args.
- Glossary: network stays the name; the per-server network_access fields are
  deprecated as servers move onto the block's rule.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(swebench): format checkpoint tracking guard

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): validate owner metadata before constructing a provider

Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): shorten the stop limit where a cancelled restore's fork hangs on purpose

The cancelled restore now lets the fork run for the stop limit before it cuts it
short, so the test waited the full 120 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format network rule validation

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): keep metadata validation in the network layer

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): validate provider metadata before client creation

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format provider resolver cases

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): read the global config at startup only when a sandbox block is declared or lent

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): keep each provider field's snapshots apart and retry a failed provider close

- The owner on a server's other provider field kept its snapshot index and names
  under "<server>.<field>", which a server named that way also uses: the two
  releases then deleted each other's retained snapshots. Such an owner now keeps
  its index under <server>/providers/<field>/ and hashes "<server>/<field>" into
  its snapshot names; no server name has a "/". The sandbox_provider owner keeps
  its paths and names.
- The provider counts as closed only once its close succeeded, one close at a
  time, so aclose retries a close that failed or was cancelled and never repeats
  one that succeeded.
- Regressions: overlapping snapshot ids across the two owners, an unwritable
  state_dir from a real checkpoint config, and failed, cancelled and concurrent
  provider closes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): update network fixtures and use a real dry-run config

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format renamed grader network fixture

Signed-off-by: yaoyu-33 <[email protected]>

* test(server): supply a real global config to the dry-run fixture

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): publish owned starts only after file setup succeeds

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): register the checkpoint compatibility alias once

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format the server ownership declaration

Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): retain refusal checks after stack integration

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): preserve Docker argument-list execution

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): track and throttle cancelled start rollbacks

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): require declared OpenSandbox egress enforcement

Signed-off-by: yaoyu-33 <[email protected]>

* docs(sandbox): say the Environment Server owns the attempt's sandbox and others borrow it

The owner description named a Resources Server as a lender of the attempt's sandbox on equal terms with the
Environment Server. The Environment Server owns the sandbox an attempt runs in and lends it to the agent and to
the Resources Server; a Resources Server owns a sandbox only for a grader that runs code in an attempt without one.
Today's Resources lenders and agent-owned harness sandboxes are described as what moves onto it. An export also
waits for borrowers' commands, not only the owner's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* docs(sandbox): say a lending server lends to the Resources Server as well as the agent

lends_sandboxes described lending to agents only. An Environment Server lends an attempt's sandbox to the agent for
its turn and to the Resources Server for /verify, and both borrowers need a provider that reconnects.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): check named provider references at server startup

Resolve an explicitly configured sandbox_provider while loading the server config so an absent named block stops launch before a rollout is dispatched. Preserve defaults used by optional backends and keep provider construction lazy. Report only the type when a reference points at a scalar setting.

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): stop cancelled starts once the provider returns a handle

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): resolve named providers when launching the server

Allow standalone server schemas to be inspected before the operator composes a provider block. Check the reference before launching a worker or returning from a dry run. Exercise both the schema-only load and actual startup with the same configuration.

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): reject blank model server references and run rollback coverage

Signed-off-by: yaoyu-33 <[email protected]>

---------

Signed-off-by: Ananth Subramaniam <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Co-authored-by: yaoyu-33 <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
yaoyu-33 added a commit to yaoyu-33/Gym that referenced this pull request Nov 25, 2026
…VIDIA-NeMo#6417)

* fix(sandbox): add one shielded, bounded stop for sandbox owners

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]>

* feat(sandbox): make the sandbox checkpointer the public OwnedSandboxes

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]>

* feat(sandbox): stop, start and export owned sandboxes safely under load

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]>

* feat(sandbox): typed network rule and provider capabilities for owners

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]>

* feat(agents): borrow lent sandboxes and type the agent's own sandbox

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]>

* fix(sandbox): build no provider for a refused owner config

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]>

* fix(sandbox): stop a create cancelled inside the provider's start

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]>

* fix(sandbox): bound a whole owned stop by one limit and require ttl_s

- 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
  NVIDIA-NeMo#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]>

* style(sandbox): sort the swebench checkpoint server's imports

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): do not cut a queued owned stop short, and start nothing 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]>

* fix(sandbox): true reconnect capabilities, critpt specs, and a glossary 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]>

* fix(agents): let SandboxSession release a borrowed sandbox, and borrow from server_runtime

- BorrowedSandbox.stop and disconnect dropped the timeout_s keyword that
  AsyncSandbox.stop and disconnect take since NVIDIA-NeMo#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]>

* fix(sandbox): keep the provider check after the dry-run return

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]>

* fix(sandbox): settle cancelled starts and forks, and stop running sandboxes first at shutdown

- A cancelled caller now waits for its start through any further
  cancellation, bounded by the spec's readiness wait plus a stop's limit
  (a slow Enroot create took longer than one stop's limit), and stops the
  sandbox the start produced before the cancellation goes on. Restore forks
  take the same path: a restore cancelled inside a fork's create left the
  fork running untracked.
- aclose() stops the sandboxes that are running before it waits for creates
  still pending, which may now take their whole start to settle.
- The rollback of a failed start is a module function again, so a test that
  drives AsyncSandbox.start_with_setup over a mocked sandbox sees its stop.
  The litmus_agent and deepswe_external1 tests expect the start's error,
  with the failed stop as its context, as this PR documents.
- The parallelism description and the superseded stop's comment say what
  the code does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): try each key once per aclose

The shutdown's second pass, after pending creates settle, stops only the keys
the first pass did not try, so a key whose stop failed stays tracked for the
next call as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): check the provider before the dry-run return

A dry run now reports a rule the provider cannot apply, as it reports an
unsupported num_workers. The dry-run test's mocked config sets no
sandbox_provider.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): defer owner checkpoint state and preserve old imports

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): keep the old checkpointer name and let non-exporting servers own sandboxes

- SandboxSessionCheckpointer, exported from nemo_gym.server_runtime before the
  rename, resolves to OwnedSandboxes with a deprecation warning (removed in 0.10.0).
- self.sandboxes no longer needs checkpoint.state_dir: a server that never exports,
  such as an agent, gets an instance without a snapshot index, and only export says
  the directory is missing. A relative or unwritable state_dir is still refused,
  now before the provider is built.
- New lines in the moved module and its tests use X | None.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): serialize discard with pending starts and hide unready entries

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): validate portable network access before serving requests

Signed-off-by: yaoyu-33 <[email protected]>

* refactor(sandbox): share harness config independently of sandbox ownership

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): show an owned sandbox only once it is ready, and let discard wait for its keys

- get(), `in`, access() and export now agree: a sandbox still starting, or one whose
  start failed and whose stop failed too, is none of theirs. keys still lists it, so a
  stop or aclose stops it.
- discard() takes each key's lock, in the order a restore takes them, so a key whose
  create is still starting is discarded once the start ends instead of leaving the
  sandbox running untracked.
- Glossary: owner concurrency.
- Test start_with_setup's own rollback: a setup that raises and a stop that fails.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* docs(sandbox): clarify portable network options and legacy subclass settings

Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): assert unready entries remain cleanup-only

Signed-off-by: yaoyu-33 <[email protected]>

* fix(swebench): forget tracked sandboxes after their stop

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): check the declared sandbox blocks at startup and tighten the network rule

- A server lists the blocks it starts through self.sandboxes in
  owned_sandbox_blocks, with the config field naming each block's provider.
  Startup checks each listed block against that provider, and refuses a
  restricted rule in any other SandboxConfig of the config, nested ones too,
  since nothing would apply it. This replaces picking provider fields by their
  name suffix.
- Startup logs the other servers that share a host a rule allows.
- allowed_hosts takes a host name, '*.' and a domain, or an IP address or CIDR
  block; a URL, a port, a path or a loopback address is refused.
- A subclass's own network setting refuses model_server, tool_servers and
  allowed_hosts, which would do nothing beside it.
- SandboxConfig.spec takes NetworkRuleOptions built for the block's own rule,
  so no plain mapping stands in for a restricted rule.
- E2B applies every rule through its network_policy mapping; Docker's
  no_network also checks the provider's create.extra_run_args.
- Glossary: network stays the name; the per-server network_access fields are
  deprecated as servers move onto the block's rule.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(swebench): format checkpoint tracking guard

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): validate owner metadata before constructing a provider

Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): shorten the stop limit where a cancelled restore's fork hangs on purpose

The cancelled restore now lets the fork run for the stop limit before it cuts it
short, so the test waited the full 120 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format network rule validation

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): accept argv in the borrowed exec contract

Signed-off-by: yaoyu-33 <[email protected]>

* fix(agents): name the harness sandbox config for what it is, and say what a borrow does not enforce

- AgentSandboxConfig becomes HarnessSandboxConfig: the sandbox a harness runs in,
  whether an Environment Server starts and lends it or an agent starts its own
  because nothing was lent. Its spec() takes the owner's NetworkRuleOptions, and
  its docstring says an adopting agent refuses its own network_access beside the
  config's network.
- The borrow module says the refusals are advisory, the raw .provider included,
  and that the repository check follows once agents use borrow().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): keep metadata validation in the network layer

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): validate provider metadata before client creation

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): sort harness config facade import

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format provider resolver cases

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): read the global config at startup only when a sandbox block is declared or lent

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): keep each provider field's snapshots apart and retry a failed provider close

- The owner on a server's other provider field kept its snapshot index and names
  under "<server>.<field>", which a server named that way also uses: the two
  releases then deleted each other's retained snapshots. Such an owner now keeps
  its index under <server>/providers/<field>/ and hashes "<server>/<field>" into
  its snapshot names; no server name has a "/". The sandbox_provider owner keeps
  its paths and names.
- The provider counts as closed only once its close succeeded, one close at a
  time, so aclose retries a close that failed or was cancelled and never repeats
  one that succeeded.
- Regressions: overlapping snapshot ids across the two owners, an unwritable
  state_dir from a real checkpoint config, and failed, cancelled and concurrent
  provider closes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(agents): end the harness sandbox config test with one newline

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): update network fixtures and use a real dry-run config

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format renamed grader network fixture

Signed-off-by: yaoyu-33 <[email protected]>

* test(server): supply a real global config to the dry-run fixture

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): publish owned starts only after file setup succeeds

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): register the checkpoint compatibility alias once

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format the server ownership declaration

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format borrowed command signature

Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): retain refusal checks after stack integration

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): preserve Docker argument-list execution

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): track and throttle cancelled start rollbacks

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): require declared OpenSandbox egress enforcement

Signed-off-by: yaoyu-33 <[email protected]>

* docs(sandbox): say the Environment Server owns the attempt's sandbox and others borrow it

The owner description named a Resources Server as a lender of the attempt's sandbox on equal terms with the
Environment Server. The Environment Server owns the sandbox an attempt runs in and lends it to the agent and to
the Resources Server; a Resources Server owns a sandbox only for a grader that runs code in an attempt without one.
Today's Resources lenders and agent-owned harness sandboxes are described as what moves onto it. An export also
waits for borrowers' commands, not only the owner's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* docs(sandbox): say a lending server lends to the Resources Server as well as the agent

lends_sandboxes described lending to agents only. An Environment Server lends an attempt's sandbox to the agent for
its turn and to the Resources Server for /verify, and both borrowers need a provider that reconnects.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): a Resources Server grades in a sandbox it never started

The Environment Server owns an attempt's sandbox and lends it; the Resources Server borrows it for /verify. The test
lends from one owner and borrows with only the access and the borrower's own copy of the merged config: the
provider block is found by the name the access carries, commands run in the lent working directory, the borrower
cannot stop the sandbox, and only the owner's stop ends it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): check named provider references at server startup

Resolve an explicitly configured sandbox_provider while loading the server config so an absent named block stops launch before a rollout is dispatched. Preserve defaults used by optional backends and keep provider construction lazy. Report only the type when a reference points at a scalar setting.

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): stop cancelled starts once the provider returns a handle

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): resolve named providers when launching the server

Allow standalone server schemas to be inspected before the operator composes a provider block. Check the reference before launching a worker or returning from a dry run. Exercise both the schema-only load and actual startup with the same configuration.

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): reject blank model server references and run rollback coverage

Signed-off-by: yaoyu-33 <[email protected]>

---------

Signed-off-by: Ananth Subramaniam <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Co-authored-by: yaoyu-33 <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
ko3n1g pushed a commit to ko3n1g/Gym that referenced this pull request Nov 30, 2026
…oxed harnesses (NVIDIA-NeMo#5010)

* feat(single_agent_turn): drive the agent one step at a time and end the episode on the task state

A resources server whose task ends through its state, rather than through one tool's call, can now have its
episode end right after the step that ended the task. OfficeEnv's task ends when its user app's task row leaves
pending, which several operations reach, depending on how a row exposes its apps.

- single_agent_turn: max_episode_steps drives the agent one step per activation, up to that many steps, and
  end_on_task_state reads the resources session's task state between steps (GET /task_state, ResourcesTaskState
  in nemo_gym.server_runtime). Each step's failure report is kept. The server checks at startup that its agent keeps
  a session, runs the tools it calls and stops after one step. Driven episodes take part in checkpoints as restarts
  (BaseEnvironmentServer.checkpoint_mode_in_effect).
- simple_agent: with x-ng-agent-episode-step-limit, a step stopped by its own one-step limit counts as completed
  unless it is the episode's last, and the session keeps one invocation for the episode, as the agent's own loop
  does, instead of one per step that repeats the whole history.
- OfficeEnv: GET /task_state answers ResourcesTaskState; close_tools_on_task_end refuses the calls a step makes after
  the one that ended its task; its rows route by taskset to single_agent_turn with the step loop on, and the config
  allows only the simple agent. A retired attempt no longer keeps its episode, so its replacement can seed the same
  session ID. The server runs OfficeEnv 1.14.0 (1.13.0 at least), with its example rows emitted again.

Signed-off-by: Daniele Molinari <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(single_agent_turn): run the step loop's tests in the core suite, and keep a simple_agent subclass in step

CI on the step loop found two things:
- agentic_turn_simulation_agent overrides simple_agent's _create_episode, which now takes
  step_limit_owned_by_caller. The override accepts it; only an agent session sets it, and this agent
  refuses those.
- The core coverage gate counts single_agent_turn's and simple_agent's app.py, but the step loop's tests
  ran in the server suite only. They move to the core suite unchanged, and simple_agent's step limit and
  invocation folding get core tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(single_agent_turn): import each name in the moved step-loop tests from the module that defines it

Tests under tests/ import from the defining module, not a package's public API, and
test_the_librarys_tests_import_from_the_module_that_defines_each_name failed on the two files this PR moved
into the core suite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(simple_agent): one step per activation that names the episode's step limit, counted by its index

With x-ng-agent-episode-step-limit, the agent takes one step (one model call and the tool calls it makes) whatever
its max_steps says, so a pairing no longer needs max_steps: 1, which composition drops when --agent-type
simple_agent replaces the environment's agent. Requests without the header run as before.

- The step is the activation's index (x-ng-agent-activation), which such a caller sends with every step, not the
  count of requests, so a step resent after a dropped connection is not counted as the next one.
- The session keeps the model server's cookies from step to step, so the episode keeps one model server session.
- A step that raises ends the episode's folded invocation as failed (or incomplete when cancelled), not with the
  completed status of the step before.
- The step keywords go to _create_episode only with the header, so an override that predates them keeps working;
  agentic_turn_simulation_agent's override no longer needs to accept one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(single_agent_turn): drive only agents that take one step per activation, and keep what the steps did

- STEP_DRIVEN_AGENT_TYPES (nemo_gym.config, beside AGENT_SESSION_AGENT_TYPES) lists the agent types that take one
  step per activation that names the episode's step limit: simple_agent. The startup check refuses any other type,
  such as hermes_agent or browsecomp_agent, which keep a session but run their own loop in an activation; a unit
  test keeps the list in step with the agent apps. The check no longer reads max_steps, and reads execute_tools as
  the agent's config does, so a string "false" is false.
- A failure after a step completed keeps the completed steps, their output and summed usage, as its partial
  response, unless it already carries one; a failure before the first reply has none.
- An episode that runs out of steps with every step calling a tool says so in its reply's metadata
  (ng_termination_reason: max_episode_steps). Its status stays the last step's: incomplete_details names only the
  model's own cutoffs, and an incomplete reply would read as malformed to rollout recovery.
- The task state is not read after the last step, which ends the episode either way.
- GET /task_state answering 404 with failure_kind session_lost ends the episode, which goes on to /verify and its
  masked lost-session result, as when a tool call finds the session gone. Other failed reads fail the episode as
  before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(server_runtime): an environment server's checkpoint mode in effect sets its participant and its episodes

A server whose class declares exported but whose instance runs as restart_only installs a restart_only participant,
and its episodes begin as restarts; an unknown mode in effect stops the server at setup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv): run on single_agent_turn_legacy, so flat rows and session-less agents run too

single_agent_turn's /run takes only episode requests, so flat rows (training corpora, rows routed by their agent)
failed. single_agent_turn_legacy takes flat rows and taskset episodes, and runs the same step loop: OfficeEnv keeps
max_episode_steps 50, end_on_task_state, direct HTTP tools and the example taskset's route, and the simple agent no
longer sets max_steps: 1. Composition's fallback relays an agent without agent sessions through legacy_agent to its
own /run, so allowed_agents also admits simple_agent_with_compaction; the relay takes flat rows, not the taskset's
episodes.

The test that restated the YAML (skipped in CI with OfficeEnv absent) gives way to core tests that resolve the
config with a model and build its environment server: as shipped, with simple_agent.yaml added as --agent-type
simple_agent does, and with the compaction agent's config, where the server becomes a legacy_agent relay. The config
comment and README say what --agent-type and allowed_agents do, and that rollout_recovery.target_level: sibling
applies to the whole training run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* docs: GET /task_state and the episode step-limit header

The Seed/Verify Protocol Extensions table lists GET /task_state, its reply, and what a 404 or 5xx does to the
episode. The agent integration page describes x-ng-agent-episode-step-limit beside x-ng-agent-activation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(core): LentSandboxes lends a sandbox with its own image, environment and setup, and releases all within a deadline

What the OfficeEnv sandboxed server needs from core's lent sandboxes, so it builds on them instead of a copy:

- lend() takes a per-sandbox image, more environment variables and a setup that runs against the started sandbox,
  its files delivered, before it is lent (start_with_setup); a setup that fails stops the sandbox.
- The start runs to its end once begun, within start_timeout_s (30 minutes by default), even while the request that
  asked for it is cancelled: a create cut in flight leaves a sandbox whose id the provider never returned. A lend
  cancelled meanwhile lends nothing and stops what it started, and says so in the log.
- release_all(timeout_s=...) refuses new lends (503) from its start, waits for those still starting, stops everything
  within the deadline, and returns and logs the sessions whose sandbox may still run, for a reaper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv): run OfficeEnv episodes in a sandbox, for Gym's sandboxed harnesses

resources_servers/officeenv_sandbox's OfficeEnvSandboxResourcesServer subclasses the OfficeEnv server and lends each
episode session a sandbox through LentSandboxes (an operate descriptor: the harness uses it, only the server stops
it), stopped before the episode is graded.

- The harness reaches the apps as the row's exposure says: MCP tools, a command per app (cli), or endpoints it finds
  over MCP and calls with curl (api_search).
- File content stays out of the conversation through OfficeEnv's workspace mode: downloads land in the workspace,
  uploads and attachments name a workspace file, and a file API moves bytes directly.
- The sandbox sees an ordinary company API. Only Gym's servers on this node (any of the node's own addresses) and
  trusted_networks reach seeding, closing, verification, metrics, the reverify mode, the app catalog, the task state
  and the tool routes, which answer others 404 before reading a body; sessions are signed with a per-process secret.
- Seeds take turns, and a seed is admitted again before it lends; a close or a retire stops the sandbox, a failed
  seed's stop is tried again at its session's close, and shutdown stops everything within the run's grace.
- A sandbox provider failure fails the call (502) and masks the episode's reward.
- Configs for Pi (Docker and OpenSandbox), Codex CLI, mini-SWE, OpenCode, OpenClaw and Terminus 2; nine sandbox tasks
  (OfficeEnv 1.14.0), the first five as example rows with Pi's rollouts of them; images and a README.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): LentSandboxes logs a start its limit cut before the provider returned the sandbox's id

When start_timeout_s cuts a provider's create in flight, the sandbox's id is unknown, so the lend's stop cannot reach
what the create left. The lend now logs that cut at ERROR with the resources session, the task (id and taskset), the
provider, the image and the labels, so a reaper can find the sandbox. A start cut after the create returned stops its
sandbox as before and asks for no reaper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* refactor(officeenv_sandbox): name each harness's instances after it, so harness configs compose in one run

Every harness config defined `oe` and `single_agent_turn_legacy`, so two of them could not run together. Now:

- the episodes' resources server is officeenv_sandbox_resources_server;
- each config adds officeenv_sandbox_<harness>_agent (`_inherit_from` Gym's instance of the harness, as benchmarks do)
  and officeenv_sandbox_<harness>_environment_server (`_inherit_from: single_agent_turn_legacy`);
- Pi, Codex and OpenCode, which name MCP tools their own way, run on their own copy of the episodes' server
  (officeenv_sandbox_<harness>_resources_server, `_copy` with its mcp_tool_prefix); the other harnesses run on the
  shared one. A copy takes the shared server's settings from the merged config, so one override reaches every harness.

The interpolations, the documented overrides, the probe script and the README follow (a table of the names; the
OpenSandbox config is listed after the other harness configs, since a later one pulls the episodes' config in again).
A core test resolves each config alone and all six together with a model config, and replaces the server test that
restated their YAML; it needs no OfficeEnv, so it runs in CI. The OpenCode and OpenClaw configs and the README no
longer say those harnesses refuse MCP tool grants.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv_sandbox): sandbox_config.start_timeout_s bounds a sandbox's start; host_relay needs trusted_workstation

- sandbox_config.start_timeout_s (1800 s by default, a finite number above 0) is passed to LentSandboxes, which fails
  the seed at that limit and logs a create it cut for a reaper. The README says when to raise it: creates on a busy
  OpenSandbox cell have taken up to 2,430 s.
- host_relay forwards sandbox connections from the host's loopback, which the caller check takes for Gym's own
  servers, so code in a sandbox could call the routes kept for Gym for any session. Config validation now refuses
  host_relay unless sandbox_config.trusted_workstation is true, which a config sets only on a single-user workstation;
  its description and the README state the risk.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv_sandbox): officeenv_sandboxless.yaml runs the OfficeEnv server's instances under names of their own

It composes resources_servers/officeenv/configs/officeenv.yaml and copies (`_copy`) its three instances as
officeenv_sandboxless_resources_server, officeenv_sandbox_simple_agent and officeenv_sandbox_environment_server, each
copy pointing at the other copies, while the OfficeEnv server's instances keep their names. The copied agent declares
no dataset, so the example rows and their taskset stay with the OfficeEnv server's instances, and rows that name
officeenv_sandbox_simple_agent (flat rows, agent_ref) route to the copied environment server.

A `_copy` takes its source as written, before the source's own `_inherit_from` applies, so the environment server is
copied as the instance of the server type officeenv_environment_server inherits, with that server's own settings for
it on top. The core test checks each copy against its source, references aside, alone and beside the Pi and Codex
configs, so a change to the source's server type fails it rather than leaving the copy behind.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv_sandbox): the sandboxless arm copies single_agent_turn_legacy, which the OfficeEnv server now runs

officeenv_environment_server inherits single_agent_turn_legacy now, so the copy takes that instance, then the server's
own settings for it under that type, with its references still pointing at the other copies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* refactor(officeenv_sandbox): every harness runs the episodes' server under its own name, so none is left idle

Each harness config now adds officeenv_sandbox_<harness>_resources_server with `_inherit_from:
officeenv_sandbox_resources_server`, OpenClaw, mini-SWE and Terminus 2 included, and no harness names the episodes'
server. `_inherit_from` reads it from the merged config and takes it out of the run, so a run of one or several
harness configs starts no idle episodes' server, while the episodes config alone still runs it under its own name.
Settings on the episodes' server, the OpenSandbox config's included, reach every harness's server. The OpenSandbox
config still goes after the other harness configs (the first harness config listed pulls the episodes' config in),
and the README now says why. The core test checks that no episodes' server starts or is named beside the harnesses',
alone and with all six, and that the episodes config runs on its own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): the cut-start log says OpenSandbox deletes what an abandoned create left

Main's OpenSandbox provider now deletes the sandbox of a create its caller gave up on (NVIDIA-NeMo#4799), so
a start that LentSandboxes' start_timeout_s cuts before the provider returned the sandbox's id no
longer needs a reaper there. The ERROR log, LentSandboxes' docstring and the officeenv_sandbox
README now say so, and keep the reaper for providers without that cleanup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv_sandbox): Pi's run ends once its task has ended, on every exposure

- The sandboxed server holds the call that ends a watched episode's task, on
  every way in (tools, commands, endpoints, the file API), until the
  environment server releases it; the episode's lock is let go first. Only
  Gym's node reaches GET /task_state and POST /task_state/release.
- Pi supports POST /rollouts/{rollout_id}/stop (_rollout_sandbox_session): a
  run stopped as completed answers so, marked in ng_rollout_stop, and is not
  reported as a wall-time timeout.
- The Pi config sets end_on_task_state on its environment server and drops
  finish_tool_names (now []): the stop ends the run on cli and api_search rows
  too, which offer no finish tool. Its comment no longer asks cli rows to drop
  the MCP transport, which they run with as it is.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* docs(officeenv): the servers run OfficeEnv 1.14.2

1.14.2 is the OfficeEnv release N4's training runs grade with. 1.14.1 and
1.14.2 are patch releases; neither changes the API these servers use. The
READMEs' install lines name it, and the example rows are emitted again by it
(officeenv emit for resources_servers/officeenv, sandbox/prepare_rows.py for
officeenv_sandbox), which changed only their version stamp. The example
rollouts stay the ones collected against 1.14.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv_sandbox): refuse calls after the task ended with ResourcesSessionConflictError

Main's session contract (NVIDIA-NeMo#5691) has every 409 a resources server answers raise
ResourcesSessionConflictError, and tests/unit_tests/test_session_contract_repo.py
checks it. The sandboxed server refused a tool call once verification began, and a
file API call once the episode's files closed, with plain HTTPException(409)s; both
now raise the named error. The status and the detail are the same, so callers see no
change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): LentSandboxes shields a start only with start_timeout_s

Main's opencode_search (NVIDIA-NeMo#6211) lends through LentSandboxes and expects a seed cancelled
while its sandbox starts to stop that sandbox at once, as LentSandboxes did before this
branch; the shielded start made it wait for the start's end. The shield is now opt-in.
Without start_timeout_s a cancel cuts the start as it cuts any await, as on main, and the
lend stops the sandbox it began. With it, the start runs to its end within that limit,
which the OfficeEnv sandbox server sets (sandbox_config.start_timeout_s, 1,800 s by
default). START_TIMEOUT_S goes, since no default limit remains.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* build(officeenv_sandbox): lock against main's upgraded dependency locks

Main's lock upgrade (NVIDIA-NeMo#6528) moved the root lock, and `uv sync --locked` refused the
sandboxed server's older lock, so neither its suite nor a run could start it. `uv lock`
with uv 0.13.4 takes the root lock's versions (e2b 2.50.0, protobuf-py 0.1.1, pyqwest
0.10.0), keeps the tzdata OfficeEnv pins (2026.6), and passes scripts/component_locks.py.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(core): a cut start's test counts the closes the provider made

Main's NVIDIA-NeMo#6410 changed the stopped fixture from AsyncSandbox.stop calls to the closes the
provider made. A start cut before the provider returned its sandbox's id leaves nothing
to close, so the hung-start test now expects none, as the ERROR line it checks says.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(single_agent_turn): stop an agent's own loop once its task has ended

With end_on_task_state and no max_episode_steps, single_agent_turn now ends an
agent that runs its own loop (a sandboxed harness) at its task's end, as the
step loop ends a step-driven one:

- Before the agent runs it reads GET /task_state?watch=true; while the agent
  runs it reads again, each read waiting up to 30 s (wait_s).
- Once the task has ended it stops the run with POST /rollouts/{id}/stop
  {"reason": "task_ended", "completed": true}, waits for the activation to
  answer (at most 120 s), then posts /task_state/release.
- The resources server holds its answer to the call that ended the task until
  that release, so the harness never reads it while its run could go on, and
  no model call follows the call that ended the task.
- The server refuses at startup an agent type outside ROLLOUT_STOP_AGENT_TYPES
  (the agents whose runs the stop route can end; a unit test keeps the list in
  step with the apps).

Core: RolloutStopRequest.completed; such a stop answers as completed
(report_rollout_stop) and says so in ng_rollout_stop. Docker uploads take a
bound of their own, so a stop's marker never waits for the exec slot a running
harness holds (uploads_independent_of_execs).

OfficeEnv: GET /task_state takes watch and wait_s (at most 60 s); POST
/task_state/release; task_end_hold_seconds (180) bounds the hold.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(officeenv_sandbox): the stand-in sandbox stops as main's AsyncSandbox.stop does

Main's NVIDIA-NeMo#6410 moved the shielded, bounded stop into AsyncSandbox.stop(timeout_s=...),
which LentSandboxes now calls. The tests' FakeSandbox.stop took no timeout_s and had no
shield, so a seed or close cancelled during a stop failed or hung. FakeSandbox.stop now
takes timeout_s and shields its provider-side _stop, as AsyncSandbox.stop does, and the
tests that slow down, refuse or hang a stop patch _stop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(cline_agent): the fake sandbox session carries expire_completed

report_rollout_stop now reads SandboxSession.expire_completed (a run stopped once
its task has ended answers as completed), so the stand-in that Cline's session
tests use carries it too, as the real session does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* refactor(officeenv_sandbox): sign sessions with Gym's run secret

NVIDIA-NeMo#6161 now makes a secret per server and run in server_runtime, which every worker of the
server shares (signs_sessions_with_run_secret). The sandboxed server sets that flag instead
of minting its own secret in model_post_init and overriding get_session_secret(): its
cookies and MCP tokens are signed, as before, with a secret code in a sandbox cannot
derive from the server's name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv): refuse a tool call after the task ended with ResourcesSessionConflictError

Main's session contract (NVIDIA-NeMo#5691) has every 409 a resources server answers raise
ResourcesSessionConflictError, and tests/unit_tests/test_session_contract_repo.py
checks it. With close_tools_on_task_end, the OfficeEnv server refused a call after the
task ended with a plain HTTPException(409); it now raises the named error. The status
and the detail are the same, so callers see no change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): release_all stops the lent sandboxes while a lend is still starting

release_all waited for every start in flight before it stopped any lent
sandbox, all inside one time limit. One slow start at shutdown then left
every lent sandbox running until its TTL. Now the lent sandboxes stop at
once, and each starting sandbox is stopped when its start ends.

The new test fails before this change (no sandbox stopped) and passes
after it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(officeenv_sandbox): keep the agent and environment servers on 127.0.0.1

NeMo RL sets default_host to the node's address, and an explicit
default_host applies to every server, not only to the types in
absolute_ip_server_types. A sandbox's network rule opens every port of an
allowed host. So code in a sandbox could call the agent and environment
servers: run Pi on Gym's host (/v1/responses without a session), start
episodes (/run) and stop another episode's run
(/rollouts/{rollout_id}/stop).

Each harness config now sets host: 127.0.0.1 on its agent and its
environment server. No sandbox calls them: each harness in a sandbox calls
only the model server and the resources server, and NeMo RL calls /run from
the same node. Without default_host, Gym already binds them to 127.0.0.1.
The comment in officeenv_opensandbox.yaml and the README now say this.

The new config test resolves every harness config under
default_host: 10.0.0.5, on Docker and on OpenSandbox. It fails before this
change (the agent server gets 10.0.0.5) and passes after it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(officeenv_sandbox): refuse calls after the task ends for every harness

No sandboxed config set close_tools_on_task_end, though the README said
that it refuses a harness's later calls. Only Pi's environment server
stops the run at the task's end. So under Codex, OpenCode, OpenClaw,
mini-SWE and Terminus 2, a tool or file API call after complete_task could
still change what /verify grades: a late upload made a task pass.

The episodes' config, which every harness's resources server inherits, now
sets close_tools_on_task_end: true. The config test asserts the resolved
value for each harness in every composition. It fails before this change
and passes after it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* refactor(officeenv_sandbox): leave the mini-SWE pairing to a follow-up PR

The mini-SWE config ran on miniswe_sandboxed_agent, which is deprecated
for new configs in favor of mini_swe_agent's agent sessions. A follow-up
PR will add the pairing on mini_swe_agent/mini_swe_agent_sandboxed, with
one real `cli` row. This removes configs/officeenv_sandbox_miniswe.yaml,
its rows in both config tests and its mentions in the README. The other
five harness configs are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(single_agent_turn): make the task-end stop reach the agent and fail for good on 501

The stop that ends an agent's own loop at the task end now:
- goes over the reserved control connection pool, with the release, so it never waits for a connection that the
  running activation holds;
- counts its 120 s bound from the time the stop is sent, and waits for the activation also when the stop answers
  stopped: false;
- logs a warning and marks the reply (ng_task_end_stop: unconfirmed) when the activation still runs at that bound;
- fails the episode for good when the agent answers 501 (the sandbox provider cannot stop a running harness), since
  every attempt would fail the same way. 500 and 502 stay retryable.

A task that has already ended, or a lost resources session, at the first watch starts no run: the episode goes on to
verification with a reply that has no output (ng_termination_reason: task_ended_before_run).

The step loop logs a warning at startup when the driven agent sets max_steps, which it does not use.

The single_agent_turn README names bwrap among the providers that can stop a running harness, and the providers whose
stop answers 501.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(officeenv): report tool_drift for episode seeds, and document close_tools_on_task_end

An episode seed (ResourcesSeedSessionRequest) now passes the task's responses_create_params to OfficeEnv with the row,
as a seed of the whole row did through legacy_agent, so tool_drift is reported again for rows whose tools are stale.

The README no longer says that checks read every message sent after complete_task: with close_tools_on_task_end, which
this configuration turns on, such a call gets 409 and changes nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* docs(agent-server): describe completed rollout stops and the providers that can stop a running harness

The harness guide now names RolloutStopRequest.completed and the completed status it gives a stopped run, and lists
Local, bwrap, Docker and OpenSandbox with background_exec as the providers that can stop a running harness. The others
answer HTTP 501.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(officeenv_sandbox): report tool_drift for episode seeds

NVIDIA-NeMo#6162 makes the OfficeEnv server's episode seed keep the task's
responses_create_params, so tool_drift compares the row's tools with the
ones the server serves. This server overrides _new_episode with the same
task_data-only seed, so it reported no drift for an episode seed. It now
passes responses_create_params the same way.

The new test seeds a row whose first tool has a stale description. It
fails before this change (tool_drift 0.0) and passes after it (1.0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(simple_agent): run a caller-driven step once when it is sent again

Without checkpointing, the environment server's client sends a step again after a dropped connection, and the step ran
its model call and tool calls a second time: a second email, say, while the environment recorded one reply.

A step of a session that a caller drives one step per activation (x-ng-agent-episode-step-limit) is now keyed by its
session and its activation index. A step sent again while it runs shares its run, and one sent after it answered gets
the same reply and cookies; neither calls the model or runs a tool again. The step runs apart from the request that
sent it, so a disconnect that cancels that request does not cut it short, and closing the session cancels a step that
still runs. A step older than the session's latest is refused with 409.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(agents): a run stopped as completed closes with its invocation completed

A stop with completed: true, for a run whose task ended, makes the run's response completed (report_rollout_stop), but
the harness agents record their invocation before that, as incomplete. So the same run had two statuses: completed in
its response and incomplete in its agent observations (for Prime, and for every agent in ROLLOUT_STOP_AGENT_TYPES).

The base agent's session close now applies report_completed_rollout_stop when the rollout's sandbox session ended with
a completed stop: each top-level invocation the stop left incomplete says completed, with no error type. The sandbox
observation keeps the supervisor's raw timeout, and a child invocation keeps its own status.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* docs(agent-server): a step sent again runs once, and a completed stop closes completed

The integration guide says that simple_agent runs a caller-driven step once without checkpointing, and that the
session close of a run stopped as completed reports its top-level invocation as completed. The harness guide says the
same of the close.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(simple_agent): drop a session's saved step when it closes

The close now clears the step the session kept for a step sent again, so a session never keeps it after it ends. The
docstring says why only caller-driven steps without checkpointing need it: with checkpointing, the activation tracking
already gives a repeated activation its saved reply, and any other activation is the episode's only one or a
continuation session's turn on new input.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* test(goose_agent): a stop for an ended task closes with the invocation completed

A second agent from ROLLOUT_STOP_AGENT_TYPES, besides Prime, whose close after a completed stop has the shape the base
close fixes: a top-level invocation left incomplete, which report_completed_rollout_stop marks completed, and a sandbox
observation that keeps the supervisor's timeout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* build(officeenv_sandbox): lock against main's bumped root dependencies

CI tests this branch merged onto NVIDIA-NeMo#6162's merge ref with main. Main's NVIDIA-NeMo#6268
bumped hydra-core (>=1.4.0rc3), omegaconf (>=2.4.1rc2), mlflow and
gitpython in the root pyproject, which this server's lock includes through
nemo-gym. So `uv sync --locked` and the lock check refused this lock in CI.

This lock was made with `uv lock` on a tree shaped like CI's: this branch
merged onto NVIDIA-NeMo#6162's merge ref 5c7691f (942c31a on main 6aa1fd6).
There, `uv lock --check` and `uv sync --locked` pass, and the server's
tests pass. On this branch alone, `uv lock --check` fails until NVIDIA-NeMo#6162
contains main, because the branch still has the older root pyproject. The
lock is the one that is right once NVIDIA-NeMo#6162 has main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(single_agent_turn): keep task-end watches and stops progressing

Signed-off-by: yaoyu-33 <[email protected]>

* fix(officeenv_sandbox): bind sandboxless services to loopback

Signed-off-by: yaoyu-33 <[email protected]>

* fix(pi): report task-end stops after classifying the invocation

Signed-off-by: yaoyu-33 <[email protected]>

* chore(officeenv_sandbox): add the test package license header

Signed-off-by: yaoyu-33 <[email protected]>

---------

Signed-off-by: Daniele Molinari <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Yi-Fu Wu <[email protected]>
Co-authored-by: yaoyu-33 <[email protected]>
yaoyu-33 added a commit to yaoyu-33/Gym that referenced this pull request Dec 1, 2026
…ion to keep the recorded history (NVIDIA-NeMo#6672)

* feat(core): session secrets, cookie names and MCP endpoint options for servers that sandboxed code calls

A resources server that lends a sandbox is reached by code the model controls, so the session key that every
caller can compute from the server's class and name must not sign its cookies and MCP tokens, and its endpoint
should look like an ordinary one.

- SimpleServer.get_session_secret() signs session cookies and MCP session tokens (default: the session middleware
  key, so nothing changes). Session routing reads cookies and tokens with it. Its docstring states what an
  override must keep: one secret in every worker, and a secret that changes ends every open session.
- SimpleServer.get_session_cookie_name() names the session cookie (default: the same key).
- mcp_server_name: the name the MCP endpoint lists itself under; verify-time normalization strips its namespace.
- mcp_bearer_token: tokens ride as Authorization: Bearer, tools/list needs one and lists only the session's tools,
  a tool outside the grant is an unknown tool, and errors name no framework.
- Both options are refused without expose_tools_over_mcp, and a name outside MCP's tool-name alphabet is refused.
  A single_agent_turn pairing refuses to grant two MCP endpoints listed under one name.

Signed-off-by: Daniele Molinari <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(server_runtime): honor mcp_server_name end to end and refuse bearer tokens without a secret

Review fixes for the MCP endpoint options.

- mcp_server_name is also checked against the name pattern of an MCP grant (MCP_TOOL_ACCESS_NAME_PATTERN in
  tool_access, which MCPToolAccess uses), so a name that an Environment Server cannot grant, one that starts with
  '_' or '-', is refused at config instead of failing every episode before the agent seed. The grant contract is
  unchanged. A dot stays refused: Pi's MCP adapter and Codex refuse server names outside [A-Za-z0-9_-].
- seed_mcp_servers keys each entry by the seed metadata's server_name, else the server's name, and refuses two
  servers listed under one name. URLs, headers and routing still use the server's reference. The sandboxed
  OpenCode agent's required-server list uses the same keys; the sandboxed Pi agent reads them as given.
- An MCP endpoint with mcp_bearer_token refuses to start while get_session_secret() is the public session
  middleware key, since code that reads one bearer token could sign another session's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* revert(agents): keep MCP endpoint names off the legacy seeder

Review asked to keep the MCP changes on the agent-session path. The only callers of
seed_mcp_servers, the sandboxed Pi and OpenCode agents, run on the agent-owned /run path
that #5222 deprecates, and OfficeEnv's Pi preset gets the advertised name and headers
through its MCPToolAccess grant. The seeder keys its entries by server name again, and
the aliasing's tests go with it. It no longer refuses two servers under one name, a
refusal that came after the primary server may have started a task sandbox and before
OpenCode's cleanup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(opencode_agent): refuse MCP grants whose tools OpenCode could name alike

Review found that distinct endpoint names can still hide a tool in opencode_agent.
OpenCode keys each MCP tool <grant>_<tool>, writing characters outside [a-zA-Z0-9_-]
as '_', and a later tool under a key already taken replaces the earlier one without a
word: `company` serving `files_list` and `company_files` serving `list` both register
`company_files_list`. The agent's seed now refuses two MCP grants whose tools could
share a key, which the grant names decide: equal once written as OpenCode writes them,
or one the other followed by '_'. single_agent_turn's README and check, and the
mcp_server_name field, describe tool naming as each harness's own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(server_runtime): sign sessions with a secret made for the run

Review asked for per-run session secrets in server_runtime, as episode_token_secret()
does (#5346), instead of each server overriding get_session_secret().
run_session_secret(name) makes one secret per server for the run and keeps it in the
environment, so the workers uvicorn starts after the main process built the server
inherit it. get_session_secret() returns it when the server sets
signs_sessions_with_run_secret or its config sets mcp_bearer_token, so bearer tokens work
from YAML alone and with any number of workers; otherwise it is the public key, as before.
The session_secret property resolves it once per server (a cached_property, so it holds
for a server built without its model_post_init too), and the session middleware, session
routing and the MCP endpoint all read it there, so an override that answers differently
from call to call cannot split them. Exposure still refuses bearer tokens signed with the
public key, which only an override can now produce.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(single_agent_turn): drive the agent one step at a time and end the episode on the task state

A resources server whose task ends through its state, rather than through one tool's call, can now have its
episode end right after the step that ended the task. OfficeEnv's task ends when its user app's task row leaves
pending, which several operations reach, depending on how a row exposes its apps.

- single_agent_turn: max_episode_steps drives the agent one step per activation, up to that many steps, and
  end_on_task_state reads the resources session's task state between steps (GET /task_state, ResourcesTaskState
  in nemo_gym.server_runtime). Each step's failure report is kept. The server checks at startup that its agent keeps
  a session, runs the tools it calls and stops after one step. Driven episodes take part in checkpoints as restarts
  (BaseEnvironmentServer.checkpoint_mode_in_effect).
- simple_agent: with x-ng-agent-episode-step-limit, a step stopped by its own one-step limit counts as completed
  unless it is the episode's last, and the session keeps one invocation for the episode, as the agent's own loop
  does, instead of one per step that repeats the whole history.
- OfficeEnv: GET /task_state answers ResourcesTaskState; close_tools_on_task_end refuses the calls a step makes after
  the one that ended its task; its rows route by taskset to single_agent_turn with the step loop on, and the config
  allows only the simple agent. A retired attempt no longer keeps its episode, so its replacement can seed the same
  session ID. The server runs OfficeEnv 1.14.0 (1.13.0 at least), with its example rows emitted again.

Signed-off-by: Daniele Molinari <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(single_agent_turn): run the step loop's tests in the core suite, and keep a simple_agent subclass in step

CI on the step loop found two things:
- agentic_turn_simulation_agent overrides simple_agent's _create_episode, which now takes
  step_limit_owned_by_caller. The override accepts it; only an agent session sets it, and this agent
  refuses those.
- The core coverage gate counts single_agent_turn's and simple_agent's app.py, but the step loop's tests
  ran in the server suite only. They move to the core suite unchanged, and simple_agent's step limit and
  invocation folding get core tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(single_agent_turn): import each name in the moved step-loop tests from the module that defines it

Tests under tests/ import from the defining module, not a package's public API, and
test_the_librarys_tests_import_from_the_module_that_defines_each_name failed on the two files this PR moved
into the core suite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(simple_agent): one step per activation that names the episode's step limit, counted by its index

With x-ng-agent-episode-step-limit, the agent takes one step (one model call and the tool calls it makes) whatever
its max_steps says, so a pairing no longer needs max_steps: 1, which composition drops when --agent-type
simple_agent replaces the environment's agent. Requests without the header run as before.

- The step is the activation's index (x-ng-agent-activation), which such a caller sends with every step, not the
  count of requests, so a step resent after a dropped connection is not counted as the next one.
- The session keeps the model server's cookies from step to step, so the episode keeps one model server session.
- A step that raises ends the episode's folded invocation as failed (or incomplete when cancelled), not with the
  completed status of the step before.
- The step keywords go to _create_episode only with the header, so an override that predates them keeps working;
  agentic_turn_simulation_agent's override no longer needs to accept one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(single_agent_turn): drive only agents that take one step per activation, and keep what the steps did

- STEP_DRIVEN_AGENT_TYPES (nemo_gym.config, beside AGENT_SESSION_AGENT_TYPES) lists the agent types that take one
  step per activation that names the episode's step limit: simple_agent. The startup check refuses any other type,
  such as hermes_agent or browsecomp_agent, which keep a session but run their own loop in an activation; a unit
  test keeps the list in step with the agent apps. The check no longer reads max_steps, and reads execute_tools as
  the agent's config does, so a string "false" is false.
- A failure after a step completed keeps the completed steps, their output and summed usage, as its partial
  response, unless it already carries one; a failure before the first reply has none.
- An episode that runs out of steps with every step calling a tool says so in its reply's metadata
  (ng_termination_reason: max_episode_steps). Its status stays the last step's: incomplete_details names only the
  model's own cutoffs, and an incomplete reply would read as malformed to rollout recovery.
- The task state is not read after the last step, which ends the episode either way.
- GET /task_state answering 404 with failure_kind session_lost ends the episode, which goes on to /verify and its
  masked lost-session result, as when a tool call finds the session gone. Other failed reads fail the episode as
  before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(server_runtime): an environment server's checkpoint mode in effect sets its participant and its episodes

A server whose class declares exported but whose instance runs as restart_only installs a restart_only participant,
and its episodes begin as restarts; an unknown mode in effect stops the server at setup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv): run on single_agent_turn_legacy, so flat rows and session-less agents run too

single_agent_turn's /run takes only episode requests, so flat rows (training corpora, rows routed by their agent)
failed. single_agent_turn_legacy takes flat rows and taskset episodes, and runs the same step loop: OfficeEnv keeps
max_episode_steps 50, end_on_task_state, direct HTTP tools and the example taskset's route, and the simple agent no
longer sets max_steps: 1. Composition's fallback relays an agent without agent sessions through legacy_agent to its
own /run, so allowed_agents also admits simple_agent_with_compaction; the relay takes flat rows, not the taskset's
episodes.

The test that restated the YAML (skipped in CI with OfficeEnv absent) gives way to core tests that resolve the
config with a model and build its environment server: as shipped, with simple_agent.yaml added as --agent-type
simple_agent does, and with the compaction agent's config, where the server becomes a legacy_agent relay. The config
comment and README say what --agent-type and allowed_agents do, and that rollout_recovery.target_level: sibling
applies to the whole training run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* docs: GET /task_state and the episode step-limit header

The Seed/Verify Protocol Extensions table lists GET /task_state, its reply, and what a 404 or 5xx does to the
episode. The agent integration page describes x-ng-agent-episode-step-limit beside x-ng-agent-activation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(single_agent_turn): stop an agent's own loop once its task has ended

With end_on_task_state and no max_episode_steps, single_agent_turn now ends an
agent that runs its own loop (a sandboxed harness) at its task's end, as the
step loop ends a step-driven one:

- Before the agent runs it reads GET /task_state?watch=true; while the agent
  runs it reads again, each read waiting up to 30 s (wait_s).
- Once the task has ended it stops the run with POST /rollouts/{id}/stop
  {"reason": "task_ended", "completed": true}, waits for the activation to
  answer (at most 120 s), then posts /task_state/release.
- The resources server holds its answer to the call that ended the task until
  that release, so the harness never reads it while its run could go on, and
  no model call follows the call that ended the task.
- The server refuses at startup an agent type outside ROLLOUT_STOP_AGENT_TYPES
  (the agents whose runs the stop route can end; a unit test keeps the list in
  step with the apps).

Core: RolloutStopRequest.completed; such a stop answers as completed
(report_rollout_stop) and says so in ng_rollout_stop. Docker uploads take a
bound of their own, so a stop's marker never waits for the exec slot a running
harness holds (uploads_independent_of_execs).

OfficeEnv: GET /task_state takes watch and wait_s (at most 60 s); POST
/task_state/release; task_end_hold_seconds (180) bounds the hold.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(cline_agent): the fake sandbox session carries expire_completed

report_rollout_stop now reads SandboxSession.expire_completed (a run stopped once
its task has ended answers as completed), so the stand-in that Cline's session
tests use carries it too, as the real session does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv): refuse a tool call after the task ended with ResourcesSessionConflictError

Main's session contract (#5691) has every 409 a resources server answers raise
ResourcesSessionConflictError, and tests/unit_tests/test_session_contract_repo.py
checks it. With close_tools_on_task_end, the OfficeEnv server refused a call after the
task ended with a plain HTTPException(409); it now raises the named error. The status
and the detail are the same, so callers see no change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(core): LentSandboxes lends a sandbox with its own image, environment and setup, and releases all within a deadline

What the OfficeEnv sandboxed server needs from core's lent sandboxes, so it builds on them instead of a copy:

- lend() takes a per-sandbox image, more environment variables and a setup that runs against the started sandbox,
  its files delivered, before it is lent (start_with_setup); a setup that fails stops the sandbox.
- The start runs to its end once begun, within start_timeout_s (30 minutes by default), even while the request that
  asked for it is cancelled: a create cut in flight leaves a sandbox whose id the provider never returned. A lend
  cancelled meanwhile lends nothing and stops what it started, and says so in the log.
- release_all(timeout_s=...) refuses new lends (503) from its start, waits for those still starting, stops everything
  within the deadline, and returns and logs the sessions whose sandbox may still run, for a reaper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv): run OfficeEnv episodes in a sandbox, for Gym's sandboxed harnesses

resources_servers/officeenv_sandbox's OfficeEnvSandboxResourcesServer subclasses the OfficeEnv server and lends each
episode session a sandbox through LentSandboxes (an operate descriptor: the harness uses it, only the server stops
it), stopped before the episode is graded.

- The harness reaches the apps as the row's exposure says: MCP tools, a command per app (cli), or endpoints it finds
  over MCP and calls with curl (api_search).
- File content stays out of the conversation through OfficeEnv's workspace mode: downloads land in the workspace,
  uploads and attachments name a workspace file, and a file API moves bytes directly.
- The sandbox sees an ordinary company API. Only Gym's servers on this node (any of the node's own addresses) and
  trusted_networks reach seeding, closing, verification, metrics, the reverify mode, the app catalog, the task state
  and the tool routes, which answer others 404 before reading a body; sessions are signed with a per-process secret.
- Seeds take turns, and a seed is admitted again before it lends; a close or a retire stops the sandbox, a failed
  seed's stop is tried again at its session's close, and shutdown stops everything within the run's grace.
- A sandbox provider failure fails the call (502) and masks the episode's reward.
- Configs for Pi (Docker and OpenSandbox), Codex CLI, mini-SWE, OpenCode, OpenClaw and Terminus 2; nine sandbox tasks
  (OfficeEnv 1.14.0), the first five as example rows with Pi's rollouts of them; images and a README.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): LentSandboxes logs a start its limit cut before the provider returned the sandbox's id

When start_timeout_s cuts a provider's create in flight, the sandbox's id is unknown, so the lend's stop cannot reach
what the create left. The lend now logs that cut at ERROR with the resources session, the task (id and taskset), the
provider, the image and the labels, so a reaper can find the sandbox. A start cut after the create returned stops its
sandbox as before and asks for no reaper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* refactor(officeenv_sandbox): name each harness's instances after it, so harness configs compose in one run

Every harness config defined `oe` and `single_agent_turn_legacy`, so two of them could not run together. Now:

- the episodes' resources server is officeenv_sandbox_resources_server;
- each config adds officeenv_sandbox_<harness>_agent (`_inherit_from` Gym's instance of the harness, as benchmarks do)
  and officeenv_sandbox_<harness>_environment_server (`_inherit_from: single_agent_turn_legacy`);
- Pi, Codex and OpenCode, which name MCP tools their own way, run on their own copy of the episodes' server
  (officeenv_sandbox_<harness>_resources_server, `_copy` with its mcp_tool_prefix); the other harnesses run on the
  shared one. A copy takes the shared server's settings from the merged config, so one override reaches every harness.

The interpolations, the documented overrides, the probe script and the README follow (a table of the names; the
OpenSandbox config is listed after the other harness configs, since a later one pulls the episodes' config in again).
A core test resolves each config alone and all six together with a model config, and replaces the server test that
restated their YAML; it needs no OfficeEnv, so it runs in CI. The OpenCode and OpenClaw configs and the README no
longer say those harnesses refuse MCP tool grants.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv_sandbox): sandbox_config.start_timeout_s bounds a sandbox's start; host_relay needs trusted_workstation

- sandbox_config.start_timeout_s (1800 s by default, a finite number above 0) is passed to LentSandboxes, which fails
  the seed at that limit and logs a create it cut for a reaper. The README says when to raise it: creates on a busy
  OpenSandbox cell have taken up to 2,430 s.
- host_relay forwards sandbox connections from the host's loopback, which the caller check takes for Gym's own
  servers, so code in a sandbox could call the routes kept for Gym for any session. Config validation now refuses
  host_relay unless sandbox_config.trusted_workstation is true, which a config sets only on a single-user workstation;
  its description and the README state the risk.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv_sandbox): officeenv_sandboxless.yaml runs the OfficeEnv server's instances under names of their own

It composes resources_servers/officeenv/configs/officeenv.yaml and copies (`_copy`) its three instances as
officeenv_sandboxless_resources_server, officeenv_sandbox_simple_agent and officeenv_sandbox_environment_server, each
copy pointing at the other copies, while the OfficeEnv server's instances keep their names. The copied agent declares
no dataset, so the example rows and their taskset stay with the OfficeEnv server's instances, and rows that name
officeenv_sandbox_simple_agent (flat rows, agent_ref) route to the copied environment server.

A `_copy` takes its source as written, before the source's own `_inherit_from` applies, so the environment server is
copied as the instance of the server type officeenv_environment_server inherits, with that server's own settings for
it on top. The core test checks each copy against its source, references aside, alone and beside the Pi and Codex
configs, so a change to the source's server type fails it rather than leaving the copy behind.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv_sandbox): the sandboxless arm copies single_agent_turn_legacy, which the OfficeEnv server now runs

officeenv_environment_server inherits single_agent_turn_legacy now, so the copy takes that instance, then the server's
own settings for it under that type, with its references still pointing at the other copies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* refactor(officeenv_sandbox): every harness runs the episodes' server under its own name, so none is left idle

Each harness config now adds officeenv_sandbox_<harness>_resources_server with `_inherit_from:
officeenv_sandbox_resources_server`, OpenClaw, mini-SWE and Terminus 2 included, and no harness names the episodes'
server. `_inherit_from` reads it from the merged config and takes it out of the run, so a run of one or several
harness configs starts no idle episodes' server, while the episodes config alone still runs it under its own name.
Settings on the episodes' server, the OpenSandbox config's included, reach every harness's server. The OpenSandbox
config still goes after the other harness configs (the first harness config listed pulls the episodes' config in),
and the README now says why. The core test checks that no episodes' server starts or is named beside the harnesses',
alone and with all six, and that the episodes config runs on its own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): the cut-start log says OpenSandbox deletes what an abandoned create left

Main's OpenSandbox provider now deletes the sandbox of a create its caller gave up on (#4799), so
a start that LentSandboxes' start_timeout_s cuts before the provider returned the sandbox's id no
longer needs a reaper there. The ERROR log, LentSandboxes' docstring and the officeenv_sandbox
README now say so, and keep the reaper for providers without that cleanup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv_sandbox): Pi's run ends once its task has ended, on every exposure

- The sandboxed server holds the call that ends a watched episode's task, on
  every way in (tools, commands, endpoints, the file API), until the
  environment server releases it; the episode's lock is let go first. Only
  Gym's node reaches GET /task_state and POST /task_state/release.
- Pi supports POST /rollouts/{rollout_id}/stop (_rollout_sandbox_session): a
  run stopped as completed answers so, marked in ng_rollout_stop, and is not
  reported as a wall-time timeout.
- The Pi config sets end_on_task_state on its environment server and drops
  finish_tool_names (now []): the stop ends the run on cli and api_search rows
  too, which offer no finish tool. Its comment no longer asks cli rows to drop
  the MCP transport, which they run with as it is.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* docs(officeenv): the servers run OfficeEnv 1.14.2

1.14.2 is the OfficeEnv release N4's training runs grade with. 1.14.1 and
1.14.2 are patch releases; neither changes the API these servers use. The
READMEs' install lines name it, and the example rows are emitted again by it
(officeenv emit for resources_servers/officeenv, sandbox/prepare_rows.py for
officeenv_sandbox), which changed only their version stamp. The example
rollouts stay the ones collected against 1.14.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv_sandbox): refuse calls after the task ended with ResourcesSessionConflictError

Main's session contract (#5691) has every 409 a resources server answers raise
ResourcesSessionConflictError, and tests/unit_tests/test_session_contract_repo.py
checks it. The sandboxed server refused a tool call once verification began, and a
file API call once the episode's files closed, with plain HTTPException(409)s; both
now raise the named error. The status and the detail are the same, so callers see no
change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): LentSandboxes shields a start only with start_timeout_s

Main's opencode_search (#6211) lends through LentSandboxes and expects a seed cancelled
while its sandbox starts to stop that sandbox at once, as LentSandboxes did before this
branch; the shielded start made it wait for the start's end. The shield is now opt-in.
Without start_timeout_s a cancel cuts the start as it cuts any await, as on main, and the
lend stops the sandbox it began. With it, the start runs to its end within that limit,
which the OfficeEnv sandbox server sets (sandbox_config.start_timeout_s, 1,800 s by
default). START_TIMEOUT_S goes, since no default limit remains.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* build(officeenv_sandbox): lock against main's upgraded dependency locks

Main's lock upgrade (#6528) moved the root lock, and `uv sync --locked` refused the
sandboxed server's older lock, so neither its suite nor a run could start it. `uv lock`
with uv 0.13.4 takes the root lock's versions (e2b 2.50.0, protobuf-py 0.1.1, pyqwest
0.10.0), keeps the tzdata OfficeEnv pins (2026.6), and passes scripts/component_locks.py.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(core): a cut start's test counts the closes the provider made

Main's #6410 changed the stopped fixture from AsyncSandbox.stop calls to the closes the
provider made. A start cut before the provider returned its sandbox's id leaves nothing
to close, so the hung-start test now expects none, as the ERROR line it checks says.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(officeenv_sandbox): the stand-in sandbox stops as main's AsyncSandbox.stop does

Main's #6410 moved the shielded, bounded stop into AsyncSandbox.stop(timeout_s=...),
which LentSandboxes now calls. The tests' FakeSandbox.stop took no timeout_s and had no
shield, so a seed or close cancelled during a stop failed or hung. FakeSandbox.stop now
takes timeout_s and shields its provider-side _stop, as AsyncSandbox.stop does, and the
tests that slow down, refuse or hang a stop patch _stop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* refactor(officeenv_sandbox): sign sessions with Gym's run secret

#6161 now makes a secret per server and run in server_runtime, which every worker of the
server shares (signs_sessions_with_run_secret). The sandboxed server sets that flag instead
of minting its own secret in model_post_init and overriding get_session_secret(): its
cookies and MCP tokens are signed, as before, with a secret code in a sandbox cannot
derive from the server's name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(stirrup_agent): stop a run once its task has ended, and run Stirrup on OfficeEnv's sandboxed episodes

Stirrup could not be stopped in flight, so single_agent_turn's end_on_task_state refused it and OfficeEnv's
sandboxed episodes had no Stirrup harness:

- stirrup_agent returns its sandbox session for a rollout stop (_rollout_sandbox_session) and marks the run a
  stop ended (report_rollout_stop): a stop once the task has ended answers as completed, with ng_rollout_stop and
  without the deadline's stop_reason. stirrup_agent joins ROLLOUT_STOP_AGENT_TYPES.
- The runner, ended by its supervisor while a turn's tool calls run, reports that turn's reply too (its calls
  without answers) rather than the history as of the turn's start. A stop once the task has ended lands so: the
  call that ended the task waits for its answer until the run is over, and it stays the run's last item, as Pi's
  does.
- resources_servers/officeenv_sandbox/configs/officeenv_sandbox_stirrup.yaml: Stirrup on `cli` rows, under the
  harness configs' names (officeenv_sandbox_stirrup_agent, _environment_server, _resources_server), no MCP
  transports, end_on_task_state, admitted episodes capped at Stirrup's concurrency.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(stirrup_agent): options to keep the run's history as it was recorded

Training on recorded tokens needs one unbroken history per episode, and Stirrup's defaults rewrite it: past 0.7 of
the context window it replaces the history with a summary, and on a context overflow it unwinds completed turns.
Two options keep those defaults and let a training config turn them off:

- context_summarization_cutoff (default 0.7, Stirrup's): None never summarizes, so an episode at the context limit
  ends there;
- recover_from_context_overflow (default true, Stirrup's): false raises instead of unwinding.

The runner passes them to Stirrup's agent; a payload without them keeps Stirrup's defaults.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* test(officeenv_sandbox): cover the Stirrup harness config in the core config tests

The server's own config tests skip without OfficeEnv, and CI does not install OfficeEnv. The core config tests
resolve each harness config without it, so they now include officeenv_sandbox_stirrup.yaml. The tests make sure
that its instances carry Stirrup's name, that it composes beside the other harness configs with its own cap of 32,
and that its environment server stops the run once the task has ended.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* docs(stirrup_agent): describe rollout stops and the history options

The README now says how a rollout stop ends a Stirrup run and what the response carries. A run that ends while a
turn's tool calls run ends with that turn's reply. The options table lists context_summarization_cutoff and
recover_from_context_overflow, and a new section names the settings that keep the recorded history for training.

With context_overflow_recovery off, its default, the client never reports an overflow to Stirrup. So
recover_from_context_overflow changes a run only when a config also turns context_overflow_recovery on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(stirrup_agent): keep a compaction summary out of a stopped run's output

The runner kept the last reply of every model call, a compaction summary's included. A summary can carry tool
calls, since its first attempts offer the tools. If the run then ended while the next policy call waited for the
model, the runner added the summary and its calls to the output as the running turn, although those calls never ran.

The runner now keeps only the reply of the policy turn that is running. Each model call clears the reply first, and
a reply made during a compaction is never kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(stirrup_agent): answer a stop that arrives before the runner starts

A rollout stop accepted during the seed or before the activation keeps the supervisor from launching the runner.
The runner then writes no output.json, so the activation failed with "Stirrup sandbox runner exited without
output", although the agent server had answered the stop as stopped.

When the session reports an expiry before launch, the runner's report is now an empty run that ended at its time
limit, with the session's cookies. The agent server then marks the stop and gives the status the stop asked for, as
for a run that a stop ended. Missing output from a runner that did launch still fails the activation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(stirrup_agent): report the live turn of a run stopped around a compaction

The previous commit kept no summary reply, but a run cut during a compaction still lost its last turn. Stirrup takes
its history snapshot at the start of each turn and summarizes after the turn has answered. So during a summary
request, the snapshot does not hold the turn that just ran, and the output was empty or ended with that turn's call
without its answer.

The runner now watches Stirrup's step, as it watches summarize_messages. It keeps the message list that step gets,
which Stirrup extends with the answered turn, and keeps a reply only when its request is that list and only while
step runs. On a cut, it reports that live list and the running turn's reply. A summary request sends a new list, so
its reply is never kept. The test covers a cut after a summary, in the second summary attempt and in the first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(stirrup_agent): answer a stop that ends the runner while it starts

The runner installs its SIGTERM handler only after its imports. A rollout stop in that window ends the runner
before it writes its report, and the activation still failed with "Stirrup sandbox runner exited without output".

collect now also returns the empty stopped report when the session expired (a stop that the supervisor acted on)
and the runner left no output file. A runner that crashed, or a deadline that ended it with no stop, still fails
the activation. The report helper is now _stopped_without_output, since it covers both windows.

Tests: a stop after the seed and before the run answers as an empty stopped run with no observation gaps. A runner
that never gets past its start answers as an empty stopped run when a stop ended it, and fails when its deadline
did.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* refactor(stirrup_agent): drop recover_from_context_overflow

Stirrup reads this option only when the client raises ContextOverflowError, and the client raises it only with
context_overflow_recovery on. With that option off, its default, Stirrup drops no turn whatever this option says.
With it on and this option false, the episode ends at the first overflow, as it does with context_overflow_recovery
off. So the option added no behavior, and a training config needs only context_summarization_cutoff: null.

This removes the field, its payload key, the runner argument, its README row and paragraph, and its test cases.
Draft #5835 adds the same option. No release has it, so no removed-option entry is needed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(stirrup_agent): bound context_summarization_cutoff at 1

Stirrup compares the cutoff with the last call's tokens divided by the context window, and it does not reject a
value above 1. Such a value fires only when one call uses more tokens than the window. So a percent such as 70
turned compaction off with no error. The field now accepts values above 0 and at most 1, and null still never
summarizes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* docs(stirrup_agent): name the other history rewrites, and fix the Stirrup config's network note

The Stirrup README section on keeping the recorded history now also names truncation_recovery, which sends one call
with an instruction that the history never records. It also names the two rewrites that stay: an assistant turn
with no parsed tool call loses its tool-call text, and reasoning that comes back in its own field is not sent back.

The header of officeenv_sandbox_stirrup.yaml said that Stirrup's sandboxes need the package index. The agent server
builds Stirrup's Python runtime on its own host and uploads it, so the sandboxes need no internet. Only the host
needs the package index.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* feat(single_agent_turn): drive the agent one step at a time and end the episode on the task state

A resources server whose task ends through its state, rather than through one tool's call, can now have its
episode end right after the step that ended the task. OfficeEnv's task ends when its user app's task row leaves
pending, which several operations reach, depending on how a row exposes its apps.

- single_agent_turn: max_episode_steps drives the agent one step per activation, up to that many steps, and
  end_on_task_state reads the resources session's task state between steps (GET /task_state, ResourcesTaskState
  in nemo_gym.server_runtime). Each step's failure report is kept. The server checks at startup that its agent keeps
  a session, runs the tools it calls and stops after one step. Driven episodes take part in checkpoints as restarts
  (BaseEnvironmentServer.checkpoint_mode_in_effect).
- simple_agent: with x-ng-agent-episode-step-limit, a step stopped by its own one-step limit counts as completed
  unless it is the episode's last, and the session keeps one invocation for the episode, as the agent's own loop
  does, instead of one per step that repeats the whole history.
- OfficeEnv: GET /task_state answers ResourcesTaskState; close_tools_on_task_end refuses the calls a step makes after
  the one that ended its task; its rows route by taskset to single_agent_turn with the step loop on, and the config
  allows only the simple agent. A retired attempt no longer keeps its episode, so its replacement can seed the same
  session ID. The server runs OfficeEnv 1.14.0 (1.13.0 at least), with its example rows emitted again.

Signed-off-by: Daniele Molinari <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(single_agent_turn): run the step loop's tests in the core suite, and keep a simple_agent subclass in step

CI on the step loop found two things:
- agentic_turn_simulation_agent overrides simple_agent's _create_episode, which now takes
  step_limit_owned_by_caller. The override accepts it; only an agent session sets it, and this agent
  refuses those.
- The core coverage gate counts single_agent_turn's and simple_agent's app.py, but the step loop's tests
  ran in the server suite only. They move to the core suite unchanged, and simple_agent's step limit and
  invocation folding get core tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(single_agent_turn): import each name in the moved step-loop tests from the module that defines it

Tests under tests/ import from the defining module, not a package's public API, and
test_the_librarys_tests_import_from_the_module_that_defines_each_name failed on the two files this PR moved
into the core suite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(simple_agent): one step per activation that names the episode's step limit, counted by its index

With x-ng-agent-episode-step-limit, the agent takes one step (one model call and the tool calls it makes) whatever
its max_steps says, so a pairing no longer needs max_steps: 1, which composition drops when --agent-type
simple_agent replaces the environment's agent. Requests without the header run as before.

- The step is the activation's index (x-ng-agent-activation), which such a caller sends with every step, not the
  count of requests, so a step resent after a dropped connection is not counted as the next one.
- The session keeps the model server's cookies from step to step, so the episode keeps one model server session.
- A step that raises ends the episode's folded invocation as failed (or incomplete when cancelled), not with the
  completed status of the step before.
- The step keywords go to _create_episode only with the header, so an override that predates them keeps working;
  agentic_turn_simulation_agent's override no longer needs to accept one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(single_agent_turn): drive only agents that take one step per activation, and keep what the steps did

- STEP_DRIVEN_AGENT_TYPES (nemo_gym.config, beside AGENT_SESSION_AGENT_TYPES) lists the agent types that take one
  step per activation that names the episode's step limit: simple_agent. The startup check refuses any other type,
  such as hermes_agent or browsecomp_agent, which keep a session but run their own loop in an activation; a unit
  test keeps the list in step with the agent apps. The check no longer reads max_steps, and reads execute_tools as
  the agent's config does, so a string "false" is false.
- A failure after a step completed keeps the completed steps, their output and summed usage, as its partial
  response, unless it already carries one; a failure before the first reply has none.
- An episode that runs out of steps with every step calling a tool says so in its reply's metadata
  (ng_termination_reason: max_episode_steps). Its status stays the last step's: incomplete_details names only the
  model's own cutoffs, and an incomplete reply would read as malformed to rollout recovery.
- The task state is not read after the last step, which ends the episode either way.
- GET /task_state answering 404 with failure_kind session_lost ends the episode, which goes on to /verify and its
  masked lost-session result, as when a tool call finds the session gone. Other failed reads fail the episode as
  before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(server_runtime): an environment server's checkpoint mode in effect sets its participant and its episodes

A server whose class declares exported but whose instance runs as restart_only installs a restart_only participant,
and its episodes begin as restarts; an unknown mode in effect stops the server at setup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv): run on single_agent_turn_legacy, so flat rows and session-less agents run too

single_agent_turn's /run takes only episode requests, so flat rows (training corpora, rows routed by their agent)
failed. single_agent_turn_legacy takes flat rows and taskset episodes, and runs the same step loop: OfficeEnv keeps
max_episode_steps 50, end_on_task_state, direct HTTP tools and the example taskset's route, and the simple agent no
longer sets max_steps: 1. Composition's fallback relays an agent without agent sessions through legacy_agent to its
own /run, so allowed_agents also admits simple_agent_with_compaction; the relay takes flat rows, not the taskset's
episodes.

The test that restated the YAML (skipped in CI with OfficeEnv absent) gives way to core tests that resolve the
config with a model and build its environment server: as shipped, with simple_agent.yaml added as --agent-type
simple_agent does, and with the compaction agent's config, where the server becomes a legacy_agent relay. The config
comment and README say what --agent-type and allowed_agents do, and that rollout_recovery.target_level: sibling
applies to the whole training run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* docs: GET /task_state and the episode step-limit header

The Seed/Verify Protocol Extensions table lists GET /task_state, its reply, and what a 404 or 5xx does to the
episode. The agent integration page describes x-ng-agent-episode-step-limit beside x-ng-agent-activation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(core): LentSandboxes lends a sandbox with its own image, environment and setup, and releases all within a deadline

What the OfficeEnv sandboxed server needs from core's lent sandboxes, so it builds on them instead of a copy:

- lend() takes a per-sandbox image, more environment variables and a setup that runs against the started sandbox,
  its files delivered, before it is lent (start_with_setup); a setup that fails stops the sandbox.
- The start runs to its end once begun, within start_timeout_s (30 minutes by default), even while the request that
  asked for it is cancelled: a create cut in flight leaves a sandbox whose id the provider never returned. A lend
  cancelled meanwhile lends nothing and stops what it started, and says so in the log.
- release_all(timeout_s=...) refuses new lends (503) from its start, waits for those still starting, stops everything
  within the deadline, and returns and logs the sessions whose sandbox may still run, for a reaper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv): run OfficeEnv episodes in a sandbox, for Gym's sandboxed harnesses

resources_servers/officeenv_sandbox's OfficeEnvSandboxResourcesServer subclasses the OfficeEnv server and lends each
episode session a sandbox through LentSandboxes (an operate descriptor: the harness uses it, only the server stops
it), stopped before the episode is graded.

- The harness reaches the apps as the row's exposure says: MCP tools, a command per app (cli), or endpoints it finds
  over MCP and calls with curl (api_search).
- File content stays out of the conversation through OfficeEnv's workspace mode: downloads land in the workspace,
  uploads and attachments name a workspace file, and a file API moves bytes directly.
- The sandbox sees an ordinary company API. Only Gym's servers on this node (any of the node's own addresses) and
  trusted_networks reach seeding, closing, verification, metrics, the reverify mode, the app catalog, the task state
  and the tool routes, which answer others 404 before reading a body; sessions are signed with a per-process secret.
- Seeds take turns, and a seed is admitted again before it lends; a close or a retire stops the sandbox, a failed
  seed's stop is tried again at its session's close, and shutdown stops everything within the run's grace.
- A sandbox provider failure fails the call (502) and masks the episode's reward.
- Configs for Pi (Docker and OpenSandbox), Codex CLI, mini-SWE, OpenCode, OpenClaw and Terminus 2; nine sandbox tasks
  (OfficeEnv 1.14.0), the first five as example rows with Pi's rollouts of them; images and a README.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): LentSandboxes logs a start its limit cut before the provider returned the sandbox's id

When start_timeout_s cuts a provider's create in flight, the sandbox's id is unknown, so the lend's stop cannot reach
what the create left. The lend now logs that cut at ERROR with the resources session, the task (id and taskset), the
provider, the image and the labels, so a reaper can find the sandbox. A start cut after the create returned stops its
sandbox as before and asks for no reaper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* refactor(officeenv_sandbox): name each harness's instances after it, so harness configs compose in one run

Every harness config defined `oe` and `single_agent_turn_legacy`, so two of them could not run together. Now:

- the episodes' resources server is officeenv_sandbox_resources_server;
- each config adds officeenv_sandbox_<harness>_agent (`_inherit_from` Gym's instance of the harness, as benchmarks do)
  and officeenv_sandbox_<harness>_environment_server (`_inherit_from: single_agent_turn_legacy`);
- Pi, Codex and OpenCode, which name MCP tools their own way, run on their own copy of the episodes' server
  (officeenv_sandbox_<harness>_resources_server, `_copy` with its mcp_tool_prefix); the other harnesses run on the
  shared one. A copy takes the shared server's settings from the merged config, so one override reaches every harness.

The interpolations, the documented overrides, the probe script and the README follow (a table of the names; the
OpenSandbox config is listed after the other harness configs, since a later one pulls the episodes' config in again).
A core test resolves each config alone and all six together with a model config, and replaces the server test that
restated their YAML; it needs no OfficeEnv, so it runs in CI. The OpenCode and OpenClaw configs and the README no
longer say those harnesses refuse MCP tool grants.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv_sandbox): sandbox_config.start_timeout_s bounds a sandbox's start; host_relay needs trusted_workstation

- sandbox_config.start_timeout_s (1800 s by default, a finite number above 0) is passed to LentSandboxes, which fails
  the seed at that limit and logs a create it cut for a reaper. The README says when to raise it: creates on a busy
  OpenSandbox cell have taken up to 2,430 s.
- host_relay forwards sandbox connections from the host's loopback, which the caller check takes for Gym's own
  servers, so code in a sandbox could call the routes kept for Gym for any session. Config validation now refuses
  host_relay unless sandbox_config.trusted_workstation is true, which a config sets only on a single-user workstation;
  its description and the README state the risk.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv_sandbox): officeenv_sandboxless.yaml runs the OfficeEnv server's instances under names of their own

It composes resources_servers/officeenv/configs/officeenv.yaml and copies (`_copy`) its three instances as
officeenv_sandboxless_resources_server, officeenv_sandbox_simple_agent and officeenv_sandbox_environment_server, each
copy pointing at the other copies, while the OfficeEnv server's instances keep their names. The copied agent declares
no dataset, so the example rows and their taskset stay with the OfficeEnv server's instances, and rows that name
officeenv_sandbox_simple_agent (flat rows, agent_ref) route to the copied environment server.

A `_copy` takes its source as written, before the source's own `_inherit_from` applies, so the environment server is
copied as the instance of the server type officeenv_environment_server inherits, with that server's own settings for
it on top. The core test checks each copy against its source, references aside, alone and beside the Pi and Codex
configs, so a change to the source's server type fails it rather than leaving the copy behind.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv_sandbox): the sandboxless arm copies single_agent_turn_legacy, which the OfficeEnv server now runs

officeenv_environment_server inherits single_agent_turn_legacy now, so the copy takes that instance, then the server's
own settings for it under that type, with its references still pointing at the other copies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* refactor(officeenv_sandbox): every harness runs the episodes' server under its own name, so none is left idle

Each harness config now adds officeenv_sandbox_<harness>_resources_server with `_inherit_from:
officeenv_sandbox_resources_server`, OpenClaw, mini-SWE and Terminus 2 included, and no harness names the episodes'
server. `_inherit_from` reads it from the merged config and takes it out of the run, so a run of one or several
harness configs starts no idle episodes' server, while the episodes config alone still runs it under its own name.
Settings on the episodes' server, the OpenSandbox config's included, reach every harness's server. The OpenSandbox
config still goes after the other harness configs (the first harness config listed pulls the episodes' config in),
and the README now says why. The core test checks that no episodes' server starts or is named beside the harnesses',
alone and with all six, and that the episodes config runs on its own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): the cut-start log says OpenSandbox deletes what an abandoned create left

Main's OpenSandbox provider now deletes the sandbox of a create its caller gave up on (#4799), so
a start that LentSandboxes' start_timeout_s cuts before the provider returned the sandbox's id no
longer needs a reaper there. The ERROR log, LentSandboxes' docstring and the officeenv_sandbox
README now say so, and keep the reaper for providers without that cleanup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(officeenv_sandbox): Pi's run ends once its task has ended, on every exposure

- The sandboxed server holds the call that ends a watched episode's task, on
  every way in (tools, commands, endpoints, the file API), until the
  environment server releases it; the episode's lock is let go first. Only
  Gym's node reaches GET /task_state and POST /task_state/release.
- Pi supports POST /rollouts/{rollout_id}/stop (_rollout_sandbox_session): a
  run stopped as completed answers so, marked in ng_rollout_stop, and is not
  reported as a wall-time timeout.
- The Pi config sets end_on_task_state on its environment server and drops
  finish_tool_names (now []): the stop ends the run on cli and api_search rows
  too, which offer no finish tool. Its comment no longer asks cli rows to drop
  the MCP transport, which they run with as it is.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* docs(officeenv): the servers run OfficeEnv 1.14.2

1.14.2 is the OfficeEnv release N4's training runs grade with. 1.14.1 and
1.14.2 are patch releases; neither changes the API these servers use. The
READMEs' install lines name it, and the example rows are emitted again by it
(officeenv emit for resources_servers/officeenv, sandbox/prepare_rows.py for
officeenv_sandbox), which changed only their version stamp. The example
rollouts stay the ones collected against 1.14.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv_sandbox): refuse calls after the task ended with ResourcesSessionConflictError

Main's session contract (#5691) has every 409 a resources server answers raise
ResourcesSessionConflictError, and tests/unit_tests/test_session_contract_repo.py
checks it. The sandboxed server refused a tool call once verification began, and a
file API call once the episode's files closed, with plain HTTPException(409)s; both
now raise the named error. The status and the detail are the same, so callers see no
change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(core): LentSandboxes shields a start only with start_timeout_s

Main's opencode_search (#6211) lends through LentSandboxes and expects a seed cancelled
while its sandbox starts to stop that sandbox at once, as LentSandboxes did before this
branch; the shielded start made it wait for the start's end. The shield is now opt-in.
Without start_timeout_s a cancel cuts the start as it cuts any await, as on main, and the
lend stops the sandbox it began. With it, the start runs to its end within that limit,
which the OfficeEnv sandbox server sets (sandbox_config.start_timeout_s, 1,800 s by
default). START_TIMEOUT_S goes, since no default limit remains.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* build(officeenv_sandbox): lock against main's upgraded dependency locks

Main's lock upgrade (#6528) moved the root lock, and `uv sync --locked` refused the
sandboxed server's older lock, so neither its suite nor a run could start it. `uv lock`
with uv 0.13.4 takes the root lock's versions (e2b 2.50.0, protobuf-py 0.1.1, pyqwest
0.10.0), keeps the tzdata OfficeEnv pins (2026.6), and passes scripts/component_locks.py.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(core): a cut start's test counts the closes the provider made

Main's #6410 changed the stopped fixture from AsyncSandbox.stop calls to the closes the
provider made. A start cut before the provider returned its sandbox's id leaves nothing
to close, so the hung-start test now expects none, as the ERROR line it checks says.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* feat(single_agent_turn): stop an agent's own loop once its task has ended

With end_on_task_state and no max_episode_steps, single_agent_turn now ends an
agent that runs its own loop (a sandboxed harness) at its task's end, as the
step loop ends a step-driven one:

- Before the agent runs it reads GET /task_state?watch=true; while the agent
  runs it reads again, each read waiting up to 30 s (wait_s).
- Once the task has ended it stops the run with POST /rollouts/{id}/stop
  {"reason": "task_ended", "completed": true}, waits for the activation to
  answer (at most 120 s), then posts /task_state/release.
- The resources server holds its answer to the call that ended the task until
  that release, so the harness never reads it while its run could go on, and
  no model call follows the call that ended the task.
- The server refuses at startup an agent type outside ROLLOUT_STOP_AGENT_TYPES
  (the agents whose runs the stop route can end; a unit test keeps the list in
  step with the apps).

Core: RolloutStopRequest.completed; such a stop answers as completed
(report_rollout_stop) and says so in ng_rollout_stop. Docker uploads take a
bound of their own, so a stop's marker never waits for the exec slot a running
harness holds (uploads_independent_of_execs).

OfficeEnv: GET /task_state takes watch and wait_s (at most 60 s); POST
/task_state/release; task_end_hold_seconds (180) bounds the hold.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(officeenv_sandbox): the stand-in sandbox stops as main's AsyncSandbox.stop does

Main's #6410 moved the shielded, bounded stop into AsyncSandbox.stop(timeout_s=...),
which LentSandboxes now calls. The tests' FakeSandbox.stop took no timeout_s and had no
shield, so a seed or close cancelled during a stop failed or hung. FakeSandbox.stop now
takes timeout_s and shields its provider-side _stop, as AsyncSandbox.stop does, and the
tests that slow down, refuse or hang a stop patch _stop.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* test(cline_agent): the fake sandbox session carries expire_completed

report_rollout_stop now reads SandboxSession.expire_completed (a run stopped once
its task has ended answers as completed), so the stand-in that Cline's session
tests use carries it too, as the real session does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* refactor(officeenv_sandbox): sign sessions with Gym's run secret

#6161 now makes a secret per server and run in server_runtime, which every worker of the
server shares (signs_sessions_with_run_secret). The sandboxed server sets that flag instead
of minting its own secret in model_post_init and overriding get_session_secret(): its
cookies and MCP tokens are signed, as before, with a secret code in a sandbox cannot
derive from the server's name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* fix(officeenv): refuse a tool call after the task ended with ResourcesSessionConflictError

Main's session contract (#5691) has every 409 a resources server answers raise
ResourcesSessionConflictError, and tests/unit_tests/test_session_contract_repo.py
checks it. With close_tools_on_task_end, the OfficeEnv server refused a call after the
task ended with a plain HTTPException(409); it now raises the named error. The status
and the detail are the same, so callers see no change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Daniele Molinari <[email protected]>

* docs(officeenv_sandbox): say when the task-end stop ends a Stirrup run

Stirrup cannot run without a finish tool, so with its default finish tool most runs end when the model calls
finish. The environment server's task-end stop ends a run that calls `user complete-task`, before its next model
call. Pi's config sets finish_tool_names: [], so for Pi the stop is the normal end. The README now says so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(core): release_all stops the lent sandboxes while a lend is still starting

release_all waited for every start in flight before it stopped any lent
sandbox, all inside one time limit. One slow start at shutdown then left
every lent sandbox running until its TTL. Now the lent sandboxes stop at
once, and each starting sandbox is stopped when its start ends.

The new test fails before this change (no sandbox stopped) and passes
after it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Yi-Fu Wu <[email protected]>

* fix(officeenv_sandbox): keep the agent and environment servers on 127.0.0.1

NeMo RL sets default_host to the node's address, and an explicit
default_host applies to every server, not only to the types in
absolute_ip_server_types. A sandbox's network rule opens every port of an
allowed host. So code in a sandbox could call the agent and environment
servers: run Pi on Gym's host (/v1/responses without a session), start
episodes (/run) and stop another episode's run
(/rollouts/{rollout_id}/stop).

Each harness config now sets host: 127.0.0.1 on its agent and its
environment server. No sandbox calls them: each harness in a sandbox calls
only the model server and the resources server, and NeMo RL calls /run from
the same node. Without default_host, Gym already binds them to 127.0.0.1.
The comment in officeenv_opensandbox.yaml and the README now say this.

The new config test resolves every harness config under
default_host: 10.0.0…
JeffPengCoder pushed a commit to JeffPengCoder/Gym that referenced this pull request Dec 1, 2026
…n attempt (NVIDIA-NeMo#6700)

* fix(sandbox): add one shielded, bounded stop for sandbox owners

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]>

* feat(sandbox): make the sandbox checkpointer the public OwnedSandboxes

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]>

* feat(sandbox): stop, start and export owned sandboxes safely under load

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]>

* feat(sandbox): typed network rule and provider capabilities for owners

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]>

* feat(agents): borrow lent sandboxes and type the agent's own sandbox

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]>

* feat(environment): start and lend a sandbox for each single-agent-turn 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]>

* fix(sandbox): build no provider for a refused owner config

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]>

* fix(sandbox): stop a create cancelled inside the provider's start

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]>

* fix(sandbox): bound a whole owned stop by one limit and require ttl_s

- 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
  NVIDIA-NeMo#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]>

* style(sandbox): sort the swebench checkpoint server's imports

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): do not cut a queued owned stop short, and start nothing 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]>

* fix(sandbox): true reconnect capabilities, critpt specs, and a glossary 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]>

* fix(environment): keep the lent sandbox out of results and check its 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]>

* fix(agents): let SandboxSession release a borrowed sandbox, and borrow from server_runtime

- BorrowedSandbox.stop and disconnect dropped the timeout_s keyword that
  AsyncSandbox.stop and disconnect take since NVIDIA-NeMo#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]>

* fix(sandbox): keep the provider check after the dry-run return

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]>

* fix(sandbox): settle cancelled starts and forks, and stop running sandboxes first at shutdown

- A cancelled caller now waits for its start through any further
  cancellation, bounded by the spec's readiness wait plus a stop's limit
  (a slow Enroot create took longer than one stop's limit), and stops the
  sandbox the start produced before the cancellation goes on. Restore forks
  take the same path: a restore cancelled inside a fork's create left the
  fork running untracked.
- aclose() stops the sandboxes that are running before it waits for creates
  still pending, which may now take their whole start to settle.
- The rollback of a failed start is a module function again, so a test that
  drives AsyncSandbox.start_with_setup over a mocked sandbox sees its stop.
  The litmus_agent and deepswe_external1 tests expect the start's error,
  with the failed stop as its context, as this PR documents.
- The parallelism description and the superseded stop's comment say what
  the code does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): try each key once per aclose

The shutdown's second pass, after pending creates settle, stops only the keys
the first pass did not try, so a key whose stop failed stays tracked for the
next call as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): check the provider before the dry-run return

A dry run now reports a rule the provider cannot apply, as it reports an
unsupported num_workers. The dry-run test's mocked config sets no
sandbox_provider.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): keep the lent sandbox's access off verify response types

BaseVerifyResponse inherits BaseVerifyRequest, so the sandbox_access field
put a sandbox descriptor into every verify response and episode result type,
which Harbor's response policy test refuses. The lent sandbox now travels only
on the wire, as NG_SANDBOX_ACCESS_KEY in the /verify body: a verifier that
grades in it declares the field on its own request model, and single_agent_turn
still drops it from the verify reply. A test now checks that no
single_agent_turn result type declares a sandbox field.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): defer owner checkpoint state and preserve old imports

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): keep the old checkpointer name and let non-exporting servers own sandboxes

- SandboxSessionCheckpointer, exported from nemo_gym.server_runtime before the
  rename, resolves to OwnedSandboxes with a deprecation warning (removed in 0.10.0).
- self.sandboxes no longer needs checkpoint.state_dir: a server that never exports,
  such as an agent, gets an instance without a snapshot index, and only export says
  the directory is missing. A relative or unwritable state_dir is still refused,
  now before the provider is built.
- New lines in the moved module and its tests use X | None.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): serialize discard with pending starts and hide unready entries

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): validate portable network access before serving requests

Signed-off-by: yaoyu-33 <[email protected]>

* refactor(sandbox): share harness config independently of sandbox ownership

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): show an owned sandbox only once it is ready, and let discard wait for its keys

- get(), `in`, access() and export now agree: a sandbox still starting, or one whose
  start failed and whose stop failed too, is none of theirs. keys still lists it, so a
  stop or aclose stops it.
- discard() takes each key's lock, in the order a restore takes them, so a key whose
  create is still starting is discarded once the start ends instead of leaving the
  sandbox running untracked.
- Glossary: owner concurrency.
- Test start_with_setup's own rollback: a setup that raises and a stop that fails.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* docs(sandbox): clarify portable network options and legacy subclass settings

Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): assert unready entries remain cleanup-only

Signed-off-by: yaoyu-33 <[email protected]>

* fix(swebench): forget tracked sandboxes after their stop

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): check the declared sandbox blocks at startup and tighten the network rule

- A server lists the blocks it starts through self.sandboxes in
  owned_sandbox_blocks, with the config field naming each block's provider.
  Startup checks each listed block against that provider, and refuses a
  restricted rule in any other SandboxConfig of the config, nested ones too,
  since nothing would apply it. This replaces picking provider fields by their
  name suffix.
- Startup logs the other servers that share a host a rule allows.
- allowed_hosts takes a host name, '*.' and a domain, or an IP address or CIDR
  block; a URL, a port, a path or a loopback address is refused.
- A subclass's own network setting refuses model_server, tool_servers and
  allowed_hosts, which would do nothing beside it.
- SandboxConfig.spec takes NetworkRuleOptions built for the block's own rule,
  so no plain mapping stands in for a restricted rule.
- E2B applies every rule through its network_policy mapping; Docker's
  no_network also checks the provider's create.extra_run_args.
- Glossary: network stays the name; the per-server network_access fields are
  deprecated as servers move onto the block's rule.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(swebench): format checkpoint tracking guard

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): validate owner metadata before constructing a provider

Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): shorten the stop limit where a cancelled restore's fork hangs on purpose

The cancelled restore now lets the fork run for the stop limit before it cuts it
short, so the test waited the full 120 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format network rule validation

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): accept argv in the borrowed exec contract

Signed-off-by: yaoyu-33 <[email protected]>

* fix(agents): name the harness sandbox config for what it is, and say what a borrow does not enforce

- AgentSandboxConfig becomes HarnessSandboxConfig: the sandbox a harness runs in,
  whether an Environment Server starts and lends it or an agent starts its own
  because nothing was lent. Its spec() takes the owner's NetworkRuleOptions, and
  its docstring says an adopting agent refuses its own network_access beside the
  config's network.
- The borrow module says the refusals are advisory, the raw .provider included,
  and that the repository check follows once agents use borrow().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): keep metadata validation in the network layer

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): validate provider metadata before client creation

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): sort harness config facade import

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format provider resolver cases

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): read the global config at startup only when a sandbox block is declared or lent

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): keep each provider field's snapshots apart and retry a failed provider close

- The owner on a server's other provider field kept its snapshot index and names
  under "<server>.<field>", which a server named that way also uses: the two
  releases then deleted each other's retained snapshots. Such an owner now keeps
  its index under <server>/providers/<field>/ and hashes "<server>/<field>" into
  its snapshot names; no server name has a "/". The sandbox_provider owner keeps
  its paths and names.
- The provider counts as closed only once its close succeeded, one close at a
  time, so aclose retries a close that failed or was cancelled and never repeats
  one that succeeded.
- Regressions: overlapping snapshot ids across the two owners, an unwritable
  state_dir from a real checkpoint config, and failed, cancelled and concurrent
  provider closes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(agents): end the harness sandbox config test with one newline

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): update network fixtures and use a real dry-run config

Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): list the attempt sandbox block among the blocks single_agent_turn starts

Startup now checks only the sandbox blocks a server lists in owned_sandbox_blocks, and refuses a restricted network
rule anywhere else. single_agent_turn starts the attempt sandbox from sandbox_config through self.sandboxes, so it
lists that block against sandbox_provider.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format renamed grader network fixture

Signed-off-by: yaoyu-33 <[email protected]>

* test(server): supply a real global config to the dry-run fixture

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): publish owned starts only after file setup succeeds

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): register the checkpoint compatibility alias once

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format the server ownership declaration

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format borrowed command signature

Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): retain refusal checks after stack integration

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): preserve Docker argument-list execution

Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): reserve verifier sandbox access for the attempt owner

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): track and throttle cancelled start rollbacks

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): require declared OpenSandbox egress enforcement

Signed-off-by: yaoyu-33 <[email protected]>

* test(env): declare egress enforcement for the tool grant check

Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): fail an attempt whose Resources Server lends a sandbox when this server owns one

With sandbox_provider set, the Environment Server owns the attempt's sandbox: it starts it, lends it and stops it.
A Resources Server only borrows, so a resources seed that lends a sandbox of its own now fails the attempt as a
configuration error instead of silently replacing the one this server would start. Without sandbox_provider, a
sandbox the resources seed lends is still lent on to the agent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* docs(sandbox): say the Environment Server owns the attempt's sandbox and others borrow it

The owner description named a Resources Server as a lender of the attempt's sandbox on equal terms with the
Environment Server. The Environment Server owns the sandbox an attempt runs in and lends it to the agent and to
the Resources Server; a Resources Server owns a sandbox only for a grader that runs code in an attempt without one.
Today's Resources lenders and agent-owned harness sandboxes are described as what moves onto it. An export also
waits for borrowers' commands, not only the owner's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* docs(sandbox): say a lending server lends to the Resources Server as well as the agent

lends_sandboxes described lending to agents only. An Environment Server lends an attempt's sandbox to the agent for
its turn and to the Resources Server for /verify, and both borrowers need a provider that reconnects.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): a Resources Server grades in a sandbox it never started

The Environment Server owns an attempt's sandbox and lends it; the Resources Server borrows it for /verify. The test
lends from one owner and borrows with only the access and the borrower's own copy of the merged config: the
provider block is found by the name the access carries, commands run in the lent working directory, the borrower
cannot stop the sandbox, and only the owner's stop ends it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(environment): assert the single-owner refusal's outcome, and enforce egress on the OpenSandbox test block

A handled seed failure always carries a failure report, so the refusal test checks the failure and that no provider
was built instead. OpenSandbox applies restricted rules only for a deployment that declares
networking.enforces_network_policy, so the tool-grant startup test declares it, and the README names the case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): validate attempt sandbox dependencies and relay placement

Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): prepare the sandbox workdir before lending it

Signed-off-by: yaoyu-33 <[email protected]>

* docs(environment): clarify the scope of a lent sandbox

Signed-off-by: yaoyu-33 <[email protected]>

---------

Signed-off-by: Ananth Subramaniam <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Co-authored-by: Ananth Subramaniam <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
yaoyu-33 added a commit to yaoyu-33/Gym that referenced this pull request Dec 2, 2026
…ment lends (NVIDIA-NeMo#6701)

* fix(sandbox): add one shielded, bounded stop for sandbox owners

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]>

* feat(sandbox): make the sandbox checkpointer the public OwnedSandboxes

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]>

* feat(sandbox): stop, start and export owned sandboxes safely under load

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]>

* feat(sandbox): typed network rule and provider capabilities for owners

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]>

* feat(agents): borrow lent sandboxes and type the agent's own sandbox

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]>

* feat(environment): start and lend a sandbox for each single-agent-turn 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]>

* fix(sandbox): build no provider for a refused owner config

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]>

* fix(sandbox): stop a create cancelled inside the provider's start

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]>

* fix(sandbox): bound a whole owned stop by one limit and require ttl_s

- 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
  NVIDIA-NeMo#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]>

* feat(agent): run Simple Agent's turn loop in the sandbox its environment lends

With sandboxed: true, Simple Agent borrows the sandbox its agent session is
lent, installs a private Python runtime in it with this server's nemo_gym
sources, and runs each activation through sandbox_runner.py under Gym's
process supervisor. The runner builds the same SimpleAgent and calls the same
_create_episode loop as in process, calls only the model server, and returns
the output items unchanged. A seed that lends no sandbox is refused and a
sandboxed agent never runs the loop in its own process. In-process mode stays
the default.

reward_profile and the rollout timeout summary now import numpy, pandas and
scipy where they use them, so an agent server, and the sandbox runtime, no
longer load them on import.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): sort the swebench checkpoint server's imports

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): do not cut a queued owned stop short, and start nothing 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]>

* fix(agent): build OmegaConf's source-only antlr4 runtime for the sandboxed loop

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): true reconnect capabilities, critpt specs, and a glossary 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]>

* fix(environment): keep the lent sandbox out of results and check its 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]>

* fix(agents): let SandboxSession release a borrowed sandbox, and borrow from server_runtime

- BorrowedSandbox.stop and disconnect dropped the timeout_s keyword that
  AsyncSandbox.stop and disconnect take since NVIDIA-NeMo#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]>

* fix(sandbox): keep the provider check after the dry-run return

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]>

* fix(agent): close, error and staging gaps in Simple Agent's sandbox mode

- Retiring a sandboxed session closes it, so the loop stops and the
  borrowed client is released.
- A model server's HTTP error raised in the sandbox comes back with its
  status, headers and body, as the agent boundary reports one raised in
  process.
- Stage only the settings the loop reads; refuse a direct_http grant the
  sandbox cannot reach and a subclass that changes the agent loop.
- Write the harness archive in a private directory, rewrite it when it is
  gone or changed, and build it off the event loop; create each
  activation's directory; key the runtime only when it is used.
- Drop the rollout-stop hook until stops are enforced in the sandbox, and
  use the base session_close_timeout_seconds and the harnesses'
  sandbox_runner_timeout_seconds name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(agent): expect borrow() under server_runtime in the harness archive

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): settle cancelled starts and forks, and stop running sandboxes first at shutdown

- A cancelled caller now waits for its start through any further
  cancellation, bounded by the spec's readiness wait plus a stop's limit
  (a slow Enroot create took longer than one stop's limit), and stops the
  sandbox the start produced before the cancellation goes on. Restore forks
  take the same path: a restore cancelled inside a fork's create left the
  fork running untracked.
- aclose() stops the sandboxes that are running before it waits for creates
  still pending, which may now take their whole start to settle.
- The rollback of a failed start is a module function again, so a test that
  drives AsyncSandbox.start_with_setup over a mocked sandbox sees its stop.
  The litmus_agent and deepswe_external1 tests expect the start's error,
  with the failed stop as its context, as this PR documents.
- The parallelism description and the superseded stop's comment say what
  the code does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): try each key once per aclose

The shutdown's second pass, after pending creates settle, stops only the keys
the first pass did not try, so a key whose stop failed stays tracked for the
next call as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): check the provider before the dry-run return

A dry run now reports a rule the provider cannot apply, as it reports an
unsupported num_workers. The dry-run test's mocked config sets no
sandbox_provider.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): keep the lent sandbox's access off verify response types

BaseVerifyResponse inherits BaseVerifyRequest, so the sandbox_access field
put a sandbox descriptor into every verify response and episode result type,
which Harbor's response policy test refuses. The lent sandbox now travels only
on the wire, as NG_SANDBOX_ACCESS_KEY in the /verify body: a verifier that
grades in it declares the field on its own request model, and single_agent_turn
still drops it from the verify reply. A test now checks that no
single_agent_turn result type declares a sandbox field.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(agent): cover SandboxLoop, and load it only for a sandboxed agent

Simple Agent imports its sandbox helpers only on the sandboxed path, so an
agent whose loop runs in process never loads them. New tests drive
SandboxLoop against a fake borrowed sandbox: installing and checking the
runtime, unpacking this server's sources, staging each activation's input in
its own directory, returning the runner's output, raising the loop's error or
a missing output, and releasing the sandbox on close.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(agent): patch the frozen sandbox runtime's methods on its class

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): defer owner checkpoint state and preserve old imports

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): keep the old checkpointer name and let non-exporting servers own sandboxes

- SandboxSessionCheckpointer, exported from nemo_gym.server_runtime before the
  rename, resolves to OwnedSandboxes with a deprecation warning (removed in 0.10.0).
- self.sandboxes no longer needs checkpoint.state_dir: a server that never exports,
  such as an agent, gets an instance without a snapshot index, and only export says
  the directory is missing. A relative or unwritable state_dir is still refused,
  now before the provider is built.
- New lines in the moved module and its tests use X | None.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): serialize discard with pending starts and hide unready entries

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): validate portable network access before serving requests

Signed-off-by: yaoyu-33 <[email protected]>

* refactor(sandbox): share harness config independently of sandbox ownership

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): show an owned sandbox only once it is ready, and let discard wait for its keys

- get(), `in`, access() and export now agree: a sandbox still starting, or one whose
  start failed and whose stop failed too, is none of theirs. keys still lists it, so a
  stop or aclose stops it.
- discard() takes each key's lock, in the order a restore takes them, so a key whose
  create is still starting is discarded once the start ends instead of leaving the
  sandbox running untracked.
- Glossary: owner concurrency.
- Test start_with_setup's own rollback: a setup that raises and a stop that fails.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* docs(sandbox): clarify portable network options and legacy subclass settings

Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): assert unready entries remain cleanup-only

Signed-off-by: yaoyu-33 <[email protected]>

* fix(swebench): forget tracked sandboxes after their stop

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): check the declared sandbox blocks at startup and tighten the network rule

- A server lists the blocks it starts through self.sandboxes in
  owned_sandbox_blocks, with the config field naming each block's provider.
  Startup checks each listed block against that provider, and refuses a
  restricted rule in any other SandboxConfig of the config, nested ones too,
  since nothing would apply it. This replaces picking provider fields by their
  name suffix.
- Startup logs the other servers that share a host a rule allows.
- allowed_hosts takes a host name, '*.' and a domain, or an IP address or CIDR
  block; a URL, a port, a path or a loopback address is refused.
- A subclass's own network setting refuses model_server, tool_servers and
  allowed_hosts, which would do nothing beside it.
- SandboxConfig.spec takes NetworkRuleOptions built for the block's own rule,
  so no plain mapping stands in for a restricted rule.
- E2B applies every rule through its network_policy mapping; Docker's
  no_network also checks the provider's create.extra_run_args.
- Glossary: network stays the name; the per-server network_access fields are
  deprecated as servers move onto the block's rule.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(swebench): format checkpoint tracking guard

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): validate owner metadata before constructing a provider

Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): shorten the stop limit where a cancelled restore's fork hangs on purpose

The cancelled restore now lets the fork run for the stop limit before it cuts it
short, so the test waited the full 120 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format network rule validation

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): accept argv in the borrowed exec contract

Signed-off-by: yaoyu-33 <[email protected]>

* fix(agents): name the harness sandbox config for what it is, and say what a borrow does not enforce

- AgentSandboxConfig becomes HarnessSandboxConfig: the sandbox a harness runs in,
  whether an Environment Server starts and lends it or an agent starts its own
  because nothing was lent. Its spec() takes the owner's NetworkRuleOptions, and
  its docstring says an adopting agent refuses its own network_access beside the
  config's network.
- The borrow module says the refusals are advisory, the raw .provider included,
  and that the repository check follows once agents use borrow().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): keep metadata validation in the network layer

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): validate provider metadata before client creation

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): sort harness config facade import

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format provider resolver cases

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): read the global config at startup only when a sandbox block is declared or lent

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): keep each provider field's snapshots apart and retry a failed provider close

- The owner on a server's other provider field kept its snapshot index and names
  under "<server>.<field>", which a server named that way also uses: the two
  releases then deleted each other's retained snapshots. Such an owner now keeps
  its index under <server>/providers/<field>/ and hashes "<server>/<field>" into
  its snapshot names; no server name has a "/". The sandbox_provider owner keeps
  its paths and names.
- The provider counts as closed only once its close succeeded, one close at a
  time, so aclose retries a close that failed or was cancelled and never repeats
  one that succeeded.
- Regressions: overlapping snapshot ids across the two owners, an unwritable
  state_dir from a real checkpoint config, and failed, cancelled and concurrent
  provider closes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(agents): end the harness sandbox config test with one newline

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): update network fixtures and use a real dry-run config

Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): list the attempt sandbox block among the blocks single_agent_turn starts

Startup now checks only the sandbox blocks a server lists in owned_sandbox_blocks, and refuses a restricted network
rule anywhere else. single_agent_turn starts the attempt sandbox from sandbox_config through self.sandboxes, so it
lists that block against sandbox_provider.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format renamed grader network fixture

Signed-off-by: yaoyu-33 <[email protected]>

* test(server): supply a real global config to the dry-run fixture

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): publish owned starts only after file setup succeeds

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): register the checkpoint compatibility alias once

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format the server ownership declaration

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format borrowed command signature

Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): retain refusal checks after stack integration

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): preserve Docker argument-list execution

Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): reserve verifier sandbox access for the attempt owner

Signed-off-by: yaoyu-33 <[email protected]>

* fix(agent): preserve sandboxed failure reports and filter staged inputs

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): track and throttle cancelled start rollbacks

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): require declared OpenSandbox egress enforcement

Signed-off-by: yaoyu-33 <[email protected]>

* test(env): declare egress enforcement for the tool grant check

Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): fail an attempt whose Resources Server lends a sandbox when this server owns one

With sandbox_provider set, the Environment Server owns the attempt's sandbox: it starts it, lends it and stops it.
A Resources Server only borrows, so a resources seed that lends a sandbox of its own now fails the attempt as a
configuration error instead of silently replacing the one this server would start. Without sandbox_provider, a
sandbox the resources seed lends is still lent on to the agent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* feat(agent): run Simple Agent's loop in the sandbox its seed lends, with no agent switch

The Environment Server owns where an attempt runs: when it lends a sandbox, the agent borrows it. Simple Agent now
runs a session's loop in the sandbox its seed lends, and in process when the seed lends none, instead of a
sandboxed setting that had to agree with the environment's. A session lent a sandbox still never runs its loop in
the agent server's process, a restored one included, and a subclass that changes the loop refuses a lent sandbox.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* docs(sandbox): say the Environment Server owns the attempt's sandbox and others borrow it

The owner description named a Resources Server as a lender of the attempt's sandbox on equal terms with the
Environment Server. The Environment Server owns the sandbox an attempt runs in and lends it to the agent and to
the Resources Server; a Resources Server owns a sandbox only for a grader that runs code in an attempt without one.
Today's Resources lenders and agent-owned harness sandboxes are described as what moves onto it. An export also
waits for borrowers' commands, not only the owner's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* docs(sandbox): say a lending server lends to the Resources Server as well as the agent

lends_sandboxes described lending to agents only. An Environment Server lends an attempt's sandbox to the agent for
its turn and to the Resources Server for /verify, and both borrowers need a provider that reconnects.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): a Resources Server grades in a sandbox it never started

The Environment Server owns an attempt's sandbox and lends it; the Resources Server borrows it for /verify. The test
lends from one owner and borrows with only the access and the borrower's own copy of the merged config: the
provider block is found by the name the access carries, commands run in the lent working directory, the borrower
cannot stop the sandbox, and only the owner's stop ends it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(environment): assert the single-owner refusal's outcome, and enforce egress on the OpenSandbox test block

A handled seed failure always carries a failure report, so the refusal test checks the failure and that no provider
was built instead. OpenSandbox applies restricted rules only for a deployment that declares
networking.enforces_network_policy, so the tool-grant startup test declares it, and the README names the case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(simple_agent): stage a subclass's loop settings and carry the sandboxed loop's failures back

- The sandboxed loop was staged with exclude_unset, so a subclass's own default, such as a
  one-step agent's max_steps, fell back to SimpleAgentConfig's and the loop ran without a step
  limit. It is now staged with every set or defaulted value, without None.
- The runner collects the failures its loop observes, such as those a model server recovered
  from and forwarded with its reply, and the agent adds them to its request's failure log, as
  the in-process loop's request middleware does.
- The runner deletes its input, which holds the tool grant's and model server's cookies, once
  it has read it.
- Core tests drive Simple Agent's lent-sandbox paths (seed, refusals, install failure, activation,
  close, retire, no host fallback, subclass refusal) with a stand-in loop, so the agent's side
  counts toward core coverage without the sandbox runtime.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(agent): preserve the borrowed sandbox session contract

Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): validate attempt sandbox dependencies and relay placement

Signed-off-by: yaoyu-33 <[email protected]>

* fix(agent): preserve IPv6 literals in sandbox model endpoints

Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): prepare the sandbox workdir before lending it

Signed-off-by: yaoyu-33 <[email protected]>

* docs(environment): clarify the scope of a lent sandbox

Signed-off-by: yaoyu-33 <[email protected]>

* fix(agent): advertise Harbor model reachability and report runner timeouts

Signed-off-by: yaoyu-33 <[email protected]>

---------

Signed-off-by: Ananth Subramaniam <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Co-authored-by: Ananth Subramaniam <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
yaoyu-33 added a commit that referenced this pull request Dec 3, 2026
…ronment Server, with per-task verifier modes (#6752)

* fix(sandbox): add one shielded, bounded stop for sandbox owners

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]>

* feat(sandbox): make the sandbox checkpointer the public OwnedSandboxes

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]>

* feat(sandbox): stop, start and export owned sandboxes safely under load

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]>

* feat(sandbox): typed network rule and provider capabilities for owners

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]>

* feat(agents): borrow lent sandboxes and type the agent's own sandbox

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]>

* feat(environment): start and lend a sandbox for each single-agent-turn 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]>

* fix(sandbox): build no provider for a refused owner config

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]>

* fix(sandbox): stop a create cancelled inside the provider's start

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]>

* fix(sandbox): bound a whole owned stop by one limit and require ttl_s

- 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]>

* feat(agent): run Simple Agent's turn loop in the sandbox its environment lends

With sandboxed: true, Simple Agent borrows the sandbox its agent session is
lent, installs a private Python runtime in it with this server's nemo_gym
sources, and runs each activation through sandbox_runner.py under Gym's
process supervisor. The runner builds the same SimpleAgent and calls the same
_create_episode loop as in process, calls only the model server, and returns
the output items unchanged. A seed that lends no sandbox is refused and a
sandboxed agent never runs the loop in its own process. In-process mode stays
the default.

reward_profile and the rollout timeout summary now import numpy, pandas and
scipy where they use them, so an agent server, and the sandbox runtime, no
longer load them on import.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): sort the swebench checkpoint server's imports

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): do not cut a queued owned stop short, and start nothing 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]>

* fix(agent): build OmegaConf's source-only antlr4 runtime for the sandboxed loop

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): true reconnect capabilities, critpt specs, and a glossary 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]>

* fix(environment): keep the lent sandbox out of results and check its 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]>

* fix(agents): let SandboxSession release a borrowed sandbox, and borrow 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]>

* fix(sandbox): keep the provider check after the dry-run return

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]>

* fix(agent): close, error and staging gaps in Simple Agent's sandbox mode

- Retiring a sandboxed session closes it, so the loop stops and the
  borrowed client is released.
- A model server's HTTP error raised in the sandbox comes back with its
  status, headers and body, as the agent boundary reports one raised in
  process.
- Stage only the settings the loop reads; refuse a direct_http grant the
  sandbox cannot reach and a subclass that changes the agent loop.
- Write the harness archive in a private directory, rewrite it when it is
  gone or changed, and build it off the event loop; create each
  activation's directory; key the runtime only when it is used.
- Drop the rollout-stop hook until stops are enforced in the sandbox, and
  use the base session_close_timeout_seconds and the harnesses'
  sandbox_runner_timeout_seconds name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(agent): expect borrow() under server_runtime in the harness archive

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): settle cancelled starts and forks, and stop running sandboxes first at shutdown

- A cancelled caller now waits for its start through any further
  cancellation, bounded by the spec's readiness wait plus a stop's limit
  (a slow Enroot create took longer than one stop's limit), and stops the
  sandbox the start produced before the cancellation goes on. Restore forks
  take the same path: a restore cancelled inside a fork's create left the
  fork running untracked.
- aclose() stops the sandboxes that are running before it waits for creates
  still pending, which may now take their whole start to settle.
- The rollback of a failed start is a module function again, so a test that
  drives AsyncSandbox.start_with_setup over a mocked sandbox sees its stop.
  The litmus_agent and deepswe_external1 tests expect the start's error,
  with the failed stop as its context, as this PR documents.
- The parallelism description and the superseded stop's comment say what
  the code does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): try each key once per aclose

The shutdown's second pass, after pending creates settle, stops only the keys
the first pass did not try, so a key whose stop failed stays tracked for the
next call as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): check the provider before the dry-run return

A dry run now reports a rule the provider cannot apply, as it reports an
unsupported num_workers. The dry-run test's mocked config sets no
sandbox_provider.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): keep the lent sandbox's access off verify response types

BaseVerifyResponse inherits BaseVerifyRequest, so the sandbox_access field
put a sandbox descriptor into every verify response and episode result type,
which Harbor's response policy test refuses. The lent sandbox now travels only
on the wire, as NG_SANDBOX_ACCESS_KEY in the /verify body: a verifier that
grades in it declares the field on its own request model, and single_agent_turn
still drops it from the verify reply. A test now checks that no
single_agent_turn result type declares a sandbox field.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(agent): cover SandboxLoop, and load it only for a sandboxed agent

Simple Agent imports its sandbox helpers only on the sandboxed path, so an
agent whose loop runs in process never loads them. New tests drive
SandboxLoop against a fake borrowed sandbox: installing and checking the
runtime, unpacking this server's sources, staging each activation's input in
its own directory, returning the runner's output, raising the loop's error or
a missing output, and releasing the sandbox on close.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(agent): patch the frozen sandbox runtime's methods on its class

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): defer owner checkpoint state and preserve old imports

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): keep the old checkpointer name and let non-exporting servers own sandboxes

- SandboxSessionCheckpointer, exported from nemo_gym.server_runtime before the
  rename, resolves to OwnedSandboxes with a deprecation warning (removed in 0.10.0).
- self.sandboxes no longer needs checkpoint.state_dir: a server that never exports,
  such as an agent, gets an instance without a snapshot index, and only export says
  the directory is missing. A relative or unwritable state_dir is still refused,
  now before the provider is built.
- New lines in the moved module and its tests use X | None.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): serialize discard with pending starts and hide unready entries

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): validate portable network access before serving requests

Signed-off-by: yaoyu-33 <[email protected]>

* refactor(sandbox): share harness config independently of sandbox ownership

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): show an owned sandbox only once it is ready, and let discard wait for its keys

- get(), `in`, access() and export now agree: a sandbox still starting, or one whose
  start failed and whose stop failed too, is none of theirs. keys still lists it, so a
  stop or aclose stops it.
- discard() takes each key's lock, in the order a restore takes them, so a key whose
  create is still starting is discarded once the start ends instead of leaving the
  sandbox running untracked.
- Glossary: owner concurrency.
- Test start_with_setup's own rollback: a setup that raises and a stop that fails.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* docs(sandbox): clarify portable network options and legacy subclass settings

Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): assert unready entries remain cleanup-only

Signed-off-by: yaoyu-33 <[email protected]>

* fix(swebench): forget tracked sandboxes after their stop

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): check the declared sandbox blocks at startup and tighten the network rule

- A server lists the blocks it starts through self.sandboxes in
  owned_sandbox_blocks, with the config field naming each block's provider.
  Startup checks each listed block against that provider, and refuses a
  restricted rule in any other SandboxConfig of the config, nested ones too,
  since nothing would apply it. This replaces picking provider fields by their
  name suffix.
- Startup logs the other servers that share a host a rule allows.
- allowed_hosts takes a host name, '*.' and a domain, or an IP address or CIDR
  block; a URL, a port, a path or a loopback address is refused.
- A subclass's own network setting refuses model_server, tool_servers and
  allowed_hosts, which would do nothing beside it.
- SandboxConfig.spec takes NetworkRuleOptions built for the block's own rule,
  so no plain mapping stands in for a restricted rule.
- E2B applies every rule through its network_policy mapping; Docker's
  no_network also checks the provider's create.extra_run_args.
- Glossary: network stays the name; the per-server network_access fields are
  deprecated as servers move onto the block's rule.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(swebench): format checkpoint tracking guard

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): validate owner metadata before constructing a provider

Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): shorten the stop limit where a cancelled restore's fork hangs on purpose

The cancelled restore now lets the fork run for the stop limit before it cuts it
short, so the test waited the full 120 s.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format network rule validation

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): accept argv in the borrowed exec contract

Signed-off-by: yaoyu-33 <[email protected]>

* fix(agents): name the harness sandbox config for what it is, and say what a borrow does not enforce

- AgentSandboxConfig becomes HarnessSandboxConfig: the sandbox a harness runs in,
  whether an Environment Server starts and lends it or an agent starts its own
  because nothing was lent. Its spec() takes the owner's NetworkRuleOptions, and
  its docstring says an adopting agent refuses its own network_access beside the
  config's network.
- The borrow module says the refusals are advisory, the raw .provider included,
  and that the repository check follows once agents use borrow().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): keep metadata validation in the network layer

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): validate provider metadata before client creation

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): sort harness config facade import

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format provider resolver cases

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): read the global config at startup only when a sandbox block is declared or lent

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): keep each provider field's snapshots apart and retry a failed provider close

- The owner on a server's other provider field kept its snapshot index and names
  under "<server>.<field>", which a server named that way also uses: the two
  releases then deleted each other's retained snapshots. Such an owner now keeps
  its index under <server>/providers/<field>/ and hashes "<server>/<field>" into
  its snapshot names; no server name has a "/". The sandbox_provider owner keeps
  its paths and names.
- The provider counts as closed only once its close succeeded, one close at a
  time, so aclose retries a close that failed or was cancelled and never repeats
  one that succeeded.
- Regressions: overlapping snapshot ids across the two owners, an unwritable
  state_dir from a real checkpoint config, and failed, cancelled and concurrent
  provider closes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(agents): end the harness sandbox config test with one newline

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): update network fixtures and use a real dry-run config

Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): list the attempt sandbox block among the blocks single_agent_turn starts

Startup now checks only the sandbox blocks a server lists in owned_sandbox_blocks, and refuses a restricted network
rule anywhere else. single_agent_turn starts the attempt sandbox from sandbox_config through self.sandboxes, so it
lists that block against sandbox_provider.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format renamed grader network fixture

Signed-off-by: yaoyu-33 <[email protected]>

* test(server): supply a real global config to the dry-run fixture

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): publish owned starts only after file setup succeeds

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): register the checkpoint compatibility alias once

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format the server ownership declaration

Signed-off-by: yaoyu-33 <[email protected]>

* style(sandbox): format borrowed command signature

Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): retain refusal checks after stack integration

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): preserve Docker argument-list execution

Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): reserve verifier sandbox access for the attempt owner

Signed-off-by: yaoyu-33 <[email protected]>

* fix(agent): preserve sandboxed failure reports and filter staged inputs

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): track and throttle cancelled start rollbacks

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): require declared OpenSandbox egress enforcement

Signed-off-by: yaoyu-33 <[email protected]>

* test(env): declare egress enforcement for the tool grant check

Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): fail an attempt whose Resources Server lends a sandbox when this server owns one

With sandbox_provider set, the Environment Server owns the attempt's sandbox: it starts it, lends it and stops it.
A Resources Server only borrows, so a resources seed that lends a sandbox of its own now fails the attempt as a
configuration error instead of silently replacing the one this server would start. Without sandbox_provider, a
sandbox the resources seed lends is still lent on to the agent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* feat(agent): run Simple Agent's loop in the sandbox its seed lends, with no agent switch

The Environment Server owns where an attempt runs: when it lends a sandbox, the agent borrows it. Simple Agent now
runs a session's loop in the sandbox its seed lends, and in process when the seed lends none, instead of a
sandboxed setting that had to agree with the environment's. A session lent a sandbox still never runs its loop in
the agent server's process, a restored one included, and a subclass that changes the loop refuses a lent sandbox.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* docs(sandbox): say the Environment Server owns the attempt's sandbox and others borrow it

The owner description named a Resources Server as a lender of the attempt's sandbox on equal terms with the
Environment Server. The Environment Server owns the sandbox an attempt runs in and lends it to the agent and to
the Resources Server; a Resources Server owns a sandbox only for a grader that runs code in an attempt without one.
Today's Resources lenders and agent-owned harness sandboxes are described as what moves onto it. An export also
waits for borrowers' commands, not only the owner's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* docs(sandbox): say a lending server lends to the Resources Server as well as the agent

lends_sandboxes described lending to agents only. An Environment Server lends an attempt's sandbox to the agent for
its turn and to the Resources Server for /verify, and both borrowers need a provider that reconnects.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): a Resources Server grades in a sandbox it never started

The Environment Server owns an attempt's sandbox and lends it; the Resources Server borrows it for /verify. The test
lends from one owner and borrows with only the access and the borrower's own copy of the merged config: the
provider block is found by the name the access carries, commands run in the lent working directory, the borrower
cannot stop the sandbox, and only the owner's stop ends it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(environment): assert the single-owner refusal's outcome, and enforce egress on the OpenSandbox test block

A handled seed failure always carries a failure report, so the refusal test checks the failure and that no provider
was built instead. OpenSandbox applies restricted rules only for a deployment that declares
networking.enforces_network_policy, so the tool-grant startup test declares it, and the README names the case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* feat(environment): start, lend and stop each attempt's sandbox group in the base Environment Server

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* feat(environment): let tasks and graders that execute nothing opt out of the attempt sandbox

The base Environment Server decides at seed who borrows the attempt's
sandbox group: the agent, the grader, both, or neither. A pure QA task and
a grader that executes nothing may opt out (sandbox_opt_out); a task with
tools and a grader whose Resources Server declares grader_runs_code may not.
When only the grader needs it, a group of its own starts before /verify.

The Resources Server declares at seed what the group holds
(SandboxGroupSpec: image, files, sidecars) and may prepare the task in it
through /prepare_sandbox.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* test(environment): run another Environment Server type through the attempt sandbox lifecycle

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): let a verifier opt out of the attempt sandbox only when its server declares it executes nothing

Review fixes:
- The verifier opt-out fails closed: a Resources Server declares
  verifier_executes_nothing, and an undeclared verifier, or one whose seed
  reply drops the declaration, keeps its sandbox.
- Name the verifier as the glossary does (sandbox_opt_out.verifier).
- Refuse at seed, before the agent's turn, a group no attempt can start.
- Stop the group once /verify replies; mark an episode with a plan a
  restart, so declared files and environment never reach a checkpoint.
- Move the seed-time and verify-time steps into the base class
  (seed_attempt_sandbox, verifier_sandbox_access, release_attempt_sandbox).
- Send the seed's identity and task_data to /prepare_sandbox.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* feat(environment): cut a verifier-only group's egress and give each sidecar its own

Requests from the environments that build on the base class:
- A group started for the verifier alone runs with no_network, since the
  verifier runs model output and needs no egress; startup checks the
  provider can apply it when the task may opt out.
- Each sidecar starts with its own rule (hosts_only for its egress_hosts,
  else no_network), never the main container's; tools_port names the port
  that serves the Resources Server's HTTP tools. SandboxSidecarSpec gains
  provider_options for this, as on main's OpenSandbox sidecar change.
- A server whose task and verifier both opt out neither checks nor builds
  its provider at startup.
- The task opt-out refusal says how to drop a tool transport grant.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): create the attempt sandbox's working directory before lending it

Not every provider creates the working directory it starts a sandbox with:
OpenSandbox leaves it out, so every command a borrower ran there failed.
The base class creates it from the root once the group starts, and a
failure is a retryable infrastructure failure. Also reword which verifiers
may declare verifier_executes_nothing (math-verify parses only text its
patterns limit to numbers and arithmetic).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* docs(environment): say why the attempt sandbox's working directory is created, without naming a provider

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* docs(environment): wrap the attempt sandbox start docstring

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* style(environment): wrap long docstring and message lines in the attempt sandbox code

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* feat(environment): refuse a tools sidecar on an Environment Server that does not grant its tools

A sidecar that serves the Resources Server's tools on a tools_port is
useful only to a protocol that grants those tools to the agent and brings
their state to /verify; anywhere else the verifier would grade an untouched
state. BaseEnvironmentServer.grants_tool_sidecars declares it and defaults
to False, so plan_attempt_sandbox refuses such a group at seed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* feat(environment): let the configuration alone opt the verifier out of the attempt sandbox

An opt-out is acceptable as long as it is never the default: a config that
sets sandbox_opt_out.verifier explicitly is enough. Drop the Resources
Server's verifier_executes_nothing declaration, its seed-reply field and
the seed-time refusal for a server that did not declare it. The task
opt-out is still refused for a task with tools.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* feat(environment): one sandbox opt-out switch, and the base class decides when the group starts

The opt-out is now a single explicit switch, sandbox_opt_out: true, for a
pure QA task whose verifier executes nothing: no group at all, and no
provider checked or built. It is still refused for a task with tools or
sidecars. Without it, /verify is always lent the group, and when the group
starts is derived: at seed, for the agent too, when the task has tools or
sidecars or the agent cannot run its loop without a sandbox; otherwise just
before /verify, for the verifier alone, with no_network where the provider
applies it.

The agent says whether its loop runs without a sandbox on
GET /v1/agent_sessions/capabilities (runs_loop_without_sandbox, a class
declaration that Simple Agent sets); single_agent_turn asks once per
process, only for a task without tools.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* Revert "feat(environment): one sandbox opt-out switch, and the base class decides when the group starts"

This reverts commit 2c43316246. The design keeps the two explicit opt-out
switches, sandbox_opt_out {task, verifier}, each owning its own side; the
group start is not derived from the agent, and the agent capabilities
carry no runs_loop_without_sandbox.

Signed-off-by: yaoyu-33 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(environment): drop math-verify from the verifiers that execute nothing

Math-Verify hands answer text to SymPy's evaluating parser, so its verifier
grades in the sandbox and is not an example of one that may opt out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* feat(environment): place the agent and the verifier per task instead of by an opt-out switch

There is no config switch any more: sandbox_provider and sandbox_config say
how a group starts, not whether. The agent borrows a group started at seed
when the task declares or is granted tools or sidecars, or when the agent
cannot run its loop without a sandbox, which agents now say on
GET /v1/agent_sessions/capabilities (runs_loop_without_sandbox; Simple
Agent sets it; an undeclared agent or a 404 gets the group). The verifier's
place is the Resources Server's seed declaration, verifier_mode, in
Harbor's words: none (in the Resources Server, the default), shared (the
agent's group, refused when there is none) or separate (a fresh group with
no_network, after any agent group stops). A declaration that needs a group
without a sandbox_provider is refused at seed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* docs(environment): name the placement section and its vocabulary for benchmark READMEs to link

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* feat(environment): configure where the verifier runs with a verifier block beside the task sandbox

The Environment Server's config now takes Harbor's shape: sandbox_config is the
task sandbox (the agent's group) and is optional, and a verifier block sets
mode (none, shared or separate; unset, the Resources Server's verifier_mode)
and, for separate, sandbox settings that replace sandbox_config's field by
field, with no_network unless they set a rule. A separate verifier's image is
verifier.sandbox.image, else the declared group image, else
sandbox_config.image.

The Resources Server also declares supported_verifier_modes, every mode its
/verify can run in (default: just verifier_mode), and a configured mode outside
them is refused at seed. Startup refuses verifier.sandbox without separate,
shared without a task sandbox, an incomplete verifier.sandbox without one, and
a configured separate on a provider that cannot apply its rule. Seed refuses an
agent that needs a group when there is no task sandbox.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(server_runtime): stop a separate verifier's group past a failed stop, lend DeepAgents builtin a group

- stop_attempt_sandbox stops a separate verifier's group even when the agent's group fails to stop.
  Before, a failed stop of the agent's group skipped the verifier's, which then ran until shutdown or
  its ttl_s.
- A separate verifier needs a provider that applies no_network, even when verifier.sandbox sets a
  network. Before, `network: inherit` got a separate verifier onto Enroot, which DESIGN leaves open.
- DeepAgents answers runs_loop_without_sandbox by tool profile. It inherited Simple Agent's True, so
  the builtin profile was lent no group for a task without tools and refused every seed (or started
  its own sandbox).
- single_agent_turn refuses at startup granted tools without a sandbox_config, which every seed
  would refuse.
- Tests: a separate verifier's group stops when /verify fails and when the episode is cancelled
  during /verify.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(simple_agent): stage a subclass's loop settings and carry the sandboxed loop's failures back

- The sandboxed loop was staged with exclude_unset, so a subclass's own default, such as a
  one-step agent's max_steps, fell back to SimpleAgentConfig's and the loop ran without a step
  limit. It is now staged with every set or defaulted value, without None.
- The runner collects the failures its loop observes, such as those a model server recovered
  from and forwarded with its reply, and the agent adds them to its request's failure log, as
  the in-process loop's request middleware does.
- The runner deletes its input, which holds the tool grant's and model server's cookies, once
  it has read it.
- Core tests drive Simple Agent's lent-sandbox paths (seed, refusals, install failure, activation,
  close, retire, no host fallback, subclass refusal) with a stand-in loop, so the agent's side
  counts toward core coverage without the sandbox runtime.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(server_runtime): declare a sidecar's tools_port as the port the main container may reach

With #6668 on main, OpenSandbox gives a deny-by-default main container a rule for a sidecar only on
the ports the sidecar names, so SandboxGroupSidecar.spec() now passes tools_port as the sidecar's
ports. The test provider answers sidecar_host, which SupportsSandboxSidecars now requires, and the
lent descriptor carries each sidecar's ports.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* docs(agents): say the loop that needs no sandbox only calls the model server

runs_loop_without_sandbox matters only for a task with no tools at all: any tool,
an HTTP one included, already makes the Environment Server lend the agent the
attempt's group. Say so in the flag's comment, the capabilities docstring, Simple
Agent's comment and the single_agent_turn placement tables.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* refactor(environment): keep where the verifier runs in the Resources Server's code, not in pairing config

This reverts commit c168e189c7787960c7f510d4125df5a5805a0efa, keeping the
fixes made since. The config surface of this stack does not change: a pairing
sets sandbox_provider and sandbox_config together, or neither, and has no
verifier block. Where /verify runs is the Resources Server's verifier_mode
ClassVar, sent on its seed reply; supported_verifier_modes is gone. A separate
verifier's group starts from sandbox_config with the declared image and
workdir, and always with no_network.

Kept: each group's stop is tried even when the other's fails, a sidecar's
tools_port is the port the main container may reach, DeepAgents answers
runs_loop_without_sandbox by tool profile, and the wording that a loop needing
no sandbox only calls the model server.

The verifier block itself moves to a draft PR of its own.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* docs(environment): drop the placement section from the single-agent-turn README

No benchmark README carries a placement table, so the section that asked for one, and its tables, go. The
`verifier_mode` row now says what `shared` and `separate` do itself.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* fix(agent): preserve the borrowed sandbox session contract

Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): validate attempt sandbox dependencies and relay placement

Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): enforce capability-based sandbox placement

Signed-off-by: yaoyu-33 <[email protected]>

* fix(agent): preserve IPv6 literals in sandbox model endpoints

Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): prepare the sandbox workdir before lending it

Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): honor configured sandbox placement on every attempt

Signed-off-by: yaoyu-33 <[email protected]>

* docs(environment): clarify the scope of a lent sandbox

Signed-off-by: yaoyu-33 <[email protected]>

* fix(agent): advertise Harbor model reachability and report runner timeouts

Signed-off-by: yaoyu-33 <[email protected]>

* docs(environment): explain the attempt group checkpoint policy

Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): exercise environment fixtures under enforced placement

Signed-off-by: yaoyu-33 <[email protected]>

* fix(server_runtime): send the class's verifier_mode from an overridden seed_session

A Resources Server that overrides seed_session and builds its own reply without sandbox_declaration() sent no
verifier_mode, so the Environment Server read "none" and ran a separate or shared verifier with no sandbox. The
served /seed_session route now puts the class's verifier_mode on a typed reply that sets none; a server whose class
mode is "none" serves its override unchanged.

The verifier_mode docs now say fresh first, shared last: "separate" for any verifier that executes something,
"shared" only when a check must run a command in the environment the agent configured.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>

* feat(sandbox): provision only a verifier group for checked model-only tasks

Signed-off-by: yaoyu-33 <[email protected]>

* feat(sandbox): keep agent and grader runtimes independent

Signed-off-by: yaoyu-33 <[email protected]>

* test(sandbox): cover the separate grader declaration on the wire

Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): warn on unused Simple Agent HTTP grants

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): require a reviewed harness for host execution

Signed-off-by: yaoyu-33 <[email protected]>

* fix(environment): preserve resolver imports and correct failure test pairings

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): check host tools and stop the agent before grading

Signed-off-by: yaoyu-33 <[email protected]>

* refactor(environment): separate sandbox admission from the attempt lifecycle

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): reserve preparation and preserve explicit verifier placement

Signed-off-by: yaoyu-33 <[email protected]>

* fix(sandbox): stop retrying invalid provider option types

Signed-off-by: yaoyu-33 <[email protected]>

---------

Signed-off-by: Ananth Subramaniam <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Co-authored-by: Ananth Subramaniam <[email protected]>
Co-authored-by: Claude Opus 5.5 <[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 bug Something isn't working 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.

3 participants