Skip to content

fix(math_with_code): release the Python worker in close_resources_session - #5481

Merged
yaoyu-33 merged 30 commits into
mainfrom
yuya/gymint-175-math-with-code-close-sessions
Nov 10, 2026
Merged

yaoyu-33 merged 30 commits into
mainfrom
yuya/gymint-175-math-with-code-close-sessions

Conversation

@yaoyu-33

@yaoyu-33 yaoyu-33 commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Release the Python worker through the shared resources lifecycle so close works independently of verification. Switch worker start from the default multiprocessing context (fork on Linux) to a lazily started forkserver worker, keep request-based scoring and serialize allocation/cleanup.

The shared lifecycle in #5709 and MCP support in #5708 are merged into main. The child diff contains only this environment and its related documentation/configuration; shared implementation is reviewed once in the dependency. No separate issue is needed for this focused migration of an existing resources server.

  • Track the shielded worker-start task until its result is published, including cancellation of the request awaiting it. Close waits for pending allocation and then releases the actual worker; an abandoned to_thread result can no longer leak a process.
  • Add forkserver socket isolation and an async close that escalates SIGTERM then SIGKILL off the executor. A surviving process remains owned and makes cleanup fail for retry. Verification now uses the shared public context; bounded receipts retain identity, while scoring recomputes from the request.

Request-scored: retains an empty marker (retain(None)) because the request already carries the answer and grading data.

Validation on 7cc1eb7c8fece27c1302991bd4e7e748976dc3c1, Python 3.13.14, with this checkout first on PYTHONPATH and NEMO_GYM_EXTRA_ROOTS pointing to it:

Real-model smoke on preceding migration revision 27a4d4998ba824d9dc06ac41f11a914cffff9d67 (shared core 4e92d4891) used nvidia/nemotron-3.5-lightning-30b-a3b, Python 3.13.14 and actual forkserver workers. Normal and skip-verification cases each executed Python and returned 385. Normal verification scored 1.0; the skip case made zero verify calls and returned fixed reward 0.0. Verify/close returned 200 as applicable, worker death was observed, and active/starting/identity maps were empty. The skip case released a real live worker at close. Loaded source hashes matched that revision. These are synthetic lifecycle tasks, not a math benchmark baseline. The smoke made one verify per episode, so the retry path (retain(None)) is covered by unit tests only.

These targeted checks do not replace the repository CI matrix or approval of the current head.

Compatibility

The first worker per server process waits for the forkserver to import the module (seconds; later workers start in milliseconds). The forkserver is one extra resident process per server process (about 230 MB measured on macOS). Closing a worker that ignores SIGTERM can take about 11 s while holding the session lock. A worker that cannot start still answers the tool call with success: false (as on main), is now logged, and the episode is scored from the answer alone.

Main refresh validation

Merged main at acb67734c into this branch, retaining main's MCP annotation resolution and seed-validation regressions. The diff against main contains only this environment and its related documentation/configuration. No new environment behavior was added by this refresh.

On workstation ws (Python 3.13.14), this environment's complete test directory passed: 45 passed. The nine environment suites passed 904 tests in total. Shared lifecycle, MCP seed/exposure, and process-supervisor tests passed 213 tests. Tests ran in a combined validation checkout with the merged core and the exact environment sources from these nine heads, with the checkout first on PYTHONPATH and NEMO_GYM_EXTRA_ROOTS. Prior real-model smoke evidence above remains historical; no fresh model rollout was run for this merge-only update. New merge commits are DCO signed off.

pre-commit run --all-files passed on the combined checkout, including Ruff, formatting, guardwords, config flags, environment table generation, and import layering. The generated README row matches the row already included in #5485. git diff --check passed for each refreshed branch.

Cross-environment consistency fixes

Serialize each worker pipe exchange in its executor thread, retaining the lock after cancellation of the HTTP waiter. Concurrent calls receive their own replies, and cleanup can terminate a busy worker without waiting for that lock or a free executor thread. Both real-worker response-ownership regressions fail against the preceding head and pass here.

Validation at dc0190ae687d85627e4869eb85e297e6a14b73cc on ws, Python 3.13.14: this environment suite 47 passed; the three changed environment suites total 228 passed. Full pre-commit run --all-files passed in the combined validation checkout. All 59 tracked files in the three changed environments matched the local final sources by SHA-256. Three independent component reviewers examined the nine environments; a second reviewer challenged the worker/cancellation fixes. The six other environment branches required no additional changes.

A fresh task-local model/worker diagnostic used nvidia/nemotron-3.5-lightning-30b-a3b, real forkserver workers, and two concurrent arithmetic calls. Both environments returned 385 and 55 and released their workers and session identity; math verification scored 1.0 unmasked. This exercised actual resources methods directly, not an HTTP or production-agent rollout. Newton verification was not invoked in this diagnostic because its separate symbolic-judge credentials were unavailable; its judge failure and recovery paths were exercised by tests.

…sion

math_with_code keeps a per-rollout Python worker process keyed by the
session cookie, and stopped it only in /verify or /end_session. Under
single_agent_turn_legacy, an episode that never reached /verify kept its
worker until the server exited, because the inherited
close_resources_session kept no state. Stopping a worker also only joined
for one second, so a worker busy in user code outlived the stop.

- seed_session binds a typed seed's resources_session_id to the cookie and
  records its episode and task; the legacy /run seed body keeps no state.
- close_resources_session stops the worker by resources_session_id, fences
  late seeds with ResourcesSessionFence, is idempotent, and raises when the
  worker survives, so the caller can retry.
- _SessionHandle.close escalates to SIGTERM and SIGKILL and raises if the
  process is still alive; a worker that survives stays registered. Verify
  logs that failure and keeps its score. Stops run off the event loop.
- execute_python for a closed session gets ResourcesSessionLostError
  (404); a call that a close overtook stops the worker it started.
- A /verify for a closed session returns lost_session_verification.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Nov 3, 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.

@yaoyu-33 yaoyu-33 added area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers bug Something isn't working labels Nov 3, 2026
@yaoyu-33

yaoyu-33 commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test d87a7f4

yaoyu-33 and others added 3 commits November 3, 2026 11:05
… the registry on the loop

Linux forks the worker, so it inherits the server's Python SIGTERM handler (uvicorn's under a served app). terminate() then only ran that handler, and every close of a busy worker waited out both joins before SIGKILL, holding a thread and the session's fence for about 6 s. The worker now resets SIGTERM and SIGINT to their defaults.

_cleanup_session ran entirely in a thread, so two cleanups of one handle could both pass the identity check and the second del raised KeyError, which verify's except RuntimeError did not catch. Only handle.close now runs in a thread; the check and delete happen on the event loop.

Adds a test that forks a worker under a no-op SIGTERM handler (fails on the previous code), and moves the conformance import to nemo_gym.server_runtime.testing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@yaoyu-33

yaoyu-33 commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test af49dc9

@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team November 3, 2026 21:43
@github-actions github-actions Bot added the sla:triage-overdue Review assignment is over the one-business-day SLA label Nov 4, 2026
yaoyu-33 and others added 6 commits November 4, 2026 15:19
…ycle

- The repo contract test counts a server that implements the state hooks as
  closing through the inherited close_resources_session. newton_bench,
  workplace_assistant, tavily_search and indirect_prompt_injection override
  seed_session but close through the hooks, and failed it.
- Export reject_partial_typed_seed from nemo_gym.server_runtime, so servers
  that override seed_session reuse the shared guard instead of a copy.
- The MCP seed wrapper still recognises a request param annotated as
  Annotated[Request, ...]; keeping Annotated metadata had made it inject a
  second Request and fail with KeyError.
- Name the 409 for a typed seed over a cookie session "cookie-seeded", not
  "legacy", and document that a served seed_session override declares
  request before body.
- Shared tests now cover the MCP-wrapped seed route, close after verify
  (checked against the verified episode), and a cookie seed of a verified
  typed session.
- The add-benchmark skill describes the three state hooks as the default
  for a stateful server.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
The inherited retire_session_state recorded a typed session as closed. The
checkpoint participant also calls that hook to undo a restore
(delete_restored) and to drop an unclaimed session, and both promise to
refuse nothing later; with the fence, a restore that was rolled back and
installed again in the same process left its session fenced, so its verify
was masked as lost and its continuation's seed got 409. The participant
already refuses a retired attempt's requests until it forgets the rollout,
so retirement now releases the state and drops the identity without
recording a close. A close still fences.

Also write down that an exported server using the state hooks carries each
session's identity through its checkpoint itself.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@kajalj22
kajalj22 removed request for a team November 6, 2026 22:51
Base automatically changed from yuya/shared-resources-lifecycle to main November 8, 2026 06:36
@yuhezhang-ai
yuhezhang-ai requested a review from ffrujeri November 9, 2026 20:18
@github-actions github-actions Bot removed the sla:triage-overdue Review assignment is over the one-business-day SLA label Nov 9, 2026
@yaoyu-33

yaoyu-33 commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test dc0190a

@yaoyu-33
yaoyu-33 added this pull request to the merge queue Nov 10, 2026
@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/42767695952

@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/42768128157

@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/42771358573

@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 10, 2026
@yaoyu-33
yaoyu-33 added this pull request to the merge queue Nov 10, 2026
@yaoyu-33 yaoyu-33 added ready-to-merge PR is approved, current, and waiting for final CI or merge and removed needs-review PR is ready for code review and waiting on a reviewer labels Nov 10, 2026
@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/42851710007

Merged via the queue into main with commit 93a6c09 Nov 10, 2026
102 of 113 checks passed
@yaoyu-33
yaoyu-33 deleted the yuya/gymint-175-math-with-code-close-sessions branch November 10, 2026 16:26

This branch was previously deployed

1 inactive deployment
public — dc0190ae Deployed Nov 9, 2026 by copy-pr-bot[bot] via release / finalize / notify #11197
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers bug Something isn't working ready-to-merge PR is approved, current, and waiting for final CI or merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants