Skip to content

fix(checkpoint): wake sandbox command polls while a harness launch is stopped - #4553

Draft
macandro96 wants to merge 3 commits into
pthombre/partial-ckpt-sandbox-capturefrom
amahishi/opencode-resume-tool-call-lineage
Draft

macandro96 wants to merge 3 commits into
pthombre/partial-ckpt-sandbox-capturefrom
amahishi/opencode-resume-tool-call-lineage

Conversation

@macandro96

@macandro96 macandro96 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

This PR started as a set of fixes that kept OpenCode SWE rollouts recoverable at a checkpoint. It was written against the OpenCode agent before #4274 moved OpenCode onto the harness driver. It has been rebuilt onto the current stack. The parts that are not already elsewhere stay here; every other part now lives in the PR that owns that code.

What this PR adds:

  • Sandbox command polls wake while a harness launch is stopped. OpenSandbox runs a long command as a background execution and polls for its result. The poll backs off up to background_poll_interval_s, which is 30 s in the shipped config. When a checkpoint stops a harness launch, two waits can each sleep that long:

    • the poll of the launch's command, after the launch has already ended;
    • the wait for the late result of a launch that had ended just before the park request.

    Changes:

    • AsyncSandbox.checkpoint_exec_polling() opens a scope. Inside it, a provider that supports it (SupportsSandboxCheckpointPolling) wakes the pending command polls of that sandbox and caps them at operations.checkpoint_background_poll_interval_s (1 s) until the scope exits. Other providers get a no-op scope.
    • OpenSandboxProvider implements it with a wakeup event per command. Nested scopes, concurrent commands and cancellation release their waiters.
    • The harness driver's stop (nemo_gym/_checkpoint/harness.py, feat(checkpoint): harness driver for sandboxed agents that pauses them at checkpoints, with OpenCode on it #4274) runs inside the scope. Every harness stopped at a checkpoint benefits: the fallback when a pause cannot be confirmed, adapters that do not pause, and the late-result wait. A paused launch is not ending, so it does not enter the scope.
    • Signals, grace periods, command deadlines and safe-point requirements are unchanged.
  • Checkpoint resume is documented in the OpenCode README:

    • a checkpoint pauses OpenCode; OpenCode is relaunched only after a crash restore, or when a pause cannot be confirmed;
    • the relaunch re-enters the saved user message through resume_opencode.py without a new message;
    • the sandbox requirements for the helper;
    • how to run the real-runtime resume regression.
  • A failed session-database snapshot is reported in full. The error for opencode db VACUUM INTO names the destination, the return code, the error type, and the tail of stdout and stderr. A background execution returns both streams in stdout, so stderr alone often held only a status.

Where the rest of the original PR went:

Original change Now
Resume OpenCode's saved user turn without a new message (resume_opencode.py) #4274, fix(opencode_sandboxed_agent): continue a checkpointed session without adding a user turn (co-authored)
Register queued runs before they wait for a concurrency slot #4274, in the harness driver (run_harness(..., slot=))
Prepared verification (/prepare_verify, /verify_prepared); grading cleanup on failure or cancellation; cancellation no longer swallowed; one logger per grading; the prepared-verification tests #4778 (co-authored)
Keep an ended session's snapshots for retained checkpoints #4220: the snapshot index and release delete snapshots only when no kept checkpoint names them
Tool-call-ID parent and terminal resolution, and its file-ledger follow-up upstream in #4014, which is in the base
Per-snapshot timing logs dropped from this stack

Where this sits in the stack

Stack on ananthsub/partial-ckpt-fault-tests:

  1. feat(sandbox): sandbox and snapshot lifecycle for partial-rollout checkpoints #4220: sandbox checkpointer, release, snapshot index, sandbox lease
  2. feat(checkpoint): process-level evidence for resources-owned sandbox checkpoints, their release, and lease expiry #4221
  3. feat(checkpoint): ask a long-running agent harness to park when a checkpoint opens #4222
  4. feat(sandbox): sandbox owner base for resources servers, with SWE-bench on it #4576
  5. feat(checkpoint): harness driver for sandboxed agents that pauses them at checkpoints, with OpenCode on it #4274: the harness driver with pause-at-checkpoint, with OpenCode on it
  6. fix(checkpoint): leave the calls a checkpoint abandoned out of the capture ledger #4451: calls a checkpoint abandoned stay out of the capture ledger
  7. fix(checkpoint): wake sandbox command polls while a harness launch is stopped #4553 (this PR): wake sandbox command polls while a harness launch is stopped; checkpoint-resume docs
  8. feat(checkpoint): prepared verification, so a checkpoint never waits for SWE-bench grading #4778: prepared verification
  9. feat(sandbox): take a failed checkpoint snapshot again before failing the export #4779: retry a failed checkpoint snapshot

Issue

No tracking issue. Delayed detection of command exit during checkpoint preparation was found in the 32-node Nano SWE/OpenSandbox checkpointing workload.

Validation

On this head (75ed4b5e7), in the rl-gym.nightly container on Slurm:

  • Gym suites (SWE-bench, OpenCode, and the checkpoint, sandbox, OpenSandbox and token-capture unit tests), job 8087404: 2308 passed and 1 failed.
  • tests/unit_tests/test_opensandbox_checkpoint_polling.py:
    • the scope wakes a long sleep without affecting other sandboxes;
    • it wakes every command in the same sandbox;
    • a nested scope caps new command polls and restores the normal back-off;
    • a cancelled command cleans up its waiter and the scope;
    • a provider without the capability keeps its behaviour;
    • the interval must be positive.
  • tests/unit_tests/test_checkpoint_harness.py (new):
    • a stop runs inside the sandbox's polling scope;
    • a pause does not enter it.
  • Lint and DCO: ruff check and ruff format --check are clean on the changed files. Each commit is signed off by Anish Mahishi, and by Pranav Prashant Thombre for the port.

Rollout evidence

32-node GRPO run with the whole stack (job 8093570; nano-3.5 SWE policy, SWE-bench, 64 prompts × 2, 5 steps):

  • 5/5 steps, 128/128/128/127/128 valid samples (one sample masked for a logprob error), run_complete=True;
  • 18 checkpoints committed with 0 failures;
  • no errors from the polling scope.

OpenCode was paused at every checkpoint in that run, so no launch was stopped and the scope never had to engage. The unit tests above cover the stop path.

Compatibility

  • New OpenSandbox setting: operations.checkpoint_background_poll_interval_s (default 1.0), validated as positive and finite. It is a sleep cap, not a guarantee that a remote status request completes within one second.
  • No change outside a stop: normal commands keep their polling back-off.

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Oct 12, 2026

Copy link
Copy Markdown

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

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@macandro96 macandro96 changed the title Amahishi/opencode resume tool call lineage fix(checkpoint): preserve OpenCode sessions and tool-call lineage Oct 12, 2026
@pthombre
pthombre added this pull request to stack #3962 October 12, 2026 23:48
@yaoyu-33 yaoyu-33 added area:agent Agent harnesses and Responses API agent behavior bug Something isn't working complexity:high Cross-component or shared-contract change with a large review surface needs-review PR is ready for code review and waiting on a reviewer labels Oct 13, 2026
@pthombre
pthombre requested review from a team as code owners October 13, 2026 16:24
@macandro96 macandro96 changed the title fix(checkpoint): preserve OpenCode sessions and tool-call lineage fix(checkpoint): keep OpenCode SWE rollouts recoverable Oct 13, 2026
@macandro96
macandro96 marked this pull request as draft October 13, 2026 17:05
@pthombre
pthombre removed this pull request from stack #3962 October 13, 2026 21:49
@pthombre
pthombre added this pull request to stack #4578 October 13, 2026 21:53
mpatel31415 pushed a commit to mpatel31415/Gym that referenced this pull request Oct 16, 2026
… ids (NVIDIA-NeMo#4014)

## What does this PR do?

Preserve token-capture ancestry when a harness echoes a complete served
model turn but rewrites its tool arguments, as Claude Code does for Bash
commands and Edit defaults. The fallback requires matching tool IDs,
names, order and non-tool assistant content, plus the recorded request
context; inserted, missing or changed model output and ambiguous token
sequences remain unresolved.

Both local token logs and external-staging custody ledgers now retain
this complete-turn key, return `tool_call_turn` when it supplies the
parent, and reuse the parent's original staged tokens. Existing custody
rows without the new optional key remain strict-only, identical replays
remain idempotent, and checkpoint import/export preserves new keys. This
deliberately narrows NVIDIA-NeMo#3301's rejection of edited echoes to permit
argument-only rewrites while continuing to reject text, tool-name, ID
and item changes.

Terminal attribution skips token-free custody rows for the
argument-insensitive reading, rejects IDs reused in earlier transcript
turns, and treats interleaved reasoning consistently. Strict witnesses
still take precedence, conflicting witnesses fail closed, and the merge
with NVIDIA-NeMo#3973 preserves the distinction between a uniquely identified
serving and token-identical retries with different finish reasons.
Custody-only terminal attribution still relies on its existing
IDs/fingerprints; this PR does not add output items to custody records.

The file-ledger implementation in NVIDIA-NeMo#4553 should be updated to use this
complete-turn key when that branch integrates NVIDIA-NeMo#4014, rather than
reintroducing its older ID-only match. No separate issue is needed for
the defects addressed by the inline review.

## Validation

- Source-bound native Python 3.13 run: **1,425 passed**, covering
`test_tool_call_turn_fallback.py`,
`test_tool_call_turn_lineage_store.py`, `test_token_id_capture.py`,
`test_terminal_attribution.py`, `test_conversation_fingerprint.py`,
`test_external_capture_handlers.py`, `test_trajectory_builder.py`, all
`test_token_capture_*.py`, and the complete
`responses_api_models/vllm_model/tests/` suite.
- New regression controls: **9 failed before / passed after** for
interleaved reasoning and reused terminal IDs; one additional
finish-reason identity regression failed before the main-integration
fix. Tests also exercise durable-store restart/checkpoint compatibility,
strict precedence, ambiguity, identical retries, version guards, and
HTTP continuations consuming the exact original staged token prefix.
- `pre-commit run --all-files` and `git diff --check`: passed; the
private guardwords catalog was unavailable, so that hook skipped its
private-catalog scan. The formatter changed one test file; its 65 cases
passed again on final head `a791afff6f875a53908420df5198cf30a9feeab7`.

## Rollouts and compatibility

No fresh live-model rollout was run for this revision; HTTP routing,
conversion, lineage, admission and worker capture helpers are exercised
with CPU generation/staging doubles. The earlier report of several
thousand Claude Code training rollouts is historical author-provided
evidence, not validation of this revised head. Argument-only echoes may
become trainable where they previously failed attribution; this changes
sample eligibility, not verifier scores, and requires Ananth's review
and required CI before merge.

---------

Signed-off-by: Lin Jia <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Pranav Prashant Thombre <[email protected]>
pthombre added a commit that referenced this pull request Oct 21, 2026
…t adding a user turn

A relaunch after a checkpoint ran `opencode run --continue -- "Your previous session was interrupted. Continue
working on the task from where you left off."`. Every checkpoint stops OpenCode, so every rollout running through
a checkpoint got that message in its trajectory: in a 32-node SWE-bench run, all 641 calls that spanned a
checkpoint grew the conversation by one extra message, in 56% of rollouts. The policy is then trained on turns
conditioned on a message the task never had, only because the run was checkpointed.

The relaunch now runs resume_opencode.py in the sandbox (from #4553's d431b1fb): it starts an authenticated
loopback `opencode serve`, posts the session's last user message back with empty parts, which OpenCode 1.17.11
upserts and continues without a new message, checks the saved user turns are unchanged, and stops the server.
resume_decision still decides whether there is a session to continue; the launch tag that the stop signals is
inherited by the helper and its server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-authored-by: Anish Mahishi <[email protected]>
Signed-off-by: Pranav Prashant Thombre <[email protected]>
pthombre added a commit that referenced this pull request Oct 21, 2026
… stopped

OpenSandbox runs a long command as a background execution and polls for its result with a back-off that grows
to background_poll_interval_s (30 s in the shipped config). When a checkpoint stops a harness launch, the poll
of that launch's command can sleep for up to 30 s after the launch has ended, and so can the wait for the late
result of a launch that had ended just before the park request.

AsyncSandbox.checkpoint_exec_polling() opens a scope in which a provider that supports it
(SupportsSandboxCheckpointPolling) wakes the pending command polls of that sandbox and caps them at
operations.checkpoint_background_poll_interval_s (1 s) until the scope exits; other providers get a no-op scope.
OpenSandboxProvider implements it with a per-command wakeup event.

The harness driver's stop (nemo_gym/_checkpoint/harness.py) runs inside the scope, so every harness that is
stopped at a checkpoint benefits: the fallback when a pause cannot be confirmed, adapters that do not pause,
and the late-result wait. A paused launch is not ending and does not enter the scope.

Ported from #4553 (written against the OpenCode agent before the harness driver): the provider change is
Anish's as written; the scope now wraps the driver's stop instead of OpenCode's former interrupt.

Signed-off-by: Anish Mahishi <[email protected]>
Co-authored-by: Pranav Prashant Thombre <[email protected]>
Signed-off-by: Pranav Prashant Thombre <[email protected]>
@pthombre
pthombre force-pushed the amahishi/opencode-resume-tool-call-lineage branch from 819322d to dc38adf Compare October 21, 2026 03:05
pthombre added a commit that referenced this pull request Oct 21, 2026
…t a failed session database snapshot in full

- README: a "Checkpoint resume" section. A checkpoint pauses OpenCode, and OpenCode is relaunched on its saved
  session only after a crash restore or when a pause cannot be confirmed. The relaunch re-enters the saved user
  message through resume_opencode.py without a new message. The section also gives the sandbox requirements and
  how to run the real-runtime resume regression.
- The error for a failed `opencode db VACUUM INTO` names the destination, return code, error type and the tail
  of stdout and stderr. A background execution returns both streams in stdout, so stderr alone often held only
  a status.

From #4553 (b53e39f, 4d077ea), whose resume helper and the rest of whose changes are now in #4274 and #4778.

Signed-off-by: Anish Mahishi <[email protected]>
Co-authored-by: Pranav Prashant Thombre <[email protected]>
Signed-off-by: Pranav Prashant Thombre <[email protected]>
pthombre added a commit that referenced this pull request Oct 21, 2026
…for SWE-bench grading

SWE-bench's /verify is a wait step: a checkpoint's prepare waits for every in-flight grading, which can take up
to evaluation_timeout (1800 s, longer than a controller's prepare deadline). In a 32-node SWE-bench run two
prepares took 833 s and 1126 s, idling every node.

Verification can now take two steps:

- /prepare_verify (a wait step for the caller): capture the patch, end the session and stop the agent's
  sandbox. A retry of a lost reply gets the same patch.
- /verify_prepared: grade the captured patch in a fresh sandbox. It touches no session state, so the server
  declares it in the new checkpoint_replayable_paths: a checkpoint neither waits for it nor refuses it.

SandboxedHarnessAgent runs an adapter's optional PreparedVerification: the capture is recorded in the verify
bookmark, grading is a replay step, and a restore grades the saved capture again. OpenCode opts in with
prepare_verification: true. verify_agent_response takes the route and extra body fields.

From #4553 (4d077ea), which designed the same routes for the OpenCode agent before the harness driver:

- A grading that fails or is cancelled before run_instance's own cleanup still stops its sandbox, and the
  container stop is shielded from cancellation.
- run_instance gives each grading its own logger and no longer returns from its finally, which swallowed the
  cancellation of an interrupted grading.
- The capture is a helper that leaves the sandbox running when it fails.
- test_prepared_verification.py: retries return the captured patch after the sandbox stopped; a failed capture
  keeps the sandbox; one-step /verify still holds up prepare; a slow prepared grading does not, and replays
  in a restarted server without the original sandbox; /verify_prepared requires a patch but accepts an empty
  diff; and run_instance propagates cancellation after cleanup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-authored-by: Anish Mahishi <[email protected]>
Signed-off-by: Pranav Prashant Thombre <[email protected]>
@pthombre
pthombre force-pushed the amahishi/opencode-resume-tool-call-lineage branch from dc38adf to 7144bb3 Compare October 25, 2026 02:47
macandro96 and others added 3 commits October 25, 2026 09:28
… stopped

OpenSandbox runs a long command as a background execution and polls for its result with a back-off that grows
to background_poll_interval_s (30 s in the shipped config). When a checkpoint stops a harness launch, the poll
of that launch's command can sleep for up to 30 s after the launch has ended, and so can the wait for the late
result of a launch that had ended just before the park request.

AsyncSandbox.checkpoint_exec_polling() opens a scope in which a provider that supports it
(SupportsSandboxCheckpointPolling) wakes the pending command polls of that sandbox and caps them at
operations.checkpoint_background_poll_interval_s (1 s) until the scope exits; other providers get a no-op scope.
OpenSandboxProvider implements it with a per-command wakeup event.

The harness driver's stop (nemo_gym/_checkpoint/harness.py) runs inside the scope, so every harness that is
stopped at a checkpoint benefits: the fallback when a pause cannot be confirmed, adapters that do not pause,
and the late-result wait. A paused launch is not ending and does not enter the scope.

Ported from #4553 (written against the OpenCode agent before the harness driver): the provider change is
Anish's as written; the scope now wraps the driver's stop instead of OpenCode's former interrupt.

Signed-off-by: Anish Mahishi <[email protected]>
Co-authored-by: Pranav Prashant Thombre <[email protected]>
Signed-off-by: Pranav Prashant Thombre <[email protected]>
…t a failed session database snapshot in full

- README: a "Checkpoint resume" section. A checkpoint pauses OpenCode, and OpenCode is relaunched on its saved
  session only after a crash restore or when a pause cannot be confirmed. The relaunch re-enters the saved user
  message through resume_opencode.py without a new message. The section also gives the sandbox requirements and
  how to run the real-runtime resume regression.
- The error for a failed `opencode db VACUUM INTO` names the destination, return code, error type and the tail
  of stdout and stderr. A background execution returns both streams in stdout, so stderr alone often held only
  a status.

From #4553 (b53e39f, 4d077ea), whose resume helper and the rest of whose changes are now in #4274 and #4778.

Signed-off-by: Anish Mahishi <[email protected]>
Co-authored-by: Pranav Prashant Thombre <[email protected]>
Signed-off-by: Pranav Prashant Thombre <[email protected]>
…kpoint ends

While a checkpoint pauses a harness launch, the launch's long command is still polled for its status. The
sandbox is being snapshotted then and often does not answer: each status request times out after
status_poll_timeout_s, and once operations.retries are spent the command fails, although the launch is only
paused. Checkpoints in a 16-node full-SWE run (job 8143368) lasted 1-4.5 minutes; 359 status timeouts across
130 sandboxes, all during checkpoints, lost 4 OpenCode runs.

AsyncSandbox.parked_exec_polling() opens a scope in which a provider that supports it
(SupportsSandboxParkedPolling) holds the command polls of that sandbox without asking it, and asks at once when
the scope exits; other providers get a no-op scope. OpenSandboxProvider marks each pending poll when a scope
opens: a status request that fails after that, because it overlapped the park, is logged as forgiven (warning) and
asked again once the park ends, with a fresh retry allowance. A request that fails with no park overlapping it
fails the command as before, so a sandbox still lost after the park is not retried indefinitely.

The harness driver awaits park() inside the scope. The pause, continue, and kill commands run outside it, since
their own polls would be held too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
@pthombre
pthombre force-pushed the amahishi/opencode-resume-tool-call-lineage branch from 7144bb3 to b8ed803 Compare October 25, 2026 16:57
pthombre added a commit that referenced this pull request Nov 7, 2026
…a renewable lease

Adds the optional provider capabilities partial-rollout checkpoints need on the
sandbox side, and implements them for OpenSandbox:

- SupportsSandboxSnapshot: snapshot(handle, name) starts a snapshot and returns
  its id at once; wait_snapshot_ready, delete_snapshot (404 is gone) and
  list_snapshots(prefix) go over the management API through Gym's shared
  aiohttp client. 429, 5xx and connection errors are retried; a 404 for a
  snapshot the API has only just created is waited out for
  snapshot_lookup_grace_s. The API's name filter matches whole names, so a
  prefix listing reads every page and filters client-side. A fork stays
  create(provider_options.snapshot_id), as on main.
- A renewable lease (create.renew_ttl_s): each sandbox is created with the
  lease, capped by the spec's ttl_s, and renewed every renew_interval_s
  (jittered) with renew_timeout_s per call, never past the spec's lifetime. A
  failed lease renewal is logged and retried; a renewal that finds the sandbox
  gone ends the loop quietly in both modes. Off by default: shipping it would
  break configs that set a longer renew_interval_s (swe_together, TB4).
- SupportsSandboxCheckpointPolling / SupportsSandboxParkedPolling and the
  AsyncSandbox.checkpoint_exec_polling() / parked_exec_polling() scopes: a
  harness stopped for a checkpoint is seen to end within
  checkpoint_background_poll_interval_s, and a sandbox paused for a snapshot is
  not polled until the park ends, forgiving one status request that failed
  meanwhile.
- AsyncSandbox.provider, owns_provider and handle properties.

Provenance: the provider half of #4220, #4553 and #4779 (legacy stack), rebuilt
on main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
@cmunley1

Copy link
Copy Markdown
Contributor

/ok to test b8ed803

pthombre added a commit that referenced this pull request Nov 13, 2026
…a renewable lease

Adds the optional provider capabilities partial-rollout checkpoints need on the
sandbox side, and implements them for OpenSandbox:

- SupportsSandboxSnapshot: snapshot(handle, name) starts a snapshot and returns
  its id at once; wait_snapshot_ready, delete_snapshot (404 is gone) and
  list_snapshots(prefix) go over the management API through Gym's shared
  aiohttp client. 429, 5xx and connection errors are retried; a 404 for a
  snapshot the API has only just created is waited out for
  snapshot_lookup_grace_s. The API's name filter matches whole names, so a
  prefix listing reads every page and filters client-side. A fork stays
  create(provider_options.snapshot_id), as on main.
- A renewable lease (create.renew_ttl_s): each sandbox is created with the
  lease, capped by the spec's ttl_s, and renewed every renew_interval_s
  (jittered) with renew_timeout_s per call, never past the spec's lifetime. A
  failed lease renewal is logged and retried; a renewal that finds the sandbox
  gone ends the loop quietly in both modes. Off by default: shipping it would
  break configs that set a longer renew_interval_s (swe_together, TB4).
- SupportsSandboxCheckpointPolling / SupportsSandboxParkedPolling and the
  AsyncSandbox.checkpoint_exec_polling() / parked_exec_polling() scopes: a
  harness stopped for a checkpoint is seen to end within
  checkpoint_background_poll_interval_s, and a sandbox paused for a snapshot is
  not polled until the park ends, forgiving one status request that failed
  meanwhile.
- AsyncSandbox.provider, owns_provider and handle properties.

Provenance: the provider half of #4220, #4553 and #4779 (legacy stack), rebuilt
on main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
pthombre added a commit that referenced this pull request Nov 14, 2026
…a renewable lease

Adds the optional provider capabilities partial-rollout checkpoints need on the
sandbox side, and implements them for OpenSandbox:

- SupportsSandboxSnapshot: snapshot(handle, name) starts a snapshot and returns
  its id at once; wait_snapshot_ready, delete_snapshot (404 is gone) and
  list_snapshots(prefix) go over the management API through Gym's shared
  aiohttp client. 429, 5xx and connection errors are retried; a 404 for a
  snapshot the API has only just created is waited out for
  snapshot_lookup_grace_s. The API's name filter matches whole names, so a
  prefix listing reads every page and filters client-side. A fork stays
  create(provider_options.snapshot_id), as on main.
- A renewable lease (create.renew_ttl_s): each sandbox is created with the
  lease, capped by the spec's ttl_s, and renewed every renew_interval_s
  (jittered) with renew_timeout_s per call, never past the spec's lifetime. A
  failed lease renewal is logged and retried; a renewal that finds the sandbox
  gone ends the loop quietly in both modes. Off by default: shipping it would
  break configs that set a longer renew_interval_s (swe_together, TB4).
- SupportsSandboxCheckpointPolling / SupportsSandboxParkedPolling and the
  AsyncSandbox.checkpoint_exec_polling() / parked_exec_polling() scopes: a
  harness stopped for a checkpoint is seen to end within
  checkpoint_background_poll_interval_s, and a sandbox paused for a snapshot is
  not polled until the park ends, forgiving one status request that failed
  meanwhile.
- AsyncSandbox.provider, owns_provider and handle properties.

Provenance: the provider half of #4220, #4553 and #4779 (legacy stack), rebuilt
on main.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
gwarmstrong pushed a commit to gwarmstrong/Gym that referenced this pull request Nov 16, 2026
…kpointer (NVIDIA-NeMo#5265)

* feat(sandbox): snapshot, list and delete OpenSandbox snapshots, with a renewable lease

Adds the optional provider capabilities partial-rollout checkpoints need on the
sandbox side, and implements them for OpenSandbox:

- SupportsSandboxSnapshot: snapshot(handle, name) starts a snapshot and returns
  its id at once; wait_snapshot_ready, delete_snapshot (404 is gone) and
  list_snapshots(prefix) go over the management API through Gym's shared
  aiohttp client. 429, 5xx and connection errors are retried; a 404 for a
  snapshot the API has only just created is waited out for
  snapshot_lookup_grace_s. The API's name filter matches whole names, so a
  prefix listing reads every page and filters client-side. A fork stays
  create(provider_options.snapshot_id), as on main.
- A renewable lease (create.renew_ttl_s): each sandbox is created with the
  lease, capped by the spec's ttl_s, and renewed every renew_interval_s
  (jittered) with renew_timeout_s per call, never past the spec's lifetime. A
  failed lease renewal is logged and retried; a renewal that finds the sandbox
  gone ends the loop quietly in both modes. Off by default: shipping it would
  break configs that set a longer renew_interval_s (swe_together, TB4).
- SupportsSandboxCheckpointPolling / SupportsSandboxParkedPolling and the
  AsyncSandbox.checkpoint_exec_polling() / parked_exec_polling() scopes: a
  harness stopped for a checkpoint is seen to end within
  checkpoint_background_poll_interval_s, and a sandbox paused for a snapshot is
  not polled until the park ends, forgiving one status request that failed
  meanwhile.
- AsyncSandbox.provider, owns_provider and handle properties.

Provenance: the provider half of NVIDIA-NeMo#4220, NVIDIA-NeMo#4553 and NVIDIA-NeMo#4779 (legacy stack), rebuilt
on main.

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

* feat(checkpoint): sandbox checkpointer with a snapshot index and release

SandboxSessionCheckpointer (nemo_gym/_checkpoint/sandbox.py) checkpoints the
sandboxes a server owns, by an opaque key, for any owner: a resources server,
an agent or an environment server.

- export(keys, checkpoint_id) snapshots each live sandbox; a key without one
  exports None. Every snapshot is indexed under
  <state_dir>/<server>/snapshots/<checkpoint>/<snapshot> as soon as its id
  returns, before the readiness wait. A failed snapshot is taken again up to
  snapshot_attempts times; the backend semaphore covers the submit only, not
  the readiness wait.
- Snapshot names are ng-<run>-<server>-<checkpoint>-<key>-<attempt>, with
  short hashes and a run id written once into state_dir.
- restore(states) validates everything, forks all or nothing (rolling back
  its own forks), retries a fork the store cannot find yet, and stops the
  superseded sandboxes in the background.
- release(kept) deletes, under a file lock shared by every process of the
  server, the indexed snapshots of every checkpoint not kept, including a
  crashed process's and a failed commit's, then sweeps snapshots of dropped
  checkpoints the index never recorded by name. A failed delete keeps its
  marker for the next release.
- checkpoint_state_dir() requires checkpoint.state_dir (added to
  CheckpointSettings) once checkpointing is on.
- OpenSandbox's snapshots.py cleanup tool gains --name-prefix, so an operator deletes the
  snapshots a job left when it ended for good: --name-prefix ng-<run_id>- --reap.

Provenance: nemo_gym/sandbox/checkpoint.py of NVIDIA-NeMo#4220 and NVIDIA-NeMo#4779 (legacy stack),
moved out of nemo_gym.sandbox, without park/on_stop (stop-commit is deferred).

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

* fix(sandbox): let each provider create a sandbox from its snapshots, with a typed not-found error

The snapshot protocol made `create` with `provider_options["snapshot_id"]` and no image the way to fork a
snapshot, which is OpenSandbox's API: a provider whose snapshots are created another way (an E2B template id, for
one) could not implement it. `SupportsSandboxSnapshot.create_from_snapshot` now owns that step;
`AsyncSandbox.start(snapshot_id=...)` calls it, and OpenSandbox implements it as the option it already took.

The checkpointer's fork retried on `"NOT_FOUND" in repr(error)`. Providers now raise
`SandboxSnapshotNotFoundError` for a snapshot they do not have, and the fork retries on that type only.

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

* fix(sandbox): await snapshot release, type the snapshot contract, and bound its requests

Addresses the review of the sandbox snapshot provider and checkpointer.

Checkpointer:
- release() deletes before it returns and takes the index lock without
  blocking, so the participant that awaits it admits no commit meanwhile
  and a cancelled wait cannot end up holding the lock. It raises
  SnapshotReleaseError when a delete failed, and says why when the index
  cannot be locked.
- restore() stops its completed forks when it is cancelled, logs a fork
  whose rollback stop failed and stops it again on the next restore, and
  refuses a state of a format version it does not know.
- A key is taken while its sandbox is created or restored, so two
  creates for one key start one sandbox.
- The sweep deletes only names the checkpointer gives; the index listing
  skips a folder that vanished; a spec that is not JSON fails the export
  before any snapshot; settle() only waits.
- The saved state carries a version and snapshot_ready_ts.

Provider contract and OpenSandbox:
- list_snapshots returns SandboxSnapshotInfo; failed, in-use and missing
  snapshots raise typed errors that carry the server's reason.
- create_from_snapshot recognizes SNAPSHOT::NOT_FOUND under the create
  wrapper, so the checkpointer's fork retry runs.
- Management requests are sent once within a short timeout and retried by
  their callers, connection errors and cut-off replies included; a 404 to
  a delete is confirmed with a lookup.
- Renewal jitter never exceeds the interval, the first renewal counts the
  time the create spent, and a vanished sandbox fails a sandbox without a
  lease as before.
- The final log read of a finished command waits out a park.

The lease stays off in the shipped config, with the reason in a comment.

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

* fix(sandbox): start the lease at the create request, track unstopped forks, and bound snapshot cleanup

Addresses the second review round of the sandbox snapshot provider and
checkpointer.

Checkpointer:
- release() is now delete_snapshots(kept) and SnapshotReleaseError is
  SnapshotDeleteIncompleteError: the lending code already uses "release"
  for stopping a session's sandbox.
- The state directory's ID is read from <state_dir>/state_dir_id, not
  run_id, which names a collection run elsewhere in Gym.
- A fork a restore will not install is tracked from before its stop
  until the stop succeeds, so a failed or cancelled stop cannot lose it.
  settle() stops such forks again, and the new aclose() stops every
  tracked sandbox and fork at shutdown.
- access() serializes with scope="operate": a borrower may run commands
  in the sandbox but not destroy it.
- export() warns once the index holds more than five checkpoints, and
  again when that doubles: nothing but a release deletes a snapshot.
- It snapshots through AsyncSandbox.snapshot() instead of the provider
  handle.

Sandbox API and provider contract:
- AsyncSandbox gains snapshot(name=...) and a started flag; the public
  handle accessor is removed.
- SandboxSnapshotNotFoundError derives from SandboxSnapshotError (and
  LookupError) and carries snapshot_id.
- SupportsSandboxSnapshot states that a provider must keep a snapshot's
  name and return it from list_snapshots.

OpenSandbox:
- The lease clock starts when the create request is sent, which is when
  the server starts the TTL, so the first renewal accounts for placement
  and the image pull as well as the setup.
- A parked command's poll is held only until the command's client wait
  runs out, not until the park ends.
- Management requests take the server and key from the SDK's connection
  config, so OPEN_SANDBOX_DOMAIN and OPEN_SANDBOX_API_KEY apply to them
  as they do to the SDK's own requests.
- One listing and one delete each have an overall budget
  (operations.snapshot_list_timeout_s, snapshot_delete_timeout_s); the
  listing asks for the server's largest page (200) and ends on an empty
  page.

Docs: a state_dir belongs to one job and its restarts; snapshots are
deleted only by a release and the service does not expire them; the
lease runs from the create request; the module docstring states the
provider-neutral contract and the OpenSandbox and Lustre specifics move
to the OpenSandbox page and the state_dir setting.

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

* fix(sandbox): treat a bare 404 on a create from a snapshot as snapshot not found

A live OpenSandbox service answers a create from a snapshot it has
deleted with HTTP 404 and no error code in the body, so the SDK's error
carried no SNAPSHOT::NOT_FOUND and create_from_snapshot raised a generic
create failure. The checkpointer's retry of a fork whose snapshot is not
found, and a caller that handles SandboxSnapshotNotFoundError, never saw
the typed error.

create_from_snapshot now raises SandboxSnapshotNotFoundError for that
404 as well. The create names nothing else that could be missing: the
snapshot stands in for the image.

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

* fix(sandbox): keep changed exec defaults across a restore and retry a failed lease renewal in time

- A checkpoint records the sandbox's current default user and working directory, so a fork runs commands as
  setup left them rather than as the sandbox was created.
- The spec's lifetime is counted from the create request, so renewals cannot extend a sandbox past its ttl_s
  by the time its startup took.
- A failed lease renewal is tried again within what is left of the lease, sooner as the expiry nears, instead
  of a full interval later.
- A snapshot listing page that has items must say whether another page follows; a missing or mistyped flag
  raises instead of returning a partial listing.
- A command poll waits for its wakeup under a timeout instead of racing two helper tasks.
- A release does not read the index folders of the checkpoints it keeps.

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

* fix(sandbox): close the checkpointer before a shutdown stops its sandboxes and jitter lease renewal retries

- aclose closes the checkpointer, so create, add and restore are refused, waits for the ones already
  running, and then stops the sandboxes; a restore that installs its forks during a shutdown has them stopped.
- Every sandbox stop has a time limit, so one that hangs does not hold up a shutdown.
- A create from a snapshot counts an HTTP 404 as a missing snapshot only when the SDK parsed no error code;
  a 404 with a code about the sandbox keeps its own type.
- A failed lease renewal's retry wait is jittered, so sandboxes created together do not retry in step.
- add's docstring says the default user and working directory of a fork come from the sandbox at export.
- Tests: a cancelled restore whose fork's stop fails keeps the fork tracked; the lookup-grace test no longer
  depends on an earlier test importing the SDK.

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

---------

Signed-off-by: Pranav Thombre <[email protected]>
Signed-off-by: Pranav Prashant Thombre <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
pthombre added a commit that referenced this pull request Nov 21, 2026
OpenCode episodes were restarted from scratch by every checkpoint restore, and a checkpoint had to wait for the
harness. The agent now exports its sessions and uses the shared pause mechanism.

- checkpoint_mode = "exported" and rebinds_tool_accesses = True. A session whose sandbox the agent owns (no
  sandbox_access) or a continuation session restarts instead.
- A checkpointed session keeps OpenCode's conversation under the sandbox's session root, on the snapshotted disk,
  and the activation runs inside participant.activation(), so close and retire cancel the launch.
- The launch loop runs run_until_parked: a confirmed pause parks the activation and continues the harness in
  place; a stopped harness is relaunched with the unspent budget (time paused does not count). A relaunch, or the
  first launch after a restore, resumes the saved conversation when it starts with the task and has a completed
  assistant message: resume_opencode.sh starts `opencode serve` in the sandbox and re-posts the last user message
  with empty parts, so no user turn is added. Otherwise the original prompt runs fresh, with the reason logged.
- A re-sent activation index is answered from the saved reply; the reply metadata reports harness_launches.
- Hooks: export_agent_sessions, restore_agent_sessions (unconnected), and _rebind_restored_agent_session_state,
  which connects to the forked sandbox, reattaches the SandboxSession and reinstalls missing files. A restored
  session that was never re-bound answers 409.
- nemo_gym/testing/checkpoint_conformance.py: check_harness_adapter(), run here against OpenCode with a fake
  `opencode` that implements both `run` and `serve`.

Provenance: #4274's pause idea, resume decision and resume helper, and #4553's agent half (legacy stack),
rebuilt on main's SandboxSession and bash supervisor.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
pthombre added a commit that referenced this pull request Nov 21, 2026
OpenCode episodes were restarted from scratch by every checkpoint restore, and a checkpoint had to wait for the
harness. The agent now exports its sessions and uses the shared pause mechanism.

- checkpoint_mode = "exported" and rebinds_tool_accesses = True. A session whose sandbox the agent owns (no
  sandbox_access) or a continuation session restarts instead.
- A checkpointed session keeps OpenCode's conversation under the sandbox's session root, on the snapshotted disk,
  and the activation runs inside participant.activation(), so close and retire cancel the launch.
- The launch loop runs run_until_parked: a confirmed pause parks the activation and continues the harness in
  place; a stopped harness is relaunched with the unspent budget (time paused does not count). A relaunch, or the
  first launch after a restore, resumes the saved conversation when it starts with the task and has a completed
  assistant message: resume_opencode.sh starts `opencode serve` in the sandbox and re-posts the last user message
  with empty parts, so no user turn is added. Otherwise the original prompt runs fresh, with the reason logged.
- A re-sent activation index is answered from the saved reply; the reply metadata reports harness_launches.
- Hooks: export_agent_sessions, restore_agent_sessions (unconnected), and _rebind_restored_agent_session_state,
  which connects to the forked sandbox, reattaches the SandboxSession and reinstalls missing files. A restored
  session that was never re-bound answers 409.
- nemo_gym/testing/checkpoint_conformance.py: check_harness_adapter(), run here against OpenCode with a fake
  `opencode` that implements both `run` and `serve`.

Provenance: #4274's pause idea, resume decision and resume helper, and #4553's agent half (legacy stack),
rebuilt on main's SandboxSession and bash supervisor.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
pthombre added a commit that referenced this pull request Nov 21, 2026
OpenCode episodes were restarted from scratch by every checkpoint restore, and a checkpoint had to wait for the
harness. The agent now exports its sessions and uses the shared pause mechanism.

- checkpoint_mode = "exported" and rebinds_tool_accesses = True. A session whose sandbox the agent owns (no
  sandbox_access) or a continuation session restarts instead.
- A checkpointed session keeps OpenCode's conversation under the sandbox's session root, on the snapshotted disk,
  and the activation runs inside participant.activation(), so close and retire cancel the launch.
- The launch loop runs run_until_parked: a confirmed pause parks the activation and continues the harness in
  place; a stopped harness is relaunched with the unspent budget (time paused does not count). A relaunch, or the
  first launch after a restore, resumes the saved conversation when it starts with the task and has a completed
  assistant message: resume_opencode.sh starts `opencode serve` in the sandbox and re-posts the last user message
  with empty parts, so no user turn is added. Otherwise the original prompt runs fresh, with the reason logged.
- A re-sent activation index is answered from the saved reply; the reply metadata reports harness_launches.
- Hooks: export_agent_sessions, restore_agent_sessions (unconnected), and _rebind_restored_agent_session_state,
  which connects to the forked sandbox, reattaches the SandboxSession and reinstalls missing files. A restored
  session that was never re-bound answers 409.
- nemo_gym/testing/checkpoint_conformance.py: check_harness_adapter(), run here against OpenCode with a fake
  `opencode` that implements both `run` and `serve`.

Provenance: #4274's pause idea, resume decision and resume helper, and #4553's agent half (legacy stack),
rebuilt on main's SandboxSession and bash supervisor.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
ehosseiniasl pushed a commit to ehosseiniasl/Gym that referenced this pull request Nov 21, 2026
…-NeMo#5268)

* fix(checkpoint): leave the calls a checkpoint abandoned out of the capture ledger

A harness interrupted at a checkpoint (OpenCode killed while its model call is held) gives up on the call. The
ledger had recorded it, often as a failure row for a request that ended without staging coordinates, and the
gate no longer counted it as undelivered once the request had finished, so the row went into the commit and
the restored attempt's manifest reported a failure for a call no trajectory contains, which masks the sample.

The policy gate now remembers calls whose client left while admission was closed (`GateSnapshot.abandoned`);
the commit leaves their rows out like an undelivered call's, and the resume drops them from the live ledger
(`FileLineageStore.discard_calls`), in the single-process and the multi-worker policy server alike.

(cherry picked from commit 912ce78)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
(cherry picked from commit 7619754df96d015eb6bb98ec956aa5feb1c2c078)

* feat(agent-utils): pause a supervised harness in place at a checkpoint and park its activation

A checkpoint of an agent whose harness runs in a task sandbox had two choices: wait for the harness, which can
take an hour, or stop it and relaunch after the commit. This adds a third, which is now the first choice.

The bash supervisor pauses and continues the harness on request. Writing sequence number N to `pause.request`
sends SIGSTOP to every process a stop would reach and to every process carrying the supervisor's environment
marker, including services that left the harness, waits until each is stopped (longer while some are in
uninterruptible sleep), and acknowledges in `paused.json`; `continue.request` with N sends SIGCONT and
acknowledges in `continued.json`. Numbers only grow, so every checkpoint re-arms the protocol without removing
files. Time spent paused does not count against the harness deadline, a pause requested before the launch holds
the launch, and a stop while paused continues the processes first so the harness still sees TERM and can save its
state. The cleanup receipt gains `stopped`: the stop file, not the harness's own exit or the deadline, ended the
harness or fenced its launch. Receipts without it still parse.

`SandboxSession` opts in with `pausable=True` and gains `pause_harness()` / `continue_harness()`, which read an
existing receipt first, `execute(pause_allowance_s=...)` for the provider deadline, `session_root`, and
`checkpoint_state()` / `reattach()` to rebind a session to the sandbox a restore forks from a snapshot.

`run_until_parked()` races a launch against the activation's park request: it pauses the harness, parks the
activation at the adapter's boundary, continues the harness after the resume, and keeps racing for the next
checkpoint. A pause that is not confirmed, or a continue that fails three times, falls back to the stop the
supervisor already had; the adapter then relaunches. A cancelled activation still stops its harness, shielded and
bounded.

Where the provider has them, a confirmed pause holds the launch's command polls in the sandbox's
parked_exec_polling() scope until the continue, so a sandbox being snapshotted is not polled, and a stop for a
checkpoint runs in checkpoint_exec_polling() so the provider notices the launch's end promptly.

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

* feat(opencode): pause at checkpoints and resume after a crash

OpenCode episodes were restarted from scratch by every checkpoint restore, and a checkpoint had to wait for the
harness. The agent now exports its sessions and uses the shared pause mechanism.

- checkpoint_mode = "exported" and rebinds_tool_accesses = True. A session whose sandbox the agent owns (no
  sandbox_access) or a continuation session restarts instead.
- A checkpointed session keeps OpenCode's conversation under the sandbox's session root, on the snapshotted disk,
  and the activation runs inside participant.activation(), so close and retire cancel the launch.
- The launch loop runs run_until_parked: a confirmed pause parks the activation and continues the harness in
  place; a stopped harness is relaunched with the unspent budget (time paused does not count). A relaunch, or the
  first launch after a restore, resumes the saved conversation when it starts with the task and has a completed
  assistant message: resume_opencode.sh starts `opencode serve` in the sandbox and re-posts the last user message
  with empty parts, so no user turn is added. Otherwise the original prompt runs fresh, with the reason logged.
- A re-sent activation index is answered from the saved reply; the reply metadata reports harness_launches.
- Hooks: export_agent_sessions, restore_agent_sessions (unconnected), and _rebind_restored_agent_session_state,
  which connects to the forked sandbox, reattaches the SandboxSession and reinstalls missing files. A restored
  session that was never re-bound answers 409.
- nemo_gym/testing/checkpoint_conformance.py: check_harness_adapter(), run here against OpenCode with a fake
  `opencode` that implements both `run` and `serve`.

Provenance: NVIDIA-NeMo#4274's pause idea, resume decision and resume helper, and NVIDIA-NeMo#4553's agent half (legacy stack),
rebuilt on main's SandboxSession and bash supervisor.

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

* fix(opencode): resume a saved conversation exported from OpenCode's database

snapshot.py keeps each message's id beside its info, because OpenCode stores the id on the message row and not
in its data; resume_payload read it from info and failed with KeyError 'id' on every real export, so every
relaunch and restore started the task afresh (16-node job 8459954: 2 of 2 relaunches).

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

* fix(opencode): retry a new sandbox's setup commands, and report a launch that saved nothing in one line

A sandbox that was just created or restored can refuse a connection for a few seconds after it first answered (a
gateway 502). OpenCode's seed failed on its first commands then, and the rollout started over (job 8539361: the
workdir, preparation and runtime install failed for 3+ sandboxes each).

- `exec_idempotent` (agent utilities) runs a command and retries it, twice, when the provider raises; a returned
  result, any exit code, is final. Only for commands that are safe to run twice.
- OpenCode runs its workdir creation, sandbox preparation (it checks before it installs), runtime install (the
  installer serializes and skips a runtime in place) and the "set the conversation aside" move through it.
- A restore that finds OpenCode had written no conversation yet (no root session) logs one INFO line and starts
  afresh, as before, instead of a WARNING with a traceback (`NoRootSessionError`).
- A launch that ended without finishing and left no session database or no root session raises
  `NothingCapturedError`, which the session logs as one WARNING line with the runner's log, instead of a chained
  capture traceback on top of the launch's own error.

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

* fix(opencode): take the concurrency slot with Activation.slot, so a parked session's slot always comes back

The slot was taken inside Activation.queued() but given back by a try/finally that began only after it. A retire or
close of a session parked on the way out of queued(), after taking a slot while a checkpoint was open, raised before
that finally, and the agent server ran with one slot fewer for good. Activation.slot() takes and releases the slot in
one scope; without checkpointing, the same holds through a local helper.

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

* fix(opencode): relaunch, re-bind and stop paths found in a review of the checkpoint pause

Found in a review of the harness pause and of OpenCode's relaunch.

Relaunch and re-bind (OpenCode):
- A relaunch that starts the task afresh no longer names the conversation it set aside. The launch command was
  built before the decision, so it kept `--session <id>` of the discarded conversation; it is now built after it,
  and the fresh start also drops the observations and trajectory of the discarded launch.
- A saved conversation that cannot be read is no longer taken for a missing one. The relaunch reads the database
  itself, three times, and raises if it still cannot, instead of setting a resumable conversation aside after one
  failed download on a sandbox a restore just forked.
- A restored session gets back what its seed had set and a checkpoint does not carry: `export_dir` and the
  environment of OpenCode's import and export. Without them a restored episode wrote no exports.
- The re-bind's first command on the forked sandbox goes through `exec_idempotent`, and a re-bind that fails
  releases its sandbox connection instead of leaving one behind per retried seed.
- A resumed launch that ends in a reported model error (API error, context overflow) is recognised:
  `resume_opencode.sh` exits 0 once the server answered, where `opencode run` exits 1.
- A session that continues an imported conversation (`session_import_path`) restarts after a crash: a relaunch
  compared the imported conversation's first prompt with the task's and discarded it.
- A reply given again from a saved one forwards its verification failure report, as the first reply does.
- Text parts OpenCode marks synthetic are not part of the prompt a saved conversation is matched against.

`resume_opencode.sh`:
- The prompt request runs in the background and is waited for. Bash runs a trap only between foreground
  commands, so the supervisor's TERM was held until the turn ended: every stop of a resumed launch took the full
  grace period and the server was killed.
- The server is ended with TERM: bash starts a background command with INT ignored.
- The loopback request ignores proxy variables, and a path outside ASCII is encoded as its UTF-8 bytes.

Pause and stop (agent utils):
- A stop of a launch that is still staging cancels it. The stop had no harness to end, and the launch then ran
  its harness through the checkpoint, or waited until the provider deadline for the continue of a pause request
  that did reach the sandbox.
- An error of a launch that left no receipt of a stop, for example because its sandbox died, propagates as the
  launch's own failure instead of parking a dead session.
- A pause waits, bounded, for a launch that is staging, so a snapshot does not run beside the uploads and the
  launch command's polls are held like a running launch's.

Process supervisor:
- A hold before the launch is not added to the harness deadline again by the first pause after it.
- An expire that arrives during a hold before the launch launches nothing.
- A pause scans until a scan finds no new process, not twice.

Other:
- The launch number in the client session id is gone. Only a continuation session sets that id and only a
  checkpointed session relaunches, and a session is never both, so nothing could send it.
- "discarded N abandoned call row(s)" is logged only when rows were dropped.
- The OpenCode runtime's sandbox path prefix is a module constant, so a test whose sandbox is the test machine
  installs its fake CLI under its own directory instead of one /tmp path shared by every run on the node.

Tests: the cases above; the receipt of a stop that fenced a launch, which has `stopped` since the pause in
place; the kit's local provider; pause numbering, malformed requests and receipts; deterministic
replacements for races and fixed sleeps (a harness that ticks until the test ends it, bounded waits, cleanup of a
paused harness when a test fails half way); larger limits around the real supervisor.

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

* fix(checkpoint): require delete_calls of a capture ledger, and name the calls it deletes "disconnected"

Review of NVIDIA-NeMo#5268.

- `CheckpointableLedger` requires the method, and the model server refuses a ledger without it at startup, so
  the `getattr` fallback and its warning could not be reached. The method is called directly.
- "abandoned" already means a rollout attempt the framework gave up on, and "discard" a fenced write. The calls
  are now `disconnected` (`GateSnapshot.disconnected`, `take_disconnected`), the ledger method is `delete_calls`,
  and the helper `delete_disconnected_calls`. Nothing of this is released, so there is no alias.
- The comments describe the rule the code applies (a call that ended while admission was closed, before its
  response started) and the rows it leaves: an intent row and, sometimes, a failure row.
- `FileLineageStore.delete_calls` removes the rollout from the cache through `_ledger_cache_pop`, which also
  drops the lineage caches.
- `PolicyWorkerLink` uses its gate's ledger instead of a second copy.
- New test: a worker deletes the rows of such a call when it reopens.

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

* fix(agent-utils): bound a checkpoint pause, retry its requests, and never park beside a launch that still writes

Review of NVIDIA-NeMo#5268.

Supervisor (`process_supervisor.sh`):
- `--max-pause SECONDS`: a pause nobody continues used to hold the harness for good, with the deadline not
  running and an expire waiting for the continue. Past the limit the supervisor ends the harness as at its time
  limit and the receipt records `pause_expired`. The limit counts the supervisor's polls, not the clock.
  `SandboxSession.execute` passes the pause allowance as the limit.
- The wait for a continue also ends when the harness is gone.
- The usage text lists the pause options.

Pause and continue requests (`supervisor_client._request`):
- bounded as a whole, so a request queued behind a full provider does not wait for a harness to end;
- run from `control_cwd`, so they do not need a workdir the task moved or deleted.

`SandboxSession.pause_harness` answers `unconfirmed` while the launch is still staging after its wait: a pause
request would only hold the launch command, and staging would keep writing during the snapshot.

`run_until_parked` is now `run_with_checkpoint_pauses` (it returns when the launch ends, parked or not), and
`Finished`/`Stopped` are `LaunchFinished`/`LaunchStopped`. It also:
- repeats a pause request that failed in transport (4 attempts, 1 s doubling) and waits the same way between
  continue attempts; a timeout or an answer of the supervisor is not repeated;
- treats a `receipt_missing` receipt (main's NVIDIA-NeMo#6280: the supervisor died and the provider proved the sandbox
  empty) after its own stop as a stopped launch, not a finished one;
- raises, and does not park, when a launch cancelled while staging does not end within the stop timeout;
- reads the exception of a park request or an abandoned launch, so asyncio does not log it as never retrieved.

`SandboxSession.reattach` is now `rebind`, the word the checkpoint code uses; `ParkingActivation` and
`SandboxSessionCheckpoint` are exported. `exec_idempotent` takes `cwd`, `env` and `timeout_s` explicitly.

The conformance kit moves to `nemo_gym.agents.testing` as `check_harness_checkpointing`: it checks an agent
adapter, and can now import `AGENT_ACTIVATION_HEADER`. Its local provider is private. The crash scenario ends
the first agent (handles, processes, tasks) before the restore and cleans up in a `finally`, and an adapter can
supply `crash_recovery_assertion` to prove the recovery continued the saved conversation.

Tests: the deadline-extension test now fails without the extension, the hold test no longer asserts a tight
real-time bound, and each change above has tests.

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

* fix(opencode): bind a saved reply to its request, keep the trajectory in a checkpoint, and reprompt like a first launch

Review of NVIDIA-NeMo#5268.

- A saved reply is given again only to the request that produced it: the session keeps the request's SHA-256
  with the reply, also in the checkpoint, and a different request under the same activation index is a 409, as
  before this PR.
- The checkpoint keeps a finished session's trajectory, restored under the replacement attempt's rollout ID, so
  a session that finished before the checkpoint still closes with it, also when closed before it is re-bound.
- A re-bind that has to install the runtime again passes the seed's pinned ripgrep and plugin dependencies, and
  stages them through the sandbox connection it holds (`state.session` is not set yet).
- "Resume" names the checkpoint step, so continuing a saved conversation is a reprompt: `reprompt.py`,
  `reprompt_opencode.sh`, `RepromptDecision`. `discard_conversation` is `set_conversation_aside`
  (`data.set-aside-N`).
- The reprompt helper rejects permission requests, as `opencode run` does; under `opencode serve` nothing
  answered one and the turn waited until the harness deadline. It keeps the server's log and the request's
  status in the launch directory, and prints the log's end when the request fails.
- A saved conversation that downloads but cannot be parsed starts the task afresh under its own reason; one
  that cannot be downloaded is still retried and then fails the activation.
- Tool calls a relaunch finds unfinished are counted once each (`interrupted_tool_calls` in the launch record)
  and mark the observations with the gap `tool_call_interrupted_by_relaunch`.
- The reply's metadata carries `harness_paused_seconds` next to `harness_launches`.
- `_reported_model_error` keeps main's exit-0 context overflow (NVIDIA-NeMo#6471) for a launch that did not reprompt.
- The preparation command's package install takes a lock, so a retry that overlaps its first run waits for it.

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

* docs(opencode): document partial-rollout checkpoints, their limits, and the supervisor's pause files

Review of NVIDIA-NeMo#5268: the OpenCode README gets a section on checkpoints (settings, what a pause and a stop do, pause
limits, clocks, recovery after a crash, the reprompt, interrupted tool calls, restart-only sessions); the agent
integration page summarizes it; the harness guide lists the pause and continue files, `stopped` and
`pause_expired` in the receipt, and `run_with_checkpoint_pauses`.

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

* test(hermes): expect `stopped` in the receipt of a stop that fenced the launch

The supervisor now records that a stop request, not the harness's own exit or the deadline, ended or fenced the
launch. Hermes's test compared the whole receipt.

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

* fix(opencode): do not repeat a refused continue, give retries one budget, and report a timeout after a stop

Second review round of NVIDIA-NeMo#5268.

- A continue the supervisor answered with a refusal is not sent again: the same sequence number would read the
  same answer from the acknowledgement file. `HarnessPauseResult.acknowledged` tells such an answer from a lost
  one, which is still retried.
- `exec_idempotent`'s `timeout_s` is the budget of all attempts and the waits between them, not of each attempt.
- When a launch was stopped at a checkpoint and the activation's budget is spent, nothing is relaunched: the reply
  is built from the stopped launch and reports a timeout. Preparing the relaunch used to discard that launch's
  output and then raise.
- A re-bind installs the runtime again only when the check of its files ran and found some missing. A check the
  provider could not run is repeated and then fails the re-bind.
- `prepare_launch` creates the launch directory through `exec_idempotent`.
- The observation bundle of a restored session closed before its re-bind is schema 2.0, like every other close.
- The saved conversation's export is read and decoded in the worker thread that makes it.
- The test of the unread park-request exception now fails without its fix.

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

* test(agents): run the harness checkpoint conformance kit against a minimal adapter in the core suite

The kit's main check only ran in OpenCode's server suite, which the core
coverage gate does not measure, so the combined core coverage fell to
94.86%. A reference adapter whose harness is a shell loop now takes the
kit through every scenario with the real process supervisor, and a second
test shows the kit fails an adapter that cannot pause in place.

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

* fix(opencode): hold a checkpoint for staging that is still writing, bound retries by one deadline, and report a timeout when the relaunch budget runs out

- run_with_checkpoint_pauses: a launch cancelled while staging is not
  reported stopped while its staging task still runs, and no error leaves
  the activation until the launch has ended and staging no longer runs.
  Until then the session is not ready, so the checkpoint waits for it up
  to its own deadline. SandboxSession gains staging and wait_staged.
- exec_idempotent: every attempt runs under the one deadline, which now
  also bounds a provider's wait for capacity; no attempt starts once the
  budget is spent.
- OpenCode: what a stopped launch produced is kept until its relaunch has
  started its harness. A budget that runs out before then, while the
  relaunch is prepared or staged, ends the activation as a timeout with
  the stopped launch's output.

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

* style(opencode): format a test line the linter rejects

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

* fix(opencode): reprompt a saved conversation whose prompt was sent quoted as one argv word

With argv_prompt_quoting (NVIDIA-NeMo#5458) a launch sends the prompt as `opencode run` builds it from one
argv word, so the saved user turn holds the quoted text. A relaunch after a stop compared that turn
with the unquoted prompt, found no match, and started the task afresh every time. It now compares
with the prompt as the launch sent it.

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

---------

Signed-off-by: Pranav Thombre <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>

This branch was previously deployed

1 inactive deployment
public — b8ed8034 Deployed Nov 13, 2026 by copy-pr-bot[bot] via release / finalize / notify #12200
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:agent Agent harnesses and Responses API agent behavior bug Something isn't working complexity:high Cross-component or shared-contract change with a large review surface needs-review PR is ready for code review and waiting on a reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants