Repository navigation
fix(deepswe): score confirmed agent sandbox OOMs as zero - #4685
mpatel31415 wants to merge 16 commits into
Conversation
Signed-off-by: Martyna Patelka <[email protected]>
|
Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually. Contributors can view more details about this message here. |
giuliolovisotto
left a comment
There was a problem hiding this comment.
This fixes a real issue: an agent-execution OOM shouldn’t silently remove the task from the scoring denominator.
Could we reuse SandboxObservation for the retained evidence instead of adding agent_sandbox_oom_killed? It already supports role="agent", outcome="oom", provider and sandbox ID. We need to preserve the distinction between setup and agent execution—potentially with a phase field.
The typed SandboxOOMKilledError is useful for catching confirmed OOMs; that serves a different purpose from the saved observation. Ideally it belongs to the shared sandbox interface, so the harness and benchmark don’t import an OpenSandbox-specific exception.
Keep the zero-score decision in DeepSWE. The harness should report what happened; the benchmark decides how that affects scoring.
Before merging, please run the focused tests on current main and a representative smoke that triggers an actual OOM, confirming the task remains in the denominator with reward zero and its sandbox evidence retained.
| @dataclass(frozen=True) | ||
| class _SandboxDeathNotice: | ||
| message: str | ||
| oom_killed: bool |
There was a problem hiding this comment.
Would there be more states here other than oom_killed?
There was a problem hiding this comment.
Yes. The death notice now has explicit oom and other_terminal outcomes. Only an explicit terminal OOM reason, or an authenticated inspect result confirming the current user container was OOMKilled, takes the typed OOM path. Other terminal states retain the original failure.
|
Could we clarify coverage across the three execution paths: local |
Signed-off-by: Martyna Patelka <[email protected]>
|
Addressed the review comments in
The PR remains Draft because Gym's contributor guidance still calls for a representative model-backed rollout. The OpenSandbox inspect route used to distinguish the real K8s OOM is deprecated in 1.1.0; classification fails closed when it is unavailable. No historical 112/113 result has been relabeled. |
Signed-off-by: Martyna Patelka <[email protected]>
Signed-off-by: Martyna Patelka <[email protected]>
Signed-off-by: Martyna Patelka <[email protected]>
9c9d4ac to
b62eb7f
Compare
Signed-off-by: Martyna Patelka <[email protected]>
Signed-off-by: Martyna Patelka <[email protected]>
hemildesai
left a comment
There was a problem hiding this comment.
Review from the nemo_gym.sandbox code owners, covering only the files under nemo_gym/sandbox/. Main asks: fix the base classes of the new exceptions and document when they're raised, keep the old OOM match for PTY diagnostics, and drop the new AsyncSandbox properties. The comments on behavior change, inspect, and the double OOM check are smaller and could be follow-ups.
| """The sandbox backend became unreachable while submitting or running a command.""" | ||
|
|
||
|
|
||
| class SandboxCommandStatusTimeoutError(TimeoutError): |
There was a problem hiding this comment.
SandboxCommandStatusTimeoutError should not subclass TimeoutError. Callers already catch TimeoutError to mean "the command ran past timeout_s". With this base class, losing the command's status looks the same as a command that ran too long. DeepSWE's _run_verifier already needed a re-raise workaround, and any other resources server that catches TimeoutError around exec will turn lost status into a score. Suggest a neutral base, for example SandboxLostError(RuntimeError), with this class under it.
| """Status reads for an already-submitted command exhausted its deadline.""" | ||
|
|
||
|
|
||
| class SandboxOOMKilledError(SandboxBackendUnreachableError): |
There was a problem hiding this comment.
SandboxOOMKilledError should not subclass SandboxBackendUnreachableError. An OOM kill is a confirmed fact about the sandbox; "backend unreachable" means we lost contact. As written, except SandboxBackendUnreachableError also catches OOMs, so the order of except blocks decides the outcome. Please make them siblings under the same neutral base suggested above.
| """Raised when a newly-created sandbox fails provider readiness checks.""" | ||
|
|
||
|
|
||
| class SandboxBackendUnreachableError(RuntimeError): |
There was a problem hiding this comment.
These exceptions are now part of the provider-neutral API but have no documented contract. Only OpenSandbox raises them, and the provider contract says process exits come back as SandboxExecResult. Please document when a provider must raise each one instead, especially what evidence is enough for SandboxOOMKilledError, and that Docker, Daytona, and E2B don't raise them today. The places to update are the Error Handling section of fern/.../sandbox/index.mdx and adding-a-provider.mdx.
| self.pty = SandboxPty(self) | ||
|
|
||
| @property | ||
| def sandbox_id(self) -> str | None: |
There was a problem hiding this comment.
Please drop sandbox_id and provider_name from AsyncSandbox. We want to keep the public facade to methods only; these would be its first properties, and the sync Sandbox facade doesn't get them. Callers already have both values:
- borrowed sandbox (the DeepSWE case):
sandbox_access.connection.descriptor["sandbox_id"]andconnection.provider_config_ref, asopencode_agentused before this PR; - owned sandbox:
self.config.sandbox_provider, plusawait sandbox.serialize()for the ID.
If the OOM path needs the ID at the point of failure, have the provider set it on the error, for example SandboxOOMKilledError(message, sandbox_id=handle.sandbox_id). The provider has the handle when it raises. This also removes the need to save the ID before stop() clears it.
| if ( | ||
| terminal | ||
| and isinstance(reason, str) | ||
| and re.fullmatch(r"oom[\s_-]*killed", reason.strip(), re.IGNORECASE) |
There was a problem hiding this comment.
This misses OOMs that the old check caught. Before, it searched both reason and message for "oom killed" or "out of memory", in any state. Now it needs a terminal state and reason exactly equal to OOMKilled, yet the PR description says real K8s OOMs show up as ContainerFailed. The PTY diagnose callbacks and the attach-takeover path still go through _oom_death_notice without the new inspect fallback. So a PTY session that dies from OOM is now reported as just "Sandbox is dead". Please keep the old message match for these diagnostic notices, or run the inspect fallback there too.
| status_code = _exception_status_code(error) | ||
| if not isinstance( | ||
| error, (SandboxBackendUnreachableError, SandboxCommandStatusTimeoutError) | ||
| ) and status_code not in {410, 502}: |
There was a problem hiding this comment.
This changes behavior for every OpenSandbox user, not only opted-in runs. report_agent_sandbox_oom and score_agent_sandbox_oom_as_zero only control the agent and DeepSWE. These provider changes are always on:
- 410 and 502 errors now raise
SandboxBackendUnreachableErrorinstead of the original SDK error; - background exec gets a 5-minute status-recovery window;
- every such failure triggers an extra inspect request.
The recovery window is probably a good change, but please list all three in the PR's compatibility notes, or put the inspect step behind a provider option.
| return f"Sandbox was OOM-killed: inspect confirms {evidence}. {message}" | ||
| return None | ||
|
|
||
| async def _control_plane_inspect_oom_evidence(self, handle: SandboxHandle) -> str | None: |
There was a problem hiding this comment.
This relies on a deprecated plain-text route and has no switch to turn it off. SDK 0.1.15 has no inspect call, so building the request by hand is understandable. The auth header and use of server_utils.request match what the SDK and Gym already do. Still, the result comes from parsing deprecated text with regexes, and the PR description says deployments need a compatibility check first. Please:
- add a provider option, for example
diagnostics.inspect_oom: bool; - put a comment by
_inspect_oom_evidencenaming the OpenSandbox version whose output format it expects; - log at debug level when parsing falls back to "no evidence", so a format change doesn't fail silently.
| error, (SandboxBackendUnreachableError, SandboxCommandStatusTimeoutError) | ||
| ) and status_code not in {410, 502}: | ||
| raise | ||
| if evidence := await self._confirmed_oom_death(handle, error): |
There was a problem hiding this comment.
The OOM check runs twice for one failure. _exec_background already calls _confirmed_oom_death on each failed status read (L2005). That polls get_info for up to 5 seconds and makes a 2-second inspect call. When the loop then raises SandboxCommandStatusTimeoutError, this handler runs the same check again. That's up to about 7 extra seconds and a second inspect request per failure. Please skip the re-check when the error came from the background loop.
Signed-off-by: Martyna Patelka <[email protected]>
…om-zero-main Signed-off-by: Martyna Patelka <[email protected]> # Conflicts: # nemo_gym/agent_utils/sandbox_session.py # nemo_gym/rollout_observability.py # nemo_gym/sandbox/providers/opensandbox/provider.py # responses_api_agents/opencode_agent/app.py # tests/unit_tests/test_opensandbox_provider.py # tests/unit_tests/test_rollout_collection.py
Signed-off-by: Martyna Patelka <[email protected]>
Signed-off-by: Martyna Patelka <[email protected]>
Signed-off-by: Martyna Patelka <[email protected]>
Signed-off-by: Martyna Patelka <[email protected]>
Signed-off-by: Martyna Patelka <[email protected]>
giuliolovisotto
left a comment
There was a problem hiding this comment.
Could you split this into three PRs, stacked if useful?
- Sandbox provider changes.
- OpenCode harness changes.
- DeepSWE changes.
This will let us review the provider failure contracts, harness handling and reporting, and DeepSWE verification and scoring separately.
Superseded by three focused draft PRs (2026-10-27)
This combined PR has been split into a stack, following the requested review boundaries:
main).All 24 changed files and original hunks from
2629a3b9aa1c28d56ee4ef5c72750da449527aa8are accounted for, rebased onto main0729e02ca. Local validation across the three layers passed 1,566 tests with 50 skips; pre-commit passed for each layer. The new descriptions record per-layer validation and remaining model-backed smoke/full-CI work. #4781 remains an open overlapping temporary alternative and was not changed.This PR is closed as superseded, with its branch and review discussion retained. The historical description and evidence below apply only to the original heads named there; they are not current-stack validation.
Current head and remaining validation (2026-10-22)
The draft PR now points to signed-off
79901c5761df43645056f7b5a482cfbc34c4d271, on current Gym main92407083ba1a8373b96ae660cbd4404cd874169c. It remains open, mergeable and review-required. Its new commits afterf75026cdafail closed on missing or invalid OpenCode transcript exports, unknown foreground/background provider command outcomes, deleted primary OpenCode logs, and incomplete non-OOM DeepSWE verification. Agent git setup now checks its status; the verifier requires an explicit binary reward, parseable CTRF and a successful command. A confirmed current agent-sandbox OOM remains the sole incomplete unmasked zero, with matching seeded-sandbox evidence. A captured agent time-limit failure still follows the frozen zero-scoring contract.The combined affected OpenSandbox provider, OpenCode agent and DeepSWE suite passed 326 tests on this exact head. Each changed test was reviewed with the repository's test-quality workflow, and
pre-commit run --all-filespassed. The push has queued basic checks; current-head full CI and model-backed rollout validation are still absent. This PR is not release-ready. The historical validation details below refer to earlier immutable heads unless stated otherwise.A separate DeepSeek FP4 exploratory full run on old Gym e76 ended at 101 valid graded main rows and 12 ungraded sidecars: ten pre-agent ripgrep
write_filetimeouts and two agent-sandbox OOM kills. It has no release score or certificate and does not validate this PR head. Its outcomes cannot be selectively relabeled, resumed without its lost ExecDB, or mixed with another invocation.Before using this head for a release, validate a fresh exact-pin model-backed DeepSWE smoke and a complete 113-task run. Audit 113 distinct canonical main keys with no duplicates or sidecars. Each row must either have
evaluation_completed=True, successful verifier and reward artifact, or be a zero withfailure_kind=provider_oom_killedand matching current agent-sandbox OOM evidence. Gym's generic completion check counts keys without inspecting these semantics; Evergreen's aggregate health gate does not distinguish a confirmed OOM from another unobserved row. Downstream Kimi and GLM DeepSWE cells also need new complete runs and certificates on the final shared Gym pin and frozen benchmark before a 0.5.2 release can combine them with DeepSeek.What changed
No separate Gym issue was filed: this focused PR records the confirmed DeepSWE agent-sandbox OOM and Ultra ripgrep-upload failures, their failure evidence, and the opt-in recovery. The related EFB follow-up issue #9 tracks the earlier missing-ripgrep exposure and possible score impact.
A confirmed OOM kill of the agent's sandbox during agent execution now becomes a visible, unmasked DeepSWE reward-zero row when the recipe opts in. The agent records a structured
SandboxObservationwith provider, sandbox ID, execution phase, outcome, exception type, and reason; DeepSWE checks it against the seeded sandbox and decides the score. Setup failures, generic transport errors, verifier/patch-collection OOMs, and golden runs keep their existing failure behavior.The two sandboxed OpenCode paths are covered: legacy
opencode_sandboxed_agentandopencode_agentusing sandboxed agent sessions. Localopencode_agenthas no sandbox OOM to classify. The typed OOM exception is shared through the sandbox interface. The DeepSWE recipe opts in withreport_agent_sandbox_oomandscore_agent_sandbox_oom_as_zero; both settings default to false elsewhere.On OpenSandbox K8s, a real OOM can surface through the lifecycle API only as
ContainerFailedafter exec returns 502. In that terminal state, Gym also checks the authenticated control-plane inspect response for the current user container's explicitreason=OOMKilled. Exit 137 alone, historical container state, and sidecar/init container state are insufficient. If inspection is unavailable or ambiguous, classification fails closed to the original error. OpenSandbox 1.1.0 exposes this as a deprecated plain-text route, so deployment compatibility must be checked before using this policy.Ultra job 1016011 exposed another path: status reads for an already-submitted agent command timed out, the backend returned 502, and a later request returned 410
SANDBOX::ENDEDwith the current sandbox's OOM. The status-recovery changes keep polling the same execution ID, without resubmitting the command, for a bounded five-minute recovery window. They inspect the current user container after persistent status timeouts or 502/410 and require affirmative OOM evidence before producing a zero. A lagging genericContainerFaileddoes not prematurely end that recovery window. Unconfirmed backend loss and expired status recovery propagate as failures, including during patch collection and verification.This supports DeepSWE evaluation runs that previously stopped at 112 of 113 tasks. Existing historical results are unchanged; a new pinned Gym version and fresh run are needed to produce a complete 113-row result.
The Ultra JHB run also exposed intermittent 300-second timeouts while uploading the checksum-pinned local
rgbinary into agent sandboxes, before OpenCode started. The sandboxed OpenCode agent now limits these uploads to two at a time per worker and retries a timed-out upload once, after a 15–30-second delay, at a fresh remote path. Other upload errors still fail closed. The setup command uses only the successful path. This is a separate infrastructure recovery; an upload timeout is never scored as an agent OOM or task zero.Validation
06f5f8966a25a545b20b81116a414b6782e540b3before the17ad70ad7checks; a later main merge advanced this PR to489c2b3d2452a5166323796ba519cfa228c9b88e. That merge changes token-capture and dependency files, with no DeepSWE, OpenCode, sandbox, provider, or verifier file changes. Focused provider, sandbox, agent-path, DeepSWE, and rollout-collection tests: 953 passed, 4 skipped.pre-commit run --all-filespassed on the17ad70ad7code commit before the main merge; commit hooks passed and all commits have DCO sign-off. The full DeepSWE test file passed 27 tests after the verifier-status fix; Ruff check, Ruff format, andgit diff --checkpassed.OOMKilledand exit 137. Gym's legacy agent path emittedSandboxOOMKilledErrorwith the current sandbox ID andphase=agent_execution; DeepSWE returnedreward=0,mask_sample=false, andfailure_kind=provider_oom_killedwithout patch collection. The smoke harness wrote that response to the main rollout JSONL and invoked Gym's aggregate calculation. The main JSONL contained 1 row, the failures sidecar 0 rows, and the aggregate reportednum_repeats=1,expected_num_rollouts=1,missing_num_rollouts=0, andmean/reward=0.Saved, sanitized excerpts from that K3s smoke (local user, node, IP, and sandbox ID omitted):
The raw smoke artifacts remain with the author for inspection; this PR contains no committed evidence file. The task and CLI were synthetic: the Pod OOM and Gym agent, verifier, and aggregate paths were real, but this was not model inference or a 113-task benchmark result.
Focused tests also cover the sandboxed agent-session path, local-path behavior, non-OOM terminal failures, ambiguous inspect evidence, setup failures, and the aggregate denominator.
The Ultra-sequence regression tests cover status timeout → 502 → 410, one command submission and one execution ID, affirmative current-container OOM evidence, rejection of sidecar-only OOM evidence, generic
ContainerFailedbefore later OOM confirmation, and a recovery timeout shorter than the three-hour agent command. Affected agent/DeepSWE tests: 90 passed, 2 skipped; provider tests available in the local borrowed environment: 119 passed, 1 skipped. Thirteen additional provider tests could not run locally because that environment lacks the OpenSandbox SDK. For the latest status-recovery code, the 28 focused background-execution and status-recovery provider tests passed, as did 90 agent/DeepSWE tests with 2 skipped; scoped pre-commit passed. JHB replay of the original task-5 timeout → 502 → 410 sequence on Gym9c9d4ac9confirmed that a current user-container OOM produces one unmasked reward-zero main row and zero sidecar rows; an unconfirmed backend loss remained an unscored failure.A final-diff review found that the provider's
SandboxCommandStatusTimeoutErrorsubclassesTimeoutError. DeepSWE previously caught it as an ordinary verifier execution timeout and returned reward zero if OpenSandbox lost status while running the verifier. At17ad70ad7,_run_verifiernow re-raises that provider status-loss error before the ordinary timeout handler. Two tests exercise the real method: status loss propagates unscored, while a genuine verifier execution timeout retains its reward-zero behavior. The corrected17ad70ad7code commit has a fresh model-backed smoke below. Full repository CI completed: unit and server shards passed, while harness conformance P0 failed with the same probe failures seen on Gym main run 38899092121 and main run 38915541449. The PR-specific Guardwords description check was fixed and rerun successfully. Maintainer review remains pending.The new
rgstaging tests cover a first timeout followed by success at a different path, exhausted timeouts with no agent execution, permanent errors that fail immediately, cleanup, and a two-upload concurrency limit per agent instance. The full sandboxed OpenCode test file passed 68 tests, 2 skipped; scoped pre-commit passed. The SWE-bench sanity assertion was updated to check stable observation fields after the new optional OOM fields; its focused test passed. A JHB stress test on exact Gymd4209f590staged, installed, and checksum-verified the 5.4 MB ripgrep binary in 32/32 real Ultra task-image sandboxes using four agent instances and two uploads per instance, with zero timeouts or retries. It had no model traffic and did not exercise the retry. The earlier full Ultra run 1048053 was cancelled after recurrent pre-agentrgupload timeouts; its partial rows are diagnostic only.A fresh model-backed one-task Ultra smoke on Gym
d4209f590(Slurm 1049862) completed 0:0 in 26:02. OpenCode made two glob and eleven grep calls with real matches, no ripgrep execution failures or download, and the checksum pre-command passed. DeepSWE produced one unmasked main row, zero failure-sidecar rows, and a normal reward-zero miss with a positive 22,088-byte patch; MLflow export completed. No upload timeout or retry occurred, and the new upload-attempt log lines did not reach the run logs. This is representative model and verifier evidence for the priord4209f590head. It predates the narrow verifier status-loss fix at17ad70ad7, does not exercise the upload retry, and is not a 113-task benchmark score.On exact EFB
093bc323and Gym17ad70ad7, a fresh one-task model-backed Ultra smoke (Slurm 1050663, invocation9eab55c56a9f2c0a) completed 0:0 in 24:56; MLflow export completed. The runtime checkout resolved the full17ad70ad7e8c7f9144ba0e5eea7abeb5b2c7e909commit and the local ripgrep checksum pre-command passed. OpenCode made 14 grep calls with no ripgrep execution failures, download, upload timeout, or write-file error. DeepSWE produced one unmasked graded main row, zero sidecar rows, and a normal reward-zero miss with a 15,438-byte patch; the verifier completed normally with exit 0 and no verifier error. No provider status loss occurred, so the new fail-closed exception path is covered by the real-method regression tests rather than this smoke. This is not a 113-task benchmark score.A separate three-task model-backed GLM-5.3-Flash run on Gym
78a88f4a(invocationaf03933275fef0ed, Slurm1046802) completed 0:0 in 35 minutes. Real model inference, OpenCode actions, and DeepSWE verification produced three main rows, zero failure-sidecar rows, and three healthy reward-1.0 verdicts; no OOM occurred. The run was isolated from fn100sprint. It validates the original code path. A later one-task model-backed Ultra smoke on Gym9c9d4ac9completed with working OpenCode glob/grep, one graded main row, and zero sidecars, but predates the new upload retry. The pinned17ad70ad7commit has a real model-backed Ultra smoke and the prior staging stress. A later main merge advanced the PR to489c2b3d, and the sandbox code-owner fixes advanced it tobe04db10538aa6ee026d33101dabcaf541612a0c. The489c2b3dfull CI passed unit/server/build checks but retained the baseline harness P0 failures. Prior-head CI onbe04db105completed: core unit tests and all eight server shards passed, while harness conformance P0 failed with the same opencode/pi/codex probe signatures seen on the earlier489c2b3dhead and recent Gym main runs. Maintainer review remains pending. The Ultra full run stayed pinned to17ad70ad7. Slurm segment 1051913 was PREEMPTED after 4h08m35s; same-invocation automatic successor 1052002 completed 0:0 in 13m29s, and guard 1056306 was cancelled. The terminal audit found 113 distinct unmasked main keys and zero sidecars after resume; 1052002 wrote no new rows. Four rows haveevaluation_completed=False: tasks 27 and 70 are confirmed agent-sandbox OOMKilled zeros, while task 62 failed host-side verifier staging (tests/test.shmissing) and task 81's verifier was killed after 1826.8 seconds withoutreward.json. The latter two were never graded. Export 1056482 completed and MLflow recorded the diagnostic aggregate, but 4 solved / 113 and mean 0.0354 are not a release score. All five first-attempt ripgrep upload timeouts recovered on retry, and no provider I/O timeout was found. Pinned Gym17adcheck_completioncounts unique non-sidecar keys without checkingevaluation_completed, so this invocation cannot certify even though Slurm and export succeeded. It is exploratory evidence for that immutable code, not validation ofbe04db105.be04db10538aa6ee026d33101dabcaf541612a0c: status loss, backend loss, confirmed OOM, and provider SDK I/O timeout are siblingSandboxLostErrorfailures, separate from genuine command execution timeouts. This prevents ambiguous submit/log/file/session or hard-cap failures from becoming verifier zeros. DeepSWE and OpenCode propagate these losses; the ripgrep upload retains its bounded fresh-path timeout retry. The public sandbox contract and OpenSandbox compatibility docs were updated, the extraAsyncSandboxproperties removed, and PTY OOM diagnostics kept conservative. A real-method verifier regression covers a completed command followed by log-read timeout. The combined affected suite passed 538 tests, 12 skipped before integration with main; after rebase onto489c2b3d, the focused provider/sandbox/DeepSWE/OpenCode suite passed 446 tests, 4 skipped, and repository-wide pre-commit passed. No model-backed smoke has yet run onbe04db105; its core/server/build checks passed, while baseline-matching harness P0 remains red.Compatibility and metric impact
The settings are opt-in. A confirmed agent-execution sandbox OOM is a zero-score task in the normal denominator with retained evidence. A missing or uncertain OOM classification is never silently converted to zero.