Skip to content

feat(environment): finish every Environment Server's running cleanups at shutdown - #5348

Merged
ffrujeri merged 4 commits into
ffrujeri/self-contained-environment-serverfrom
ffrujeri/self-contained-shutdown-sweep
Nov 16, 2026
Merged

ffrujeri merged 4 commits into
ffrujeri/self-contained-environment-serverfrom
ffrujeri/self-contained-shutdown-sweep

Conversation

@ffrujeri

@ffrujeri ffrujeri commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #5347 (BaseEnvironmentServerWithTools).

What changed

  • BaseEnvironmentServer.run_request tracks each episode's CleanupContext until 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.
  • The app's lifespan shutdown calls finish_running_cleanups(). It starts every unfinished cleanup at once, each under its episode's rollout, waits cleanup_timeout_seconds in all, cancels what is left, and logs Episode cleanup unconfirmed at shutdown for each episode it could not confirm. setup_webserver installs it. A server that builds its own app calls setup_shutdown_sweep(app); single_agent_turn_legacy now does.
  • run stays the only method a subclass implements, on BaseEnvironmentServerWithTools too. A tool's handled episode failure, such as a crashed sandbox, fails the episode when run returns (_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 /run requests and goes straight to the lifespan shutdown. When the event loop closes, asyncio.run cancels those tasks again. run_request runs cleanups under CancelScope(shield=True), but the shield does not hold against a native task.cancel(), so the second cancellation can stop a sandbox stop halfway. test_shutdown_finishes_a_cleanup_that_a_second_cancellation_interrupted reproduces that sequence.

The first revision of this PR did the sweep only in BaseEnvironmentServerWithTools. Every Environment Server has the same problem: swe_together registers its candidate and judge sandbox stops as cleanups, and its own shutdown closes only its runtime; harbor has its own sweep for its sandboxes. Tracking in run_request covers all of them (Linear GYMINT-642).

Validation

Command Result
pytest tests/unit_tests/server_runtime tests/unit_tests/agents 1868 passed
Environment Server tests: harbor, swe_together, single_agent_turn, single_agent_turn_legacy, nemo_user_sim, legacy_agent 698, 272, 184, 44, 33 and 12 passed
Mutations: no tracking in run_request; no lifespan sweep; drop a context whose cleanup failed; no failure check after run; no setup_shutdown_sweep in single_agent_turn_legacy each makes at least one test fail
pre-commit run on the changed files passed

Rollout evidence

A real model through an Environment Server already on main, at this PR's head (17dfa3f, rebased on main 330c461): example_single_tool_call behind single_agent_turn_legacy, with simple_agent and an OpenAI-compatible policy model (openai_model).

gym env start --config resources_servers/example_single_tool_call/configs/example_single_tool_call_single_agent_turn.yaml \
  --config responses_api_models/openai_model/configs/openai_model.yaml
gym eval run --no-serve <same configs> --input resources_servers/example_single_tool_call/data/example.jsonl \
  -a example_single_tool_call_session_agent ++environment_routing_mode=legacy \
  ++environment_server_name=example_single_tool_call_single_agent_turn [--num-repeats 8]
Run Result
5 tasks 5/5 completed, 0 failed, mean reward 0.8. Four rollouts call get_weather (one with three cities); the reward-0 rollout answered without calling the tool. No cleanup errors in the server logs.
5 tasks x 8 repeats, then SIGINT to gym env start 40/40 completed, 0 failed, mean reward 0.8; the servers shut down without cleanup errors. The tasks finish in about a second, so the interrupt came after the last episode: a shutdown with episodes in flight is covered by the unit tests above, which drive the lifespan in uvicorn's order.

The handled-failure path of BaseEnvironmentServerWithTools has no environment on main yet; BIRD-Interact (#5409) is its first user.

Compatibility

  • Every Environment Server now finishes unfinished episode cleanups at shutdown. CleanupContext already requires idempotent cleanups. harbor and swe_together keep their own shutdown code, which runs after the sweep.
  • Shutdown can take up to cleanup_timeout_seconds longer when cleanups are left, and a context whose cleanup failed stays in memory until shutdown.
  • A BaseEnvironmentServerWithTools subclass implements run. The first revision of this PR used run_episode; the stacked PRs and BIRD-Interact are updated.

@copy-pr-bot

copy-pr-bot Bot commented Oct 30, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test ee6e898

@ffrujeri
ffrujeri added this pull request to stack #5352 October 30, 2026 06:21
@svcnvidia-nemo-ci svcnvidia-nemo-ci added area:env-infra Shared environment framework, lifecycle, registry, scaffolding, and validation bug Something isn't working labels Oct 30, 2026
@ffrujeri
ffrujeri force-pushed the ffrujeri/self-contained-shutdown-sweep branch from ee6e898 to 5c09460 Compare October 30, 2026 16:21
@ffrujeri ffrujeri changed the title feat(environment): finish running episodes' cleanups when a self-contained Environment Server shuts down feat(environment): finish running episodes' cleanups when a turn-based Environment Server shuts down Oct 30, 2026
@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 5c09460

@ffrujeri
ffrujeri force-pushed the ffrujeri/self-contained-shutdown-sweep branch from 5c09460 to f5e15f4 Compare October 31, 2026 13:16
@ffrujeri ffrujeri changed the title feat(environment): finish running episodes' cleanups when a turn-based Environment Server shuts down feat(environment): finish running episodes' cleanups when a BaseEnvironmentServerWithTools shuts down Oct 31, 2026
@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test f5e15f4

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 2124b51

ffrujeri added a commit that referenced this pull request Nov 10, 2026
…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]>
@ffrujeri
ffrujeri force-pushed the ffrujeri/self-contained-shutdown-sweep branch from 2124b51 to 52eb857 Compare November 10, 2026 06:12
@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 52eb857

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test ebec917

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test e8f6300

@adil-a

adil-a commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

/review reset=True

@svcnvidia-nemo-ci svcnvidia-nemo-ci left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.py line 207: RISK — Preserve SWE-Together's cleanup dependencies during the concurrent sweep

    Exit 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-None sandbox and returns without releasing its bundle; _CleanupEntry.close then marks it complete. When the stops clear the fields, normal unwind skips the completed runtime entry. The outer lifespan subsequently calls RuntimeProvisioner.close, which raises Runtime bundles remain owned by task sandboxes before stopping the helper. Thus workload stops can succeed while the bundle and helper remain owned and lifespan shutdown fails.

    Could release_runtime wait 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.json and 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.py line 382: RISK — Provide representative model-backed smoke evidence

    The 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 execute tool that raises handled_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 /run should 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.

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 230948a

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 2070cec

@ffrujeri

Copy link
Copy Markdown
Contributor Author

On the codex review's RISK about SWE-Together's cleanup dependencies: fixed in 2dde529.

  • The sweep keeps starting every cleanup at once, as asked in the earlier review, so a sandbox stop does not wait behind an agent-session close to a server that is shutting down too.
  • SWE-Together's release_runtime now closes both sandboxes through their cleanup handles before it releases the bundle. The handles are locked and idempotent: a stop that already ran is skipped, a stop that is still running is awaited, and a stop that fails keeps the bundle for a retry. In a normal unwind the sandboxes have already stopped, so nothing changes there.
  • finish_running_cleanups's docstring now says that a cleanup that needs another one first awaits its CleanupHandle.
  • New test, test_shutdown_releases_the_runtime_bundle_after_its_sandboxes_stop: an episode is mid-activation when the sweep runs, its sandbox stops are slow, and the bundle is released once, after both stops. With the old check, the release does not happen. SWE-Together's 274 tests pass.

Not changed: persist_cleanup_evidence can still write cleanup-receipts.json before a late receipt arrives when the sweep interrupts an episode. Waiting for the other cleanups from there would retry failed cleanups in every normal unwind as well, and the interrupted episode returns no result, so I left it.

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 2dde529

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 17dfa3f

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test f68ea11

@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test 72022b2

ffrujeri and others added 4 commits November 16, 2026 17:57
…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]>
@ffrujeri

Copy link
Copy Markdown
Contributor Author

/ok to test c98282b

@github-actions

Copy link
Copy Markdown
Contributor

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:env-infra Shared environment framework, lifecycle, registry, scaffolding, and validation bug Something isn't working needs-review PR is ready for code review and waiting on a reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants