Repository navigation
feat(environment): finish every Environment Server's running cleanups at shutdown - #5348
Conversation
|
/ok to test ee6e898 |
ee6e898 to
5c09460
Compare
|
/ok to test 5c09460 |
5c09460 to
f5e15f4
Compare
|
/ok to test f5e15f4 |
f5e15f4 to
fecbdb2
Compare
|
/ok to test 2124b51 |
…thin one budget Review of #5348: - The shutdown sweep runs each cleanup under its episode's rollout, so a Resources Server close carries the attempt's capture key, as in the normal unwind. - The sweep starts every unfinished cleanup at once and waits cleanup_timeout_seconds in all, as the agent servers' shutdown drain does. A sandbox stop no longer waits behind an agent-session close that retries an agent that is shutting down too. The sweep logs each episode whose cleanup it could not confirm. - An episode whose cleanup failed when it ended stays tracked, so the sweep tries the cleanup again instead of leaving the sandbox to its TTL. - A subclass that overrides run is refused when it is defined, also when it defines run_episode too, because overriding run skips the tracking. - A tool that raises a handled episode failure (such as a crashed sandbox) fails the episode with it when run_episode returns. Before, the failure became a 500 for the model and the episode was graded as the agent's failure. - A test runs uvicorn's order: one cancellation, then the lifespan exit while the request's own cleanup still stops the sandbox. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Felipe Vieira Frujeri <[email protected]>
2124b51 to
52eb857
Compare
|
/ok to test 52eb857 |
|
/ok to test ebec917 |
|
/ok to test e8f6300 |
|
/review reset=True |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP WITH CARE — two RISKs: the concurrent sweep breaks SWE-Together's cleanup dependencies, and model-backed smoke evidence is missing for the changed episode behavior.
I inspected all five changed files and traced cleanup serialization, cancellation, lifespan ordering, checkpoint attribution, concrete environment callers, and handled tool failures. The earlier rollout-context finding is fixed: the sweep restores each episode's capture key, with coverage for concurrent episode attempts.
This was a static review. I didn't execute tests or independently verify the PR's reported validation results.
Inline comments (escaped v1):
-
environment_servers/swe_together/app.pyline 207: RISK — Preserve SWE-Together's cleanup dependencies during the concurrent sweepExit the lifespan while normal unwind is awaiting a candidate or judge sandbox stop. The new sweep starts the runtime cleanup concurrently with those stops. This branch sees a non-
Nonesandbox and returns without releasing its bundle;_CleanupEntry.closethen marks it complete. When the stops clear the fields, normal unwind skips the completed runtime entry. The outer lifespan subsequently calls RuntimeProvisioner.close, which raisesRuntime bundles remain owned by task sandboxesbefore stopping the helper. Thus workload stops can succeed while the bundle and helper remain owned and lifespan shutdown fails.Could
release_runtimewait for its prerequisites rather than count a skipped release as success? Suggested replacement at this function, subject to author verification:async def release_runtime() -> None: if state.runtime is not None: await judge_cleanup.close() await candidate_cleanup.close() await state.runtime.release(state.session_id)
Both handles are assigned before the protocol's first await. Their existing locks serialize overlapping closes, completed stops remain skipped, and a failed stop leaves this cleanup retryable. This preserves the normal successful sequence without putting independent sandbox stops behind a hanging agent close.
The same ordering change also requires a dependent correction to persist_cleanup_evidence: it is registered to run after participant callbacks, but the sweep now runs it independently. With delayed stops or agent close, it writes
cleanup-receipts.jsonand any saved failure before their final receipts arrive, then becomes inactive. Make evidence persistence wait for the participant attempts to settle, including failed attempts, while retaining concurrent releases and the shared shutdown budget. That finalizer/deadline integration needs care; the runtime replacement alone doesn't fix stale evidence.Proposed acceptance checks: Use the real SWE-Together callbacks with an owned runtime bundle and delayed sandbox stops. Cancel the episode once, enter lifespan shutdown while a stop is in progress, and assert both stops precede bundle release, the bundle disappears, the helper stops, and lifespan exit succeeds. Delay agent close too and assert the aggregate receipt file and saved failure match the final participant receipts. If a stop fails, retain bundle ownership until a successful retry; don't report release as complete. Retain the existing runtime ownership guard, once-only successful stops, and the hanging-agent-close protection. These checks weren't executed in this review.
-
nemo_gym/server_runtime/base_environment_server.pyline 382: RISK — Provide representative model-backed smoke evidenceThe PR's rollout-evidence justification says episode results don't change, but this check now replaces a returned result with a handled tool failure. The new crash test exercises that behavior through an in-process agent callback, not a real Agent Server/model. The supplied validation lists unit tests and mutations only. The protected repository guidance requires representative real smoke rollouts for behavior-changing environment work; the review rubric treats missing required evidence as a RISK.
Could you run and record a model-backed smoke for this path and update the N/A justification? A minimal proposed setup is a tool-serving environment paired with a supported Agent Server/model, with an
executetool that raiseshandled_episode_failure(terminal=False, failure_reason="sandbox crashed"). Prompt the model to invoke it and inspect the tool reply and final episode response: the agent should see the failed call, and/runshould return no result and a retryable episode failure with that reason. Record the exact command/config and inspected rollout artifacts.For preservation, also retain a successful-tool rollout and a recoverable error-valued tool result: neither should become an episode failure merely because a tool reply reports an error. If the smoke owns a sandbox or session, confirm its release on cancellation and lifespan exit. These are proposed acceptance checks, not results I obtained.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
|
/ok to test 230948a |
|
/ok to test 2070cec |
|
On the codex review's RISK about SWE-Together's cleanup dependencies: fixed in 2dde529.
Not changed: |
|
/ok to test 2dde529 |
|
/ok to test 17dfa3f |
|
/ok to test f68ea11 |
|
/ok to test 72022b2 |
…onmentServerWithTools shuts down At shutdown, uvicorn cancels the running /run requests after its 0.5 s graceful timeout and goes straight to the lifespan shutdown without waiting for them. The event loop's teardown then cancels them again, and a native cancellation interrupts the shielded cleanup partway, so an episode's sandbox can be left running. BaseEnvironmentServerWithTools now implements run() to track each running episode's CleanupContext until its last cleanup has run, and its lifespan shutdown finishes every tracked context (cleanups are idempotent). Subclasses implement run_episode(). Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Felipe Vieira Frujeri <[email protected]>
…thin one budget Review of #5348: - The shutdown sweep runs each cleanup under its episode's rollout, so a Resources Server close carries the attempt's capture key, as in the normal unwind. - The sweep starts every unfinished cleanup at once and waits cleanup_timeout_seconds in all, as the agent servers' shutdown drain does. A sandbox stop no longer waits behind an agent-session close that retries an agent that is shutting down too. The sweep logs each episode whose cleanup it could not confirm. - An episode whose cleanup failed when it ended stays tracked, so the sweep tries the cleanup again instead of leaving the sandbox to its TTL. - A subclass that overrides run is refused when it is defined, also when it defines run_episode too, because overriding run skips the tracking. - A tool that raises a handled episode failure (such as a crashed sandbox) fails the episode with it when run_episode returns. Before, the failure became a 500 for the model and the episode was graded as the agent's failure. - A test runs uvicorn's order: one cancellation, then the lifespan exit while the request's own cleanup still stops the sandbox. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Felipe Vieira Frujeri <[email protected]>
… at shutdown BaseEnvironmentServer.run_request now tracks each episode's CleanupContext until all of its cleanups have finished, and the app's lifespan finishes the rest when the server shuts down. Before, only BaseEnvironmentServerWithTools did this, so an Environment Server such as swe_together could leave its candidate and judge sandbox stops unfinished when shutdown cancelled /run. A BaseEnvironmentServerWithTools subclass implements run again, not run_episode, so run is the one method every Environment Server implements. A tool's handled episode failure still fails the episode when run returns, through _recorded_episode_failure. single_agent_turn_legacy builds its own app, so it calls setup_shutdown_sweep. The sweep tests move to the base's tests and run on a plain Environment Server. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Felipe Vieira Frujeri <[email protected]>
…p, also at shutdown The shutdown sweep starts every unfinished cleanup at once, so SWE-Together's runtime release could run while a sandbox stop was still in progress. It then skipped the release but counted as done, and the lifespan's RuntimeProvisioner.close failed with the bundle still owned. The release now closes both sandboxes through their cleanup handles first. The handles are locked and idempotent: a stop that already ran is skipped, and a stop that fails keeps the bundle for a retry. The sweep's docstring says that a cleanup that needs another one first awaits its handle. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Felipe Vieira Frujeri <[email protected]>
|
/ok to test c98282b |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/43943706820 |
Stacked on #5347 (
BaseEnvironmentServerWithTools).What changed
BaseEnvironmentServer.run_requesttracks each episode'sCleanupContextuntil all of its cleanups have finished. A cleanup that failed, such as a sandbox stop that got a provider error, or that a cancellation interrupted, keeps the context tracked.finish_running_cleanups(). It starts every unfinished cleanup at once, each under its episode's rollout, waitscleanup_timeout_secondsin all, cancels what is left, and logsEpisode cleanup unconfirmed at shutdownfor each episode it could not confirm.setup_webserverinstalls it. A server that builds its own app callssetup_shutdown_sweep(app);single_agent_turn_legacynow does.runstays the only method a subclass implements, onBaseEnvironmentServerWithToolstoo. A tool's handled episode failure, such as a crashed sandbox, fails the episode whenrunreturns (_recorded_episode_failure); the agent sees that call fail meanwhile.Why
At shutdown,
run_webserver's uvicorn (timeout_graceful_shutdown=0.5) cancels the running/runrequests and goes straight to the lifespan shutdown. When the event loop closes,asyncio.runcancels those tasks again.run_requestruns cleanups underCancelScope(shield=True), but the shield does not hold against a nativetask.cancel(), so the second cancellation can stop a sandbox stop halfway.test_shutdown_finishes_a_cleanup_that_a_second_cancellation_interruptedreproduces that sequence.The first revision of this PR did the sweep only in
BaseEnvironmentServerWithTools. Every Environment Server has the same problem:swe_togetherregisters its candidate and judge sandbox stops as cleanups, and its own shutdown closes only its runtime;harborhas its own sweep for its sandboxes. Tracking inrun_requestcovers all of them (Linear GYMINT-642).Validation
pytest tests/unit_tests/server_runtime tests/unit_tests/agentsharbor,swe_together,single_agent_turn,single_agent_turn_legacy,nemo_user_sim,legacy_agentrun_request; no lifespan sweep; drop a context whose cleanup failed; no failure check afterrun; nosetup_shutdown_sweepinsingle_agent_turn_legacypre-commit runon the changed filesRollout evidence
A real model through an Environment Server already on main, at this PR's head (17dfa3f, rebased on main 330c461):
example_single_tool_callbehindsingle_agent_turn_legacy, withsimple_agentand an OpenAI-compatible policy model (openai_model).get_weather(one with three cities); the reward-0 rollout answered without calling the tool. No cleanup errors in the server logs.gym env startThe handled-failure path of
BaseEnvironmentServerWithToolshas no environment on main yet; BIRD-Interact (#5409) is its first user.Compatibility
CleanupContextalready requires idempotent cleanups.harborandswe_togetherkeep their own shutdown code, which runs after the sweep.cleanup_timeout_secondslonger when cleanups are left, and a context whose cleanup failed stays in memory until shutdown.BaseEnvironmentServerWithToolssubclass implementsrun. The first revision of this PR usedrun_episode; the stacked PRs and BIRD-Interact are updated.