Repository navigation
fix(agent): stop waiting for a stalled harness after a rollout stop - #6452
gwarmstrong wants to merge 4 commits into
Conversation
A rollout stop (NVIDIA-NeMo#5145) only writes the supervisor's expire.request and returns; the activation then waits on the supervised command until the provider's execution deadline, the agent timeout plus the cleanup reserve. When memory pressure stalls the sandbox, the supervisor does not act on the marker, and Gym keeps polling the command for hours. In a TB-Science run, a Codex rollout stopped at its 8 h budget came back 292 minutes later, with its model replicas held all along. Once the expire marker is in the sandbox, the activation now waits for the command only for the supervisor's own cleanup bound: its three cleanup phases plus 30 s (cleanup_bound, the same reserve the provider deadline keeps after the harness timeout; session_close_timeout_seconds plus 30 s, 90 s by default and 330 s for TB-Science). Agents can set rollout_stop_grace_seconds instead. Past it, the session logs one warning naming the rollout and reads the supervisor's receipt within the close timeout, without a stop request, which would turn the expiry into a cancellation if the supervisor resumed: - a receipt that confirms termination (the command's status hung after the supervisor finished) lets the activation capture and be graded as a stop, as before; - otherwise termination is unconfirmed, as after a negative receipt: the session records harness_termination_unconfirmed, stops polling the command, and raises it, so the rollout fails cleanly instead of hanging. Close releases a borrowed sandbox for the Resources Server's teardown, or stops an owned one, unchanged. stop_and_confirm_cleanup now reads the receipt through the new read_cleanup_receipt; its behavior is unchanged. Signed-off-by: gwarmstrong <[email protected]>
SimpleResponsesAPIAgent.stop_rollout now passes grace to SandboxSession.expire; the session-routing tests' stand-in session must accept it. Signed-off-by: gwarmstrong <[email protected]>
|
/ok to test fe71308 |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP WITH CARE
RISK: The overdue-stop path can replace a confirmed sandbox OOM with harness_termination_unconfirmed if the command reports the OOM during the receipt read.
I inspected all nine changed files and their affected execution, receipt, routing and grading paths. Two delegated reports were unavailable, so I inspected those scopes directly. This was a source-only review; I did not execute tests.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
| if receipt is not None: | ||
| self.cleanup = receipt | ||
| return | ||
| if self.termination_error is None: |
There was a problem hiding this comment.
RISK: Preserve a confirmed execution OOM received during the receipt read
When the grace expires, _stop_overdue_harness() awaits the receipt. During that await, the launch task can finish with PROVIDER_OOM_KILLED, which OpenSandbox's status path reports. If the receipt is missing or its read times out, this branch synthesizes harness_termination_unconfirmed. Then _release_exec() consumes the completed command's exception, so the confirmed OOM never reaches the existing execution classifier. A stopped rollout loses its confirmed-OOM attribution, and close attempts in-sandbox directory removal instead of taking the dead-sandbox release path.
Could you check for an already completed execution OOM before synthesizing the missing-receipt failure? Immediately before this if, this narrow addition lets the existing classifier handle it:
if (
self.termination_error is None
and self._exec_task is not None
and self._exec_task.done()
and not self._exec_task.cancelled()
):
error = self._exec_task.exception()
if (
isinstance(error, NgFailureEvent)
and error.boundary == "sandbox"
and error.failure_kind == PROVIDER_OOM_KILLED
):
raise errorThe invariant is that confirmed sandbox-death evidence must not be replaced by inference from an absent receipt. This placement keeps a confirming receipt's capture path and a negative receipt's existing failure unchanged. Please verify the suggested code before adopting it.
Proposed regression: deliver an expiry with a short grace and block the receipt read until it starts. Complete the launch task with sandbox_oom(...), then let the read report missing evidence or time out. Assert that activation raises the same OOM event, execution_oom holds it, termination_error stays unset, capture is skipped, and close releases the dead sandbox without an in-sandbox cleanup command. Retain the same-event and owned/borrowed release assertions in test_confirmed_oom_during_supervised_execution_releases_dead_sandbox, plus the confirming-receipt transcript and negative-receipt failure assertions in the new grace tests. This is source reasoning, not an executed reproduction.
There was a problem hiding this comment.
Fixed in d2f5c2a. When the receipt read finds no receipt either way (missing, or the read times out) and the provider has meanwhile reported the command OOM-killed, _stop_overdue_harness() now returns instead of synthesizing harness_termination_unconfirmed. _await_exec() then raises the command's own PROVIDER_OOM_KILLED event, so execute() records it in execution_oom and close takes the dead-sandbox release path. A confirming receipt (capture) and a negative receipt (its own failure) are unchanged. I limited this to the confirmed OOM: any other outcome that arrives during the read keeps the existing unconfirmed-termination failure.
Regression: test_a_sandbox_oom_reported_during_the_overdue_receipt_read_stays_the_failure (owned and borrowed sandbox; receipt missing or read timing out). It checks that activation raises the same OOM event, that execution_oom holds it, that termination_error stays unset, that nothing is captured, and that close runs no in-sandbox command and stops (owned) or disconnects (borrowed) the sandbox. All 4 cases fail without the fix and pass with it.
There was a problem hiding this comment.
Verified at d2f5c2a. The four owned/borrowed × missing/timed-out receipt cases fail against the pre-fix implementation and pass at head. The same OOM event propagates, execution_oom is set, termination_error remains unset, and close performs no in-sandbox cleanup before the appropriate stop/disconnect. This addresses the reported race.
…ng receipt Once a stopped harness outlives its grace, the session reads the supervisor's receipt. If the provider reports the sandbox OOM-killed while that read is in flight, and the receipt is missing or the read times out, the session synthesized harness_termination_unconfirmed and released the command, discarding the OOM. The rollout then lost its confirmed-OOM attribution, and close tried in-sandbox cleanup on a dead sandbox instead of taking the dead-sandbox release path. A command that the provider reported OOM-killed during the read now returns to execute, which classifies the confirmed sandbox death as usual. A confirming receipt (capture) and a negative receipt (its own failure) are unchanged. Reported by the review bot on NVIDIA-NeMo#6452. Signed-off-by: gwarmstrong <[email protected]>
|
/ok to test d2f5c2a |
yuhezhang-ai
left a comment
There was a problem hiding this comment.
SHIP WITH CARE — one RISK and three non-blocking NOTEs inline. The confirmed-OOM race is addressed by d2f5c2a: all four regression cases fail against the pre-fix implementation and pass at head.
Validation performed during this review: 1,028 passed and 59 skipped on the exact head; scoped pre-commit passed. A clean local integration with main at 6227a1e passed 1,042 tests with 59 skipped, including sandbox-release tests. The queued-Local and late-receipt outcome probes still reproduce on that integration. No live benchmark/OpenSandbox rollout was run locally; Linux-only tests skipped on macOS.
Independent Codex and Claude Opus 5.5 source passes were consolidated with before/after reproductions. Claude delivered its report, but its execution audit remains incomplete after denied CPU-count diagnostics; the relevant focused tests and reproductions ran.
| delivered.cancel() | ||
| if not exec_task.done(): | ||
| grace = self._expiry_grace if self._expiry_grace is not None else grace | ||
| deadline = max(cast(float, self._expiry_delivered_at), launched_at) + grace |
There was a problem hiding this comment.
RISK (P2): Preserve stops before a queued Local launch
Could we preserve a pre-launch expiry while execution is queued for Local's shared slots, or explicitly document and test the new failure/retry outcome? launched_at is recorded before LocalProvider.exec() acquires its semaphore. With no grace override, a 3 s close timeout and a slot occupied for 35 s, head fails at 33 s with harness_termination_unconfirmed, while main returns expired_before_launch. Recovery retries that failure. Please distinguish queued submission from overdue supervisor cleanup while retaining the bound for an already running harness.
There was a problem hiding this comment.
Fixed in 661bae2. The session now tells a queued launch from an overdue supervisor by supervisor.pid, which the launch shell writes before it starts the supervisor (launch_queued() in supervisor_client.py). Once the stop is delivered, _await_exec() checks for the file. If it is missing, the provider has not run the launch: its supervisor will find the marker as it starts and end without starting the harness, so the session keeps waiting for the command, checking every grace. When it finds that the launch has run, the supervisor gets a whole grace from then. A harness already running at delivery keeps the bound from delivery. Only a missing file (FileNotFoundError) counts as queued; a read that fails otherwise or outlasts the close timeout counts as run, so a stalled sandbox still settles after the grace. The cost is one small file read per delivered stop.
Regressions: test_a_stop_while_local_queues_the_launch_ends_it_before_the_harness_starts holds the only slot of a real Local provider, stops before and after submission, keeps waiting past four graces, then grades expired_before_launch with the harness never started. test_a_launch_the_provider_runs_late_gets_a_whole_grace_from_then checks that a launch that runs late and then stalls still fails, but no sooner than a grace after it ran. Both fail on d2f5c2a.
There was a problem hiding this comment.
| self.cleanup = receipt | ||
| return | ||
| exec_task = self._exec_task | ||
| if self.termination_error is None and exec_task is not None and exec_task.done() and not exec_task.cancelled(): |
There was a problem hiding this comment.
NOTE (P3): Recheck the receipt after normal completion
Suggestion: if the command completed normally during an empty or timed-out receipt read, could we try one fresh, bounded receipt read before settling the termination failure? I reproduced successful command completion and a positive receipt arriving before the stale missing-file response returns. Head never checks again; main grades the stop. This narrower success case could preserve the result while still requiring positive cleanup evidence.
There was a problem hiding this comment.
Done in 661bae2. When the command returns a result during an empty or timed-out read, _stop_overdue_harness() reads the receipt once more within the close timeout. A confirming receipt grades the stop; a missing one still settles the termination failure, so the reread needs positive evidence like the first. A command that raised gets no reread (a confirmed OOM still returns as before). test_a_command_that_returns_during_the_overdue_receipt_read_gets_one_more_read covers both outcomes and fails on d2f5c2a.
There was a problem hiding this comment.
Verified both outcomes at 661bae2: the bounded reread preserves a confirmed stop, while missing evidence still fails without capture. The previous session code fails these regressions, and the OOM and negative-receipt cases remain green. Addressed.
| await session.close(timeout=1) | ||
|
|
||
|
|
||
| def test_the_default_stop_grace_is_the_supervisors_cleanup_bound(): |
There was a problem hiding this comment.
NOTE (P3): Exercise the default grace through execute
Could this verify the default through SandboxSession.execute(), leaving grace unset? This test checks helper arithmetic; replacing the runtime's default fallback with an unbounded wait still passes all 601 focused tests. Current behavior is correct, so this is non-blocking regression protection. A short cleanup-bound value supplied by the test would keep a behavioral check fast.
There was a problem hiding this comment.
Added test_a_stop_without_a_grace_waits_the_supervisors_cleanup_bound in 661bae2. It patches cleanup_bound to a short value, expires through execute() without grace, and checks that the activation fails within that bound, computed from the activation's own cleanup timeout. Replacing the default with an unbounded wait makes it fail. I kept the arithmetic test, which pins the default to the provider deadline's reserve.
There was a problem hiding this comment.
Verified the default through execute() with grace unset. The new test passes at 661bae2 and fails when only the runtime default is replaced with a 3,600-second wait. This closes the regression gap.
| Implement these hooks and nothing more: the Environment Server runs the episode. The [Environment Server compliance](https://github.com/NVIDIA-NeMo/Gym/blob/main/scripts/environment_server_compliance/README.md) check flags an agent that does not implement them, or that keeps parts of the earlier design in which the agent ran the whole episode itself. | ||
|
|
||
| The stop route ends a running harness exactly as at its time limit, so the episode is still verified and graded as a timeout. It is for a caller that enforces its own budget (agent time, tokens, cost) or for an operator; cancelling the `/run` request instead discards the rollout. An agent whose harness runs in a `SandboxSession` supports it by returning that session from `_rollout_sandbox_session()` and passing its response through `report_rollout_stop()`, as Codex does; other agents answer HTTP 501. The stopped run's response keeps the timeout's `incomplete` status, which `single_agent_turn` verifies, and its metadata gains `ng_rollout_stop`, a JSON object with the caller's `reason` (or `null`). That marker tells a stop apart from a timeout or a cancellation. A stop is not a failure, so the response carries no `ng_agent_outcome` failure kind, and a rollout that was stopped and graded is an ordinary result. The caller keeps awaiting its `/run` request, which returns the graded result once verification finishes. Harness runners see the timeout path, not a cancellation: they find no `stop.request` marker. `stopped: true` means the stop was accepted; the run can still finish on its own before the stop takes effect. `stopped` is false when the run already ended or a stop was already requested. An unknown or closed rollout answers HTTP 404, and a stop that arrives while the session is still seeding takes effect when the harness would launch. Stopping a running harness writes a file its supervisor watches for, so it needs a sandbox provider whose uploads never wait for the capacity running commands hold (`SupportsSandboxIndependentUploads`): Local, and OpenSandbox with `operations.background_exec: true`. On other providers, such as Docker, Apptainer, Enroot and OpenShell, whose uploads share the command limit, and OpenSandbox in foreground mode, a stop of a running harness answers HTTP 501; a stop before launch works on every provider. With several server workers the request needs no session cookie: the worker running the rollout claims its `/rollouts/<capture_key>` path, and the others forward the stop to it. A stop applies to the rollout's current agent session. An environment that opens a new session for each turn, such as Harbor's multi-step tasks, still schedules the later turns, and a stop sent between sessions finds no open session and answers HTTP 404. A caller enforcing a budget for the whole episode must also keep the environment from starting further turns once the current one is graded. | ||
| The stop route ends a running harness exactly as at its time limit, so the episode is still verified and graded as a timeout. It is for a caller that enforces its own budget (agent time, tokens, cost) or for an operator; cancelling the `/run` request instead discards the rollout. An agent whose harness runs in a `SandboxSession` supports it by returning that session from `_rollout_sandbox_session()` and passing its response through `report_rollout_stop()`, as Codex does; other agents answer HTTP 501. The stopped run's response keeps the timeout's `incomplete` status, which `single_agent_turn` verifies, and its metadata gains `ng_rollout_stop`, a JSON object with the caller's `reason` (or `null`). That marker tells a stop apart from a timeout or a cancellation. A stop is not a failure, so the response carries no `ng_agent_outcome` failure kind, and a rollout that was stopped and graded is an ordinary result. The caller keeps awaiting its `/run` request, which returns the graded result once verification finishes. Harness runners see the timeout path, not a cancellation: they find no `stop.request` marker. `stopped: true` means the stop was accepted; the run can still finish on its own before the stop takes effect. Once a stop reaches the harness, the agent waits for it only as long as its supervisor needs to end it: `rollout_stop_grace_seconds`, by default `session_close_timeout_seconds` plus 30 seconds. A harness still running then, as in a sandbox stalled by memory pressure, is no longer waited for. If the supervisor's receipt shows that it ended, the run is graded as a stop; otherwise the run fails with `harness_termination_unconfirmed`, and the sandbox is left to its owner's teardown. `stopped` is false when the run already ended or a stop was already requested. An unknown or closed rollout answers HTTP 404, and a stop that arrives while the session is still seeding takes effect when the harness would launch. Stopping a running harness writes a file its supervisor watches for, so it needs a sandbox provider whose uploads never wait for the capacity running commands hold (`SupportsSandboxIndependentUploads`): Local, and OpenSandbox with `operations.background_exec: true`. On other providers, such as Docker, Apptainer, Enroot and OpenShell, whose uploads share the command limit, and OpenSandbox in foreground mode, a stop of a running harness answers HTTP 501; a stop before launch works on every provider. With several server workers the request needs no session cookie: the worker running the rollout claims its `/rollouts/<capture_key>` path, and the others forward the stop to it. A stop applies to the rollout's current agent session. An environment that opens a new session for each turn, such as Harbor's multi-step tasks, still schedules the later turns, and a stop sent between sessions finds no open session and answers HTTP 404. A caller enforcing a budget for the whole episode must also keep the environment from starting further turns once the current one is graded. |
There was a problem hiding this comment.
NOTE (P3): Qualify the missing-evidence retry guidance
Could the lower retry sections at lines 630, 632 and 873, plus the SandboxSession docstring, call out the grace-expired exception? They say an absent receipt keeps retry state so a later close can confirm termination. After the new branch sets termination_error, close re-raises it without rereading the receipt. Distinguishing these cases would keep the adapter-author contract consistent.
There was a problem hiding this comment.
Updated in 661bae2. The guide's execute() and close steps and the "Missing or malformed evidence" bullet now say that a stop whose grace runs out settles the termination failure, which close handles like a final negative receipt without reading the receipt again. The SandboxSession and expire() docstrings say the same, and the stop paragraph covers the queued launch.
There was a problem hiding this comment.
Checked the guide and both docstrings against the code at 661bae2. They now distinguish retryable missing evidence from the terminal grace-expired case and explain queued launches. Addressed.
…stop Local runs a bounded number of commands and queues the rest, so a stop can reach a launch that has not run yet. Its supervisor will find the expiry marker as it starts and end without starting the harness, but the session counted the stop grace from submission and failed the rollout with harness_termination_unconfirmed once the grace ran out. The session now checks supervisor.pid, which the launch shell writes before it starts the supervisor. While the file is missing, the session keeps waiting, checking every grace; once the launch has run, the supervisor gets a whole grace. A harness already running when the stop arrives keeps the bound from delivery. A command that returns while the overdue receipt is being read gets one more bounded read, since its supervisor writes the receipt before it exits. Also exercise the default grace through execute(), and say in the harness guide and the SandboxSession docstrings that close does not retry an expiry whose grace ran out. Signed-off-by: gwarmstrong <[email protected]>
|
/ok to test 661bae2 |
|
Thanks for the updates, @gwarmstrong. I'm rechecking the fixes. Could you also resolve the current merge conflicts with main? |
yuhezhang-ai
left a comment
There was a problem hiding this comment.
SHIP for the source reviewed at 661bae2 — all four follow-up points are addressed, with no new actionable finding in the d2f5c2a → 661bae2 delta.
Rechecked queued Local launches, the bounded receipt reread, runtime default-grace coverage, and retry documentation. The original confirmed-OOM regression remains green.
Validation: 605 passed, 17 skipped on macOS across the sandbox-session, supervisor, agent-session, routing, and Codex-session suites. Both real Local queued-launch probes passed. The previous-code controls reproduce the queued-launch and reread failures, and the default-grace test catches a 3,600-second runtime fallback. Scoped Ruff lint/format and diff checks passed. Full Linux process-supervision tests and a live OpenSandbox/model rollout were not rerun locally. This follow-up used Codex review and local checks; no fresh Claude pass ran.
Scope: reviewed this commit against its own merge base, 155b27d. The current merge-conflict resolution is outside this assessment. Leaving this as a comment review until the resolved head has been checked.
What does this PR do?
This follows up #5145 (rollout stop). A rollout stop only writes the supervisor's
expire.requestmarker and returns. The activation then waits on the supervised command until the provider's execution deadline, which is the agent timeout plus the cleanup reserve. When memory pressure stalls the sandbox, the supervisor never acts on the marker, and Gym keeps polling the command for hours. In a TB-Science run, a Codex rollout was stopped at its 8 h budget and came back 292 minutes later. Its model replicas were held the whole time.With this change, once the expiry marker is in the sandbox, the activation waits for the command only as long as the supervisor's own cleanup bound. That bound is the supervisor's three cleanup phases plus 30 s:
session_close_timeout_secondsplus 30 s, which is 90 s by default and 330 s for TB-Science. It is the same reserve the provider deadline keeps after the harness timeout. An agent can setrollout_stop_grace_secondsto use a different value. Once the bound passes, the session logs one warning that names the rollout. It then reads the supervisor's receipt within the close timeout. It does not send a stop request, because a stop request would turn the expiry into a cancellation if the supervisor resumed.execution_oom), and close takes the dead-sandbox release path.harness_termination_unconfirmed, stops polling the command and raises the failure, so the rollout fails cleanly instead of hanging. Close works as for a negative receipt: it releases a borrowed sandbox for the Resources Server's teardown, or stops an owned one, without reading the receipt again.A launch that the provider has not run yet is not an overdue supervisor. Local runs a bounded number of commands and queues the rest, so a stop can reach a launch still waiting for a slot. Its supervisor will find the marker as it starts and end without starting the harness, so the session waits for it. The session tells the two apart by
supervisor.pid, which the launch shell writes before it starts the supervisor. While the file is missing, the session keeps waiting, checking every grace. Once the launch has run, the supervisor gets a whole grace from then. A harness that is already running when the stop arrives keeps the bound from delivery. Only a missing file counts as queued; a read that fails otherwise or times out counts as run, so a stalled sandbox still settles after the grace.Changes:
supervisor_client:cleanup_bound()is split out ofexec_timeout(). The newread_cleanup_receipt()reads the receipt without asking anything of the supervisor.stop_and_confirm_cleanupnow uses it, and its behavior is unchanged. The newlaunch_queued()reports whethersupervisor.pidis missing.SandboxSession:expire()takes an optionalgrace. New_await_exec()waits for the command with that bound once an expiry is delivered, and waits on a queued launch. New_stop_overdue_harness()settles a harness that outlives the bound.BaseResponsesAPIAgentConfig.rollout_stop_grace_secondsis optional. Unset means the cleanup bound. It is passed toexpire()both from the stop route and for a stop that arrives during the seed.HARNESS_TERMINATION_UNCONFIRMEDcomment now covers the new cause. The harness guide (add-or-update-a-harness.mdx) documents the bound and the queued launch, and says that close does not retry a stop whose grace ran out.graceargument.No issue was filed. The failure is the TB-Science run described above.
Validation
All runs are on upstream
mainat 155b27d plus this branch, at 661bae2:pytest tests/unit_tests/agents tests/unit_tests/server_runtime/test_session_routing.py: 745 passed, 2 skipped.pytest responses_api_agents/codex_agent/tests tests/unit_tests/core: 1257 passed, 6 skipped and 1 failed. The failure istest_opensandbox_sdk_is_available_in_agent_environment, which checks the Codex agent's own venv for the OpenSandbox SDK. It fails because I ran from the root venv. It is unrelated to this change.expire()(Codex, Kilo Code, OpenCode, OpenClaw, Droid, OpenHands, Pool, Goose, Prime, Kimi Code and Cline): 421 passed, 1 skipped.pytest tests/unit_tests: 23,890 passed, 124 failed and 9 errors. The failures and errors are missing optional packages in my local venv (opensandbox,mlflow,tenacity,PIL). The same files give the same 124 failures and 9 errors with this branch's two session modules reverted.pre-commit run --files <the 9 changed files>: all hooks pass.supervisor_client.py: 23/23.sandbox_session.py: 75/77 (97.6% for the whole file). The 2 missed lines are the warning logged when releasing the overdue command itself fails.test_sandbox_session.py:gracewaits the supervisor's cleanup bound throughexecute(), and the default grace is the provider deadline's reserve.test_sandbox_sessions.py: a stalled Codex rollout fails cleanly after the grace, and one whose command status hangs is still graded.Rollouts
This was a TB-Science smoke with the Codex agent on OpenSandbox, run locally through the EFB runner against a multiplexer. It used Gym a631623d4a, which is this fix plus unrelated branch work, before the rebase onto
main. It ran 2 tasks withsession_close_timeout_seconds: 300.One rollout's sandbox processes were frozen with SIGSTOP (the supervisor, runner, node and codex), and the rollout was then stopped:
the Codex harness did not end within 330 s of its stop; no longer waiting for its command.harness_termination_unconfirmed(it did not end within 330 s of its stop, and no receipt confirms that it ended).Without the fix, the same stall kept the rollout until the provider deadline, 292 minutes after the stop in the original run.
The review fixes (the OOM during the receipt read, the re-read and the queued launch) came after this smoke. Unit tests cover them, including a real Local provider for the queued launch. The smoke's path, a running harness whose supervisor is frozen, is unchanged by them.
Compatibility and benchmark impact
rollout_stop_grace_seconds. Leaving it unset gives the cleanup bound. Existing configs need no change.harness_termination_unconfirmedand no longer waits until the provider deadline. A supervisor that works as designed ends its harness within the bound, so those results do not change. A stop that reaches a launch the provider has not run yet is graded as expired before launch, as onmain. Runs that do not use the stop route are not affected.supervisor.pid, a small file.SandboxSession.expire()takes a new optional keyword,grace. Test doubles that replaceexpiremust accept it, as the routing tests' fake now does.Checklist
pre-commit run --all-files) (so CI lint/format checks pass). Run on the changed files only; see Validation.git commit -s) (so the DCO check passes).