Skip to content

feat(opencode): pause at checkpoints and resume after a crash - #5268

Merged
pthombre merged 17 commits into
mainfrom
pranav/envckpt-4-opencode
Nov 21, 2026
Merged

pthombre merged 17 commits into
mainfrom
pranav/envckpt-4-opencode

Conversation

@pthombre

@pthombre pthombre commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

OpenCode episodes could not be checkpointed: a checkpoint either waited for the harness (which can take an hour) or, after a crash, started the episode over. This PR makes OpenCode the first harness that is paused in place at a checkpoint and, after a stop or a crash, continued without an added user turn. The pausing mechanism is shared, so other harnesses on SandboxSession can adopt it.

Terms used below: the activation parks at a checkpoint; the harness (OpenCode's processes) is paused and continued; a restored session is re-bound to the sandbox its replacement attempt borrows; relaunching OpenCode on its saved conversation is a reprompt (the last user message is posted again with no new parts). "Resume" is kept for the checkpoint step that releases parked participants.

Four parts:

4a. Capture fix (a cherry-pick of #4451)

Stopping a harness would otherwise poison the token-capture ledger. The policy gate records calls that ended while admission was closed, before their response started (GateSnapshot.disconnected). The commit leaves them out like undelivered calls, and the resume deletes their rows from the live ledger (CheckpointableLedger.delete_calls, required of every ledger), in the coordinator and in each worker.

4b. Pause in place (shared agent utilities)

  • Process supervisor (bash, since the task image may have no Python). A numbered pause request makes it SIGSTOP every process of the harness, including detached services, scanning until a scan finds no new process, wait until all are stopped, and acknowledge. A matching continue request sends SIGCONT. Numbers only grow, so every checkpoint re-arms the protocol. Time paused does not count against the harness deadline, a pause requested before the launch holds the launch, an expire that arrives during such a hold launches nothing, and a stop while paused continues the processes first so that TERM reaches a running harness. The existing stop behavior is unchanged.
  • A pause has an upper bound (--max-pause, set from the pause allowance). A pause nobody continues, for example because the agent server died during a checkpoint, ends the harness as at its time limit, and the receipt records pause_expired. The limit counts the supervisor's own polls, not the clock. The wait also ends when the harness is gone.
  • CleanupReceipt.stopped (optional): records that a requested stop ended the harness or fenced its launch.
  • SandboxSession(pausable=True): pause_harness() and continue_harness(), a pause allowance on the provider's exec deadline, and checkpoint_state() with rebind() to re-bind a session to the sandbox a restore forked. A pause waits, bounded, for a launch that is still staging; if staging is still running after that, the pause is not confirmed and the launch is stopped, so a snapshot never runs beside the uploads. Pause and continue requests are bounded as a whole (a request queued behind a full provider times out) and do not need the task's workdir to exist.
  • run_with_checkpoint_pauses races a launch against the activation's park request: pause, park, continue after the checkpoint, and repeat for the next one. It returns LaunchFinished or LaunchStopped. A pause or continue request that fails in transport is repeated with backoff and the same sequence number. An unconfirmed pause or a repeatedly failing continue falls back to a stop, and the adapter relaunches. A supervisor that died during that stop (main's receipt_missing receipt, feat(agents): supervisor stop policy and Codex tool pid namespace #6280) counts as stopped. A launch cancelled while staging that does not end raises instead of parking. A cancelled activation still stops its harness.

4c. OpenCode policy

  • Opt in: checkpoint_mode = "exported". A re-bound session renders its configuration again, and main's MCP grant check (feat(gdpval): run OpenCode and OpenClaw with task tools #5079) runs for every launch. These sessions restart instead: one whose sandbox the agent owns, a multi-turn continuation, one that continues an imported conversation (session_import_path), and an OpenCode 2 session (the reprompt uses OpenCode 1's server API and store). The deprecated local /run is a restart too.
  • Layout: a checkpointed session keeps its supervisor state and OpenCode's data under sandbox_session_root, which must be on the sandbox's snapshotted disk.
  • Activation: close and retire cancel the launch, the concurrency limit is applied while queued (through Activation.slot), and a restored session that was never re-bound answers 409. A re-sent activation is answered from the saved reply only when it is 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.
  • Launch loop: a confirmed pause continues the same launch. A stopped launch is relaunched with the remaining budget. A relaunch, or the first launch after a restore, reprompts the saved conversation when it starts with the task's prompt and has a completed assistant message: reprompt_opencode.sh starts OpenCode's server in the sandbox and re-posts the last user message, which OpenCode runs again without adding a turn. Otherwise the task starts afresh and the saved conversation is set aside, with the reason logged at WARNING. Replies report harness_launches and harness_paused_seconds.
    • A saved conversation that cannot be downloaded is read up to three times and then fails the activation. One that downloads but cannot be parsed starts the task afresh, under its own logged reason.
    • A tool call that was running when the launch ended is shown to the model as [Tool execution was interrupted] (OpenCode's text). The rollout is kept and marked: the observations carry the gap tool_call_interrupted_by_relaunch, and the launch record counts the calls.
    • A reprompted launch that ends in a model error OpenCode reports is recognised (the helper exits 0 once the server answered, where opencode run exits 1); main's exit-0 context overflow of OpenCode 1.15 (fix(opencode): score a context overflow that OpenCode 1.15 reports with exit 0 #6471) is kept for launches that did not reprompt.
  • reprompt_opencode.sh: rejects permission requests, as opencode run does (under opencode serve nothing answered one, and the turn waited until the harness deadline); keeps the server's log and the request's status in the launch directory and prints the log's end when the request fails; runs the prompt request in the background so the supervisor's TERM acts at once.
  • Hooks: export and restore of agent sessions, including a finished session's trajectory (restored under the replacement attempt's rollout ID), and a re-bind that connects to the forked sandbox and reinstalls the runtime if the fork lacks it, with the seed's pinned ripgrep and plugin dependencies.
  • Conformance kit: check_harness_checkpointing (nemo_gym/agents/testing/checkpoint_conformance.py, exported from nemo_gym.agents), run against OpenCode with a fake OpenCode binary under the real supervisor. Its crash scenario ends the first agent before the restore, and an adapter hook asserts that the recovery continued the saved conversation.
  • Docs: a "Partial-rollout checkpoints" section in the OpenCode README (settings, pause limits, clocks, recovery, interrupted tool calls, restart-only sessions), a summary on the agent integration page, and the pause files and receipt fields in the harness guide.

4d. Setup retries and capture errors (from the AgentENV training runs)

  • exec_idempotent (shared agent utilities) runs a setup command again, twice, with a short backoff, when the provider fails to run it; a returned result, any exit code, is final. Only for commands that are safe to run twice, also at the same time: the preparation command's package install takes a lock for that.
  • OpenCode's setup goes through it: the workdir, the preparation, the runtime install, and setting a conversation aside.
  • A restore that finds no conversation yet starts afresh with one INFO line instead of a warning and a traceback.
  • A launch that ended before OpenCode saved anything reports one capture error with the runner's log (NothingCapturedError).

Known limit: a pause stops OpenCode's processes, not their clocks. A tool that runs across a pause sees the paused time, so its timeout can fire when OpenCode continues (the shell tool's default is two minutes). Model calls are not affected. #5411 removes the freeze on sandboxes whose snapshots keep processes.

This builds on ideas from #4274, #4553 and #4222 in the legacy stack, rebuilt on main's SandboxSession (#4747) and bash supervisor (#5151).

How it works

Where this PR sits in the overall flow

The highlighted parts are what this PR changes.

flowchart LR
  C["Controller<br/>NeMo RL, or rollout collection"]
  CO["Coordination<br/>prepare, commit, resume, restore,<br/>retire, forget, release"]
  E["Environment server<br/>single_agent_turn, single_agent_turn_legacy<br/>bookmarks, re-seed after a restore"]
  A["Harness agent, e.g. OpenCode<br/>run_with_checkpoint_pauses, re-bind, reprompt"]
  S["Process supervisor in the task sandbox<br/>pause, continue, stop"]
  R["Resources server, e.g. SWE-bench<br/>owns and lends the task sandbox"]
  OB["Session base with checkpoints<br/>export, restore, release"]
  K["Sandbox checkpointer<br/>snapshot index, release, gc"]
  P["Sandbox provider, e.g. OpenSandbox<br/>snapshot, fork, delete, list"]
  M["Policy model<br/>held calls, capture ledger"]
  D[("Checkpoint directory<br/>and state_dir")]
  C --> CO --> E & A & R & M
  E -- "seed, re-seed" --> R
  E -- "seed, re-seed, activation" --> A
  R -. "sandbox_access" .-> A
  A --> S
  R --- OB --> K --> P
  A -- "model calls" --> M
  CO --> D
  classDef this fill:gold,stroke:darkorange,stroke-width:2px,color:black
  class A,S,M this
Loading

This PR

One activation under run_with_checkpoint_pauses, across a checkpoint with a confirmed pause, a checkpoint whose pause fails, and a crash.

stateDiagram-v2
  [*] --> Running: launch K, fresh or reprompting the saved conversation
  Running --> Finished: harness exits
  Running --> Pausing: park requested
  Pausing --> Parked: pause confirmed
  Pausing --> Stopping: not confirmed
  Parked --> Running: resume, continue the same launch
  Parked --> Stopping: continue failed 3 times
  Stopping --> Relaunch: stopped receipt, park, then resume
  Relaunch --> Running: launch K+1, reprompt the saved conversation
  Finished --> [*]: completed reply saved
  Parked --> Crash: process dies
  Crash --> Relaunch: restore, re-seed, re-bind to the fork
Loading

A checkpoint while OpenCode works, end to end:

sequenceDiagram
  participant C as Coordination
  participant A as OpenCode agent
  participant S as Supervisor in the sandbox
  participant M as Policy model
  participant R as SWE-bench server
  C->>M: prepare (the in-flight call is held, not delivered)
  C->>A: prepare, park requested
  A->>S: pause request N
  S-->>A: paused, every process stopped
  A->>A: park at the activation boundary
  C->>R: prepare, then commit, snapshot the paused sandbox
  C->>A: commit, export the session
  C->>A: resume
  A->>S: continue request N
  S-->>A: continued
  C->>M: resume, the held reply is delivered
  Note over A,S: OpenCode carries on as if the call were slow
Loading

Where this sits in the stack

This is one PR in a stack for checkpointing environment-server episodes whose agent harness runs in a sandbox the resources server lends (first pair: OpenCode and SWE-bench on OpenSandbox; #5410 to #5413 add AgentENV, where OpenCode resumes in place after a restore). #5264 to #5267 have merged, and this PR is rebased onto main after them. #5269 and later are still based on the previous version of this PR and are restacked next. The stack runs parallel to the legacy_agent path of #4220 to #4936, which it does not change or depend on.

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

Issue

No tracking issue. This implements the environment-server plan for checkpointing sandboxed harnesses, on top of the merged partial-rollout checkpoint stack (#3882 to #3909, #4997).

Validation

Head 23543cf01e, on main 662dc7559f. Tests ran as Slurm jobs on one node each, in the rl-gym CI container with the repository's dev dependencies; nothing ran on a login node. In that container main itself fails 176 tests with 12 errors in the core unit suite, so results are compared with main's list by test id. Two test files that hang there, on main too, are left out: tests/unit_tests/test_slurm_control.py and tests/unit_tests/benchmarks/test_agentic_vbench_staging.py.

  • Core suite, this head against main (jobs 9214018, 9214020): all of tests/unit_tests, the SWE-bench and SWE-rebench server tests and the environment server tests. The same 176 failures and 12 errors on both; no test fails on this head that passes on main.
  • The areas this PR changes (job 9214463): OpenCode's tests, tests/unit_tests/agents, tests/unit_tests/models: 4382 passed, 25 skipped, 5 failed. The 5 are the container's, on main too: three need cloudpickle, which the test environment lacks, and two compare a shell's stderr that the image adds lines to.
  • Lint: import-linter clean; ruff check and ruff format --check clean on the changed files (ruff 0.9.9).
  • Tests fail without their fix: 20 fixes were removed one at a time and the test meant for each was run (jobs 9214463, 9214800). 19 are caught, among them the deadline extension, the worker's delete, the 409 for a different request while the activation runs, and the three reads of a saved conversation, which the review found untested. One is not: the test for the unread exception of a park request passes without its fix, and is to be strengthened.
  • Tests: pause, continue, the pause limit and the stop fallback under the real supervisor; run_with_checkpoint_pauses, including retries, a staging launch and a lost supervisor; the capture fix in the coordinator and in a worker; the conformance kit against OpenCode (pause in place, relaunch, crash then re-bind and reprompt, with the recovery assertion); the saved reply and its request before and after a restore; the trajectory through a checkpoint; the pins on a re-bind; the two unusable-conversation cases; interrupted tool calls; the reprompt helper's permission reject on both of its transports.
  • Not checked against a real OpenCode on this head (only against the fake binary): the reprompt helper's permission reject (its endpoints are taken from OpenCode's source at v1.17.11), what a TERM-stopped opencode run leaves in its database, and message order after a reprompt.
  • Not run on this head: pre-commit run --all-files; any live sandbox, real-model or training run.
  • Training runs of the whole stack, on an earlier revision (e62ed9ca9a plus baseline-parity switches), not repeated on this head: the MR 69 50-step recipe on AgentENV, 16 nodes, five SWE harnesses as OpenCode sessions, once without sandbox resume and once with it.

Follow-ups: a smoke run of the pause, the stop and relaunch and the reprompt with a real OpenCode and model on this head; the pause mode in each launch record (#5411).

Compatibility

  • Supervisor: new pause and continue options and --max-pause, used only by pausable sessions; other harnesses launch exactly as before. CleanupReceipt.stopped and pause_expired are optional.
  • SandboxSession: pausable defaults to false; the new methods are additive.
  • OpenCode: with checkpointing off, nothing changes. With it on, sessions are exported instead of restarted, live under sandbox_session_root (default /tmp/nemo-gym-opencode-sessions), and replies carry harness_launches and harness_paused_seconds. New settings sandbox_session_root and checkpoint_pause_allowance_seconds (default one hour): a launch's pauses must fit within it, and one pause longer than it ends the harness as at its time limit.
  • Setup commands the provider fails to run are retried; a command that runs and fails is not.
  • Token capture: existing ledgers and checkpoints stay valid. A capture ledger used with checkpoint.policy must implement delete_calls; the checkpoint protocol is in no release, and FileLineageStore is its only implementation.
  • Rollout stop (feat(agent): let a caller stop a running rollout and still grade it #5145): an expiry that arrives while the harness is paused takes effect when the pause ends. fix(agent): stop waiting for a stalled harness after a rollout stop #6452 (open) bounds the wait after a rollout stop: whichever of the two lands second has to leave paused time out of that bound.
  • MCP tool grants (feat(gdpval): run OpenCode and OpenClaw with task tools #5079): main's grant check runs for every launch, including a relaunch after a stop and the first launch after a restore.
  • fix(checkpoint): leave the calls a checkpoint abandoned out of the capture ledger #4451 remains open in the legacy stack; its commit here drops out on rebase once it merges.

🤖 Generated with Claude Code

@copy-pr-bot

copy-pr-bot Bot commented Oct 29, 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.

@pthombre pthombre added feature New capabilities, enhancements, or enablement work area:agent Agent harnesses and Responses API agent behavior complexity:high Cross-component or shared-contract change with a large review surface labels Oct 29, 2026
@pthombre
pthombre added this pull request to stack #5270 October 29, 2026 05:56
@pthombre
pthombre force-pushed the pranav/envckpt-4-opencode branch from 77110b2 to f0e3843 Compare October 29, 2026 22:39
@pthombre
pthombre force-pushed the pranav/envckpt-4-opencode branch from f0e3843 to 36ae821 Compare October 31, 2026 18:07
@pthombre
pthombre force-pushed the pranav/envckpt-4-opencode branch from 36ae821 to ba4d1bd Compare November 3, 2026 03:22
async with participant.activation(
state.request.agent_session_id, state.request.episode_id, index=index
) as activation:
response = await self._session_response(state, body, prompt=prompt, system=system, activation=activation)

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.

_activation_task calls this without a deadline, so launch_deadline stays None and every relaunch gets the original full timeout. The continuation path uses started + timeout and adds paused time back. Is a stopped launch supposed to get only what is left of the budget?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in an earlier revision and still so: a relaunch gets what is left of the activation's budget, deadline + paused time (_run_launches), not the full timeout again.

await state.discard_conversation(timeout=timeout)
state.harness_session_id = None
state.message_ids = []
return payload

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.

This fresh-start path clears harness_session_id and moves the data directory aside, but the command in payload was already built with --session for the old id. Does opencode run --session then look that id up instead of running the original prompt? Should the command be rebuilt after the id is cleared?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in an earlier revision: the launch command is built after the reprompt decision (_relaunch_payload takes the payload as a callable), so a fresh start no longer names the conversation it set aside.

command.extend(["--session", state.harness_session_id])
payload = {
activation_id = {}
if state.is_continuation:

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.

This launch tag is set only when is_continuation, and those sessions are the ones _seed_restarts keeps out of checkpointing. The relaunch loop is the checkpointed path, which never sets NEMO_GYM_OPENCODE_ACTIVATION_ID, so the header plugin sends no X-Session-Id. Do relaunched calls still join the one invocation, or should this tag be on the checkpointed launches?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The tag is only needed by continuation sessions, where one sandbox serves several activations and the header tells them apart. A checkpointed session has one activation, and its invocation ID is the rollout's capture key, so every relaunch's calls join the same invocation without the header. No change.

@pthombre
pthombre force-pushed the pranav/envckpt-4-opencode branch 2 times, most recently from 0b71f66 to ecf2a34 Compare November 5, 2026 20:07
@pthombre

pthombre commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

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

pthombre and others added 6 commits November 21, 2026 11:07
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]>
…atabase

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]>
…nch 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]>
…arked 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]>
…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]>
…he calls it deletes "disconnected"

Review of #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]>
macandro96
macandro96 previously approved these changes Nov 21, 2026
pthombre and others added 9 commits November 21, 2026 11:09
…ever park beside a launch that still writes

Review of #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 #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]>
… in a checkpoint, and reprompt like a first launch

Review of #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 (#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]>
…nd the supervisor's pause files

Review of #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]>
…he 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]>
…get, and report a timeout after a stop

Second review round of #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]>
…nimal 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]>
…ound 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]>
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
…oted as one argv word

With argv_prompt_quoting (#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]>
@pthombre

Copy link
Copy Markdown
Contributor Author

/ok to test dc1ad56

@pthombre
pthombre requested a review from macandro96 November 21, 2026 19:52
@pthombre
pthombre enabled stacked auto-merge November 21, 2026 19:53
@pthombre
pthombre added this pull request to the merge queue Nov 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

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

Merged via the queue into main with commit aa9dc24 Nov 21, 2026
125 of 136 checks passed
@pthombre
pthombre deleted the pranav/envckpt-4-opencode branch November 21, 2026 20:41
yaoyu-33 added a commit that referenced this pull request Nov 23, 2026
…e-v1-v2

Resolve conflicts with main's checkpoint/resume (#5268) and task-container (#5458) work:
- app.py: keep main's _reported_model_error signature (reprompted) with the
  _CLASSIFIED_OPENCODE_VERSIONS docstring; take main's _install_session_files call and
  pass the release digests for every pinned version there, as the PR did inline.
- README.md: OpenCode 2 prints v2.3.2, plus main's task-container sentence.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:agent Agent harnesses and Responses API agent behavior complexity:high Cross-component or shared-contract change with a large review surface feature New capabilities, enhancements, or enablement work risk:high Autobot PR risk: high waiting-on-customer Waiting on the original author to respond

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants