Repository navigation
feat(agent-utils): resume a supervised harness in place after a restore that kept its processes - #5412
Conversation
b7223f1 to
11ee927
Compare
2adfe2d to
e9b23c4
Compare
e170dfe to
bc5892f
Compare
bc5892f to
f1f9f47
Compare
…cross a sandbox restore A sandbox restored from a memory snapshot still runs the harness, whose model client points at the model server of the job that took the snapshot. model_relay.py runs beside the harness and forwards its model calls to the upstream named in an endpoint file, so the restoring job can re-point them by writing the file: - a request for /v1/<rest> goes to <upstream>/<rest>, with the harness's method, headers and body; - while the supervisor's pause request is ahead of its continue request, new calls wait unsent; - response headers reach the harness only with the first body byte, so a call whose response has not started is sent again, byte for byte, when the endpoint's generation changes; a started response is cut with a reset; - an unreachable upstream is retried with backoff until --hold-timeout-s, then answered with a 502; - a status file names the relay's pid, start time, port and counters. The relay needs only Python 3.6 and its standard library. harness_runner.sh starts it when the params ask for one (MODEL_RELAY_PORT, _ENDPOINT, _STATUS, _SCRIPT), on the first Python 3.6+ through a neutrally named interpreter link so python-matching kills skip it, restarts it on the same port if it dies, and exports NEMO_GYM_MODEL_RELAY=1. Without a usable interpreter it writes "unavailable" beside the status file and exports MODEL_RELAY_FALLBACK_ENV instead, so the harness can call the model server directly. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]>
…rt wait harness_runner.sh waited for the relay with a wall-clock deadline (bash SECONDS) and checked it before the status file. A checkpoint taken inside that wait stops the sandbox, and a sandbox restored from its snapshot can come back with the wall clock set forward. A jump of more than 10 s made the runner give up as soon as it ran again, even when the relay was already listening, and run the command on MODEL_RELAY_FALLBACK_ENV: the launch could no longer be resumed in place at the next checkpoint. A runner stopped that long by a signal did the same. The wait now counts the runner's own running time from /proc/uptime (SECONDS without it), a gap between two polls counts as at most a second, and the status file is read before the wait is checked. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]>
…ervisor's receipt The command that starts a supervised launch holds the provider's output stream open for the whole run (8490 s for OpenCode with checkpoints). When that stream drops partway (job 8552180: 21 launches), the launch failed: the session stopped a healthy harness and the rollout started over. When the launch command raises and the supervisor has claimed the launch (its pid or launch claim exists), the session now logs "launch connection lost ...; waiting for its cleanup receipt" and waits for the receipt, as `adopt` does after a restore. The receipt's harness status is the launch's result, and checkpoints still pause and continue it through the supervisor's files. A launch whose supervisor never started still fails at once. A receipt poll whose command raises now counts as one failed poll, like a poll that returned an error: it used to end the wait, so a restored launch was relaunched instead of resumed (`adopt_failed`). A sandbox that is really gone still fails after five polls. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]>
…l as on Python model_relay.mjs implements model_relay.py's protocol with node: modules only: the same arguments, endpoint and pause files, hold, re-send, first-byte gating, backoff and 502, and the same status-file layout, which the runner and supervisor read with patterns. A harness built on Bun runs it on its own binary, so an image needs no Python for a launch to resume in place. harness_runner.sh takes MODEL_RELAY_COMMAND, a program and its leading arguments, to run the relay instead of the first Python 3.6+ found, and MODEL_RELAY_COMMAND_ENV for the relay's process alone. The neutral link name, the watchdog, the start wait and the fallback are unchanged. The relay tests run every behavior against both implementations; the JavaScript ones need node or bun (NEMO_GYM_TEST_JS_RUNTIME) and skip without. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]>
…p the Python one The Python relay needed a Python 3.6+ in the task image; model_relay.mjs does the same on the harness's own Bun binary, which every image has, so a second copy of the protocol would only need keeping in step. harness_runner.sh now starts the relay only with MODEL_RELAY_COMMAND; the interpreter search, MODEL_RELAY_SCRIPT and MODEL_RELAY_PYTHONS go. The relay's tests run on Node or Bun, and the runner's on a stand-in relay that writes the status layout, so they need neither. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]>
…l a failed check from a lost launch Found in a review of resuming a harness in place. - `check_restored` runs through `exec_idempotent` and returns `check_failed` when the command still raises: a sandbox that refuses its first commands after a restore no longer fails the restore or reads as a lost launch. - `adopt` repeats an unconfirmed continue up to three times, under the control lock; the request is the same each time. It writes an expiry that was requested before the take-over, before it continues the pause. - The receipt wait ends on failed polls only after five in a row that span a minute, and never while a checkpoint holds the harness: a gateway restart or a snapshot no longer ends a running launch. A poll that returns at once is followed by a pause. The wait returns what the launch command returns: 0 when the receipt confirms the cleanup, else 1. - The relay races a call against the endpoint change through a promise without a value, so a long call's settled results are not kept until the endpoint changes. It logs the first failure of an upstream it retries, and a response that fails after it started aborts the client connection, with a warning, instead of ending it as if complete. - Tests: the worker of the resume tests runs until told to finish, so no test depends on a three-second window; bounded waits in the relay tests, a kill after a stop that times out, a `NEMO_GYM_TEST_JS_RUNTIME` that names no executable fails. New: a launch restored a second time, a cancelled adopted launch, the relay's restore order, an upstream that resets or drops a response, the relay's status file read by `check_restored`, and each fix above. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]>
b8c1d30 to
ff04806
Compare
macandro96
left a comment
There was a problem hiding this comment.
Additional review comments: OOM preservation, control deadlines, relay retry classification, failure provenance, logging, terminology, and runtime/CI validation. Static review; no tests or live sandbox/model runs were executed for this review.
| ((port)) || relay_status_port | ||
| running "$runner" || break | ||
| wait "$relay" 2>/dev/null | ||
| echo "model relay exited with status $?; restarting it on port $port" >>"$relay_log" |
There was a problem hiding this comment.
Validation question: verify in-flight calls recover when the relay itself crashes
The watchdog restores the listener, but a relay crash loses its buffered requests and existing client connections. Does the pinned OpenCode runtime retry the resulting reset both before any response reaches it and after streaming begins? Could we add or cite a focused integration test on the reviewed head using OpenCode's binary with BUN_BE_BUN=1? The earlier live evidence in the PR description is useful, but the current-head validation only names Node against fake upstreams. This can be exercised with the integration in #5413.
|
|
||
| JS_RUNTIME = _js_runtime() | ||
|
|
||
| pytestmark = pytest.mark.skipif(JS_RUNTIME is None, reason="no JavaScript runtime (node or bun) on this machine") |
There was a problem hiding this comment.
Testing suggestion: require relay tests to execute in the relevant PR CI job
Could we explicitly install/select a JavaScript runtime in PR CI and set NEMO_GYM_TEST_JS_RUNTIME, so a missing runtime fails instead of skipping this entire suite? The core setup does not ensure Node or Bun is installed, and the PR description reports these tests being skipped there. Keep the optional local skip, but make execution required in the designated CI job. Ideally also exercise the production Bun path; when both runtimes are present, the automatic selection here chooses Node.
Model relay: - Bound each connection attempt (name lookup, TCP, TLS) by 30 s or what is left of the hold timeout, and count the time it waited, so an upstream that accepts and never completes TLS ends in the promised 502. - Answer 502 at once, naming the cause, for an upstream the relay cannot use: an address that is not http or https or has no host or a bad port, and a reply with a malformed status line, Content-Length or first chunk size. Connection failures and interrupted responses are retried as before. Launch recovery after a lost connection: - Repeat the start probe when the sandbox refuses it, read the launch claim as the link it is, and run the probe and the receipt polls from outside a workdir the task may have moved. - Re-raise a provider-confirmed OOM kill from a receipt poll instead of counting it as a failed poll. - Name the lost connection as the cause when the receipt never comes. - Warn once for each run of failed receipt polls, also while a pause is held. Pause and continue: the timeout covers the wait for another pause or continue request of the session as well as the request; unconfirmed when the other request outlasts it. Abandonment: keep every process reached, by PID and start time, across scans, so one that outlives its parent is still waited for; and raise when the abandonment failed beside the receipt of a launch that had finished. Runner: resolve the relay program on PATH or relative to the working directory before linking it. Glossary: add "Model relay". Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]>
|
/ok to test fe4dcb9 |
…box cannot answer for it A launch whose connection is lost is finished from its supervisor's receipt. Two answers of the sandbox left the launch failing with another error than the one that lost its connection, which harnesses match on: - A receipt that is no JSON object ended the wait as a failed launch command. It now ends the wait as unreadable_receipt, and the launch fails with the error that lost its connection. - A start probe whose answer could not be read raised from the probe. It now counts as not started. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]>
|
/ok to test cf618e3 |
macandro96
left a comment
There was a problem hiding this comment.
Two residual P2 follow-ups after reviewing the fixes. These refine the existing timeout and abandonment threads; they are not additional independent findings.
| error=f"another pause or continue request held the session for the whole {timeout:g}s timeout", | ||
| ) | ||
| try: | ||
| return await request(timeout=max(0.0, deadline - monotonic())) |
There was a problem hiding this comment.
[P2] Enforce the deadline across the control request as well as lock acquisition
Follow-up to #5412 (comment): the lock wait is now bounded, but request() runs outside the timeout context. _pause can spend the remaining budget waiting for staging and then reuse that same budget for request_pause; the supervisor client permits another timeout + 10 seconds. Thus pause_harness(timeout=T) can still take roughly 2*T + 10 seconds despite its whole-call deadline contract. With timeout=0.1, staging finishing at 0.08 seconds, and a stalled exec, I confirmed the call remained pending at 0.25 seconds.
Could we enforce the absolute deadline across both lock acquisition and request execution, return an unconfirmed result on expiry, and ensure the lock is released? Add coverage where staging consumes part of the budget and the subsequent request stalls.
| ((${#doomed[@]})) || break | ||
| for pid in "${!doomed[@]}"; do | ||
| reached[pid]=${start[pid]} | ||
| kill -KILL "$pid" 2>/dev/null |
There was a problem hiding this comment.
[P2] Recheck process identity immediately before abandonment signals
Follow-up to #5412 (comment): retaining reached identities now handles reparenting across rounds, but this loop still signals a PID without checking that it has the start time recorded during the scan. If that process exits and its PID is reused during the /proc scan or descendant traversal, abandonment can kill an unrelated replacement. The new reused-PID test covers reuse between rounds, not between scanning and signaling.
Could we mirror kill_reached(): re-run stat_fields immediately before signaling and require fields[19] to match reached[pid]? Add a deterministic test that changes the identity after enumeration and before signaling; the replacement must not be signaled.
…on only the processes reached Pause and continue: the timeout now bounds the request as well as the wait for another request of the session. The request gets what the wait for the lock, and for a pause the wait for the launch's staging, left of it, and the deadline ends the request when that runs out. pause_harness(timeout=T) is therefore unconfirmed by T, instead of after up to about 2T + 10 s. Abandonment: each process is signalled only while it still has the start time the scan read, as the supervisor's cleanup does, so a PID handed on between the scan and the signal is not killed. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Zeyu Zhou <[email protected]>
|
/ok to test 06bd0a3 |
| [[ $pid != "$$" ]] && stat_fields "$pid" || continue | ||
| [[ ${fields[0]} == [ZX] ]] && continue | ||
| parent[pid]=${fields[1]} start[pid]=${fields[19]} | ||
| if [[ $pid == "$shell" || ($pid == "$supervisor" && ${fields[19]} == "$started") || |
There was a problem hiding this comment.
[P2] Retain the launch shell's original identity across abandonment rounds
Follow-up to #5412 (comment): the new pre-signal check addresses PID reuse between enumeration and signaling, but the launch shell is still remembered only as a PID. This unconditional shell-PID match selects it afresh on every scan. If the original shell exits and its PID is reused during cleanup, a later scan records the replacement's new start time, and the new pre-signal check consequently passes and kills that unrelated process.
I reproduced this with a simulated process table and an overridden kill that sends no signals: shell PID 2000/start 200 is selected in round 0, then the same PID/start 300 is selected and signaled in round 1.
Could we record the shell's start time when identifying the launch parent and require both PID and original start time here? Alternatively, seed its verified identity into reached once and remove the unconditional PID-only root. Add coverage for shell PID reuse between cleanup rounds.
…bandoning a launch Abandonment matched the shell that started the supervisor by its PID alone, afresh on every scan, so a process that took over the PID after the shell exited was selected and killed in a later round. The shell's start time is now read with its PID when it is identified, and the shell is kept among the reached processes like any other, so only that process is signalled. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Zeyu Zhou <[email protected]>
|
/ok to test c5f6756 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/45281179579 |
What changed and why
After a crash, the stack restores a sandbox from its snapshot and relaunches the harness from its saved conversation (#5268). On a provider whose snapshots keep processes (AgentENV, #5410), the restored sandbox is still running the harness: the supervisor holds the checkpoint's hold pause (#5411), and the harness is mid-task with its tools, background servers and in-memory state intact. Relaunching would throw that away and start a second harness beside the first.
Two things stand in the way of simply continuing it:
This PR adds the agent-utils pieces that solve both, for any harness under
SandboxSession. #5413 wires them into OpenCode.1. Model relay
The relay runs beside the harness inside the sandbox and forwards its model calls to the upstream named in an endpoint file, so the restoring job can re-point it by rewriting that file. It is JavaScript using only Node's standard modules, so a harness built on Bun runs it on its own binary (
BUN_BE_BUN=1), and Node runs it too: the relay needs nothing from the task image.The harness runner starts the relay with the command the harness gives (
MODEL_RELAY_COMMAND, with variables set for the relay's process alone), through a link with a neutral name that a task'spkillof python or of the harness does not match, and a watchdog restarts it on the same port. If the relay cannot start, the runner marks it unavailable and the harness calls the model server directly.2. Taking over a restored launch
check_restored(...)checks in one command that the supervisor runs with the recorded identity, holds that pause in hold mode with no continue and no receipt, and optionally that the relay still runs. It returnsRestoredLaunch, orNotResumable(reason)with one ofsupervisor_gone,identity_mismatch,pause_mismatch,launch_finished,relay_gone,relay_unavailable,check_failed.SandboxSession.adopt(...)continues that pause, polls for the supervisor's receipt, then stops, collects and releases the launch asexecutedoes. Later checkpoints pause the same supervisor from the next pause number.abandon_launch(...)(and the supervisor's abandon mode) ends a launch that will not be taken over: KILL, never CONT, to the supervisor and everything it launched, then anabandonedreceipt. A harness woken later would otherwise call a model server that no longer exists.The wall clock is the provider's to keep. Nothing here sets a restored sandbox's clock. On AgentENV,
snapshots.keep_guest_clock(#5410) makes a restored sandbox continue from the clock its snapshot was taken at.3. Launches that lose their connection, and the relay's start wait
4. A relay that runs on any image (last two commits)
The relay was first written in Python, so it ran only on task images with Python 3.6 or later; on others (PHP, Julia, Java and some JavaScript images) a launch ran without it and could not resume in place. It is now JavaScript, run by the harness's own binary, and the Python version is removed, so there is one implementation of the protocol. Its behavior and status file are unchanged, so the take-over below needed no change.
Found in the review of this PR and fixed here (last commit)
check_restoredis retried. It runs throughexec_idempotentand returnscheck_failedwhen the command still raises, so a sandbox that refuses its first commands after a restore no longer fails the restore or reads as a lost launch.adoptrepeats an unconfirmed continue up to three times, and writes an expiry that was requested before the take-over, before it continues the pause.How it works
sequenceDiagram participant G as Restoring job (agent server) participant S as Supervisor (restored, holding pause N) participant R as Model relay (restored) participant H as Harness (restored, mid-call) participant M as New model server G->>S: check_restored(pause N, identity, relay) alt RestoredLaunch G->>R: rewrite endpoint file (new URL, generation plus 1) G->>S: continue N (adopt) R->>M: re-send the cut call, byte for byte M-->>R: response R-->>H: response (looks like a slow call) H-->>S: exits S-->>G: receipt, then collect and release else NotResumable(reason) G->>S: abandon launch (KILL, no CONT) Note over G: relaunch from the saved conversation, as before endWhere this sits in the stack
This stack checkpoints environment-server episodes whose agent harness runs in a sandbox the resources server lends. #5264, #5265 and #5266 have merged, and the rest of the stack is rebased onto
mainafter them. #5265 to #5331 add checkpoints for OpenCode and the SWE servers on OpenSandbox. #5410 to #5413 add AgentENV (E2B API, VM memory snapshots), where a restored sandbox still runs the harness's processes, so OpenCode continues in place instead of being relaunched. Each PR's diff shows only that PR's change.Issue
No tracking issue exists. This is the core of AgentENV in-place resume; #5413 applies it to OpenCode.
Validation
Head
6ff53fb3ac, on #541137d9fe7184. The stack was rebased ontomainafter #5266 merged. Tests ran as Slurm jobs on one node each, in therl-gymCI container with the repository's dev dependencies; nothing ran on a login node. In that containermainitself has 179 failures and 13 errors in the core unit suite (job 9188100), so results are compared withmain's list by test id. Two test files that hang there, onmaintoo, are left out:tests/unit_tests/test_slurm_control.pyandtests/unit_tests/benchmarks/test_agentic_vbench_staging.py.3d0e643db9, which includes this PR (jobs 9188099, 9188102): import-linter clean;ruff checkandruff format --checkclean; all ten server suites pass; the core suite differs frommain's list only by tests that fail from run to run on either side.mainonly by tests that fail when the node is loaded and pass when their file runs alone (test_harness_pause.py::test_a_hold_before_the_launch_is_not_added_to_the_deadline_again_by_a_later_pause,test_exec_transport.py::test_confirmed_cleanup_cancels_stuck_transport) andtest_docker_compose.pytests that fail from run to run onmaintoo. The whole core suite was run per level on the previous base (feat(swebench): checkpoint the task sandboxes of episode sessions #5266's head before it was squash-merged), with the same result; on this base it ran on the tip only.NEMO_GYM_CHECKPOINT_E2E=1): harness scenarios 11 passed, sandbox 6, sequences 4, fake backend 1,test_checkpoint_e2e.py45 passed and 12 skipped.test_harness_resume_in_place.py:test_cancelling_the_wait_for_a_lost_launchs_receipt_stops_the_harnessfailed once on the stack tip when 32 workers ran the agent tests alone (job 9188585) and passed in the tip's full core run. It was not rerun alone.nodejswheel, named byNEMO_GYM_TEST_JS_RUNTIME) against fake upstreams. It was not run on OpenCode's real binary (BUN_BE_BUN=1) on this head; production runs it there.check_restored, and one per fix above. The worker of the resume tests runs until told to finish, so no test depends on a fixed window.pre-commit run --all-files; any live sandbox, real-model or training run on this head.e62ed9ca9a), not repeated on this head: 16-node full-SWE run on AgentENV, Slurm job 9048275 (2 h, five routes, 8 Gym replicas), compared with reference job 8760594 on an earlier stack. 3 training steps (2981 s, 2567 s, 670 s; reference 2948 s, 2606 s, 681 s); 8 rollout checkpoints saved, 0 failed (reference 7 / 0); checkpoint save median 57 s, Gym commit median 50 s (reference 65 s and 48 s); 351 full 16-rollout batches, median 730 s (reference 347, 720 s); no snapshot, fork, anti-cheat, base-commit or patch-extract failures. The AgentENV gateway returned about four times as many 502s as in the reference; on the servers of this stack each was a retried first attempt and none exhausted its retries. Not exercised: the run had no crash, so no restore and no resume in place ran;scale_sweis not on the checkpoint layer.Follow-ups, not in this PR:
reattachandadopt(addressed for OpenCode in feat(opencode): resume OpenCode in place on sandboxes whose snapshots keep processes #5413).Compatibility
check_restored,adopt). OpenSandbox runs and existing harnesses are unchanged.snapshots.keep_guest_clockin feat(sandbox): AgentENV snapshots, lease and kill-at-timeout for the E2B provider #5410 for AgentENV.MODEL_RELAY_COMMANDreplacesMODEL_RELAY_SCRIPTandMODEL_RELAY_PYTHONS.scripts/ci/core_test_durations.jsongains the two new test files and the runner test's new duration.🤖 Generated with Claude Code