Repository navigation
feat(newton_bench): serve the typed resources sessions API - #5485
Merged
Merged
Conversation
An Environment Server such as single_agent_turn seeds a resources server with a typed ResourcesSeedSessionRequest and releases it with /close_session. NewtonBench's seed took only its legacy body, so a typed seed failed validation with 422, and there was no close. The server now: - accepts the typed seed next to the legacy body, reads module_name, difficulty, system, noise_level and law_version from task_data, keys the session by resources_session_id and binds the cookie to it; task_data that fails validation or names an unknown module gets 422; - keeps the session, including its Python worker, when a seed is repeated for the same episode, and refuses another episode with 409; - closes by resources_session_id, with or without the cookie, through the existing _close_session (worker process and metadata); closing a session that verify, /end_session or the idle sweep already released succeeds, and ResourcesSessionFence refuses a late seed with 409; - answers a tool call for a session it no longer holds with ResourcesSessionLostError (404) instead of a 400, and a verify for it with a masked sample instead of a 400; a session the idle sweep reaped after session_ttl reports session_expired rather than session_lost. /verify, /end_session and the idle sweep still release sessions as before, so the legacy /run path is unchanged. A new newton_bench_single_agent_turn.yaml runs the rows through single_agent_turn_legacy with Simple Agent's direct HTTP grant, and the README describes it and the session lifecycle. Refs GYMINT-178 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
Contributor
Author
|
/ok to test bea34e3 |
yaoyu-33
marked this pull request as ready for review
November 3, 2026 18:33
Signed-off-by: yaoyu-33 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
… session_ttl The idle sweep's expiry records lasted only session_close_retry_window_seconds (300 s), while the sweep runs every 600 s with a 1800 s TTL. A client back from a stall more than 5 minutes after the sweep, the case the record exists for, got session_lost instead of the session_expired the README promises. The records now last the longer of session_ttl and the close retry window. The README also says that a retried typed verify scores the law again. Adds a test that moves the clock past the close retry window (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]>
Contributor
Author
|
/ok to test aa58850 |
Signed-off-by: yaoyu-33 <[email protected]>
weijiac0619
reviewed
Nov 4, 2026
Contributor
|
[Unrelated to this PR] while reviewing with AI assistance, I noticed that if the NewtonBench symbolic judge fails (no API key, 429, network error), upstream |
weijiac0619
previously approved these changes
Nov 4, 2026
yaoyu-33
enabled auto-merge
November 4, 2026 01:31
Signed-off-by: yaoyu-33 <[email protected]>
The /run seed guard refused any body sharing a key with ResourcesSeedSessionRequest, so a dataset row with a scalar task_id got 422 on every seed. Treat a body as a malformed typed seed only when it names resources_session_id or carries typed episode_id and task_id objects, the rule #5480 settled on. Also import check_resources_session_contract from nemo_gym.server_runtime, which main's public-API test requires; name the session agent in the README's single-agent-turn command (--agent takes an agent, not the Environment Server); and state verify's no-await invariant next to its retry bookkeeping. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]>
Contributor
Author
|
/ok to test 7c750db |
Signed-off-by: yaoyu-33 <[email protected]>
Contributor
Author
|
/ok to test d2b0f2b |
Signed-off-by: yaoyu-33 <[email protected]>
Contributor
Author
|
/ok to test 221c84d |
Signed-off-by: yaoyu-33 <[email protected]>
Contributor
Author
|
/ok to test a8cfe5b |
Signed-off-by: yaoyu-33 <[email protected]>
Contributor
Author
|
/ok to test 596a2c9 |
yaoyu-33
enabled auto-merge
November 13, 2026 16:41
weijiac0619
approved these changes
Nov 13, 2026
Contributor
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/43493855988 |
tayunvidia
pushed a commit
to tayunvidia/Gym
that referenced
this pull request
Nov 13, 2026
* feat(openenv): serve the typed resources sessions API An Environment Server such as single_agent_turn seeds a resources server with a typed ResourcesSeedSessionRequest and releases it with /close_session. The OpenEnv adapter took only the legacy seed body, answered with a response the Environment Server rejects, and had no close, so an episode that never reached /verify leaked its environment instance. The server now: - accepts the typed seed next to the legacy body, keys the environment instance by resources_session_id and binds the cookie to it; a repeated seed for the same episode keeps the instance, another episode gets 409; - closes the instance by resources_session_id, with or without the cookie, unless /verify already did; closing an unknown or closed session succeeds, a late seed is fenced with 409, and an env.close() failure raises so the close can be retried; - answers a tool call (/step or a per-tool route) for a session it no longer holds with ResourcesSessionLostError (404), and a verify for it with a masked lost-session sample instead of a reward of 0; - closes an environment instance whose reset() fails during a seed. /verify still closes the instance, since a legacy /run never closes its session. The README describes the session lifecycle and no longer claims a verifier_metadata.expected_output check that the code does not do. Refs GYMINT-176 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]> * fix(openenv): retain typed state and failed reset ownership Signed-off-by: yaoyu-33 <[email protected]> * fix(openenv): end a typed episode at verify so a late step cannot change a retried verify A typed session keeps its environment until /close_session, so a step still in flight when the Environment Server verified could add to the accumulated reward and make a retried verify report a different score. Verify now marks the episode done; later steps get the existing "Episode has ended" error. Also points the conformance import at nemo_gym.server_runtime.testing, fixes the close docstring, and makes two tests check what their comments claim. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]> * fix(openenv): release verified and retired session state Signed-off-by: yaoyu-33 <[email protected]> * refactor(server_runtime): share resources session policy checks Signed-off-by: yaoyu-33 <[email protected]> * refactor(openenv): reuse shared session checks Signed-off-by: yaoyu-33 <[email protected]> * refactor(server_runtime): own stateful resources lifecycle Signed-off-by: yaoyu-33 <[email protected]> * refactor(openenv): inherit the session lifecycle Signed-off-by: yaoyu-33 <[email protected]> * refactor(resources): fold session lifecycle into SimpleResourcesServer Signed-off-by: yaoyu-33 <[email protected]> * refactor(server_runtime): drop cookie rotation from the shared resources session lifecycle Mirror of the NVIDIA-NeMo#5480 change so the two PRs keep the same base: a cookie seed keeps the cookie's session ID and replaces the previous run's state instead of minting a fresh ID, so ResourcesSessionFence. legacy_seed_session_id becomes check_cookie_seed. The partial-typed-seed guard is the internal reject_partial_typed_seed and no longer rejects a dataset row's own task_id column. The shared lifecycle and policy tests are the NVIDIA-NeMo#5480 versions, which also import EpisodeId and TaskId from nemo_gym.core.episode_types (nemo_gym.core.episode does not exist). The OpenEnv test and README now describe a legacy /run that reuses a verified cookie replacing its environment under the same ID. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]> * fix(server_runtime): drop a finished run's verify record on a cookie re-seed A cookie seed keeps its session ID and replaces the previous run's state, but the previous run's verify retry record stayed, and remember() keeps the first record. In openenv the next run's verify then returned the finished run's reward without scoring or releasing the new environment; in example_mcp_weather a resent verify of the next run replayed the finished run's weather calls. Drop that record once the new run's state is initialized, through a new ClosedResourcesSessionRecords.forget() (unit-tested; the same hunk is in NVIDIA-NeMo#5485-NVIDIA-NeMo#5488). A failed re-seed keeps it. Shared base and lifecycle tests are identical in NVIDIA-NeMo#5480 and NVIDIA-NeMo#5483. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]> * fix(openenv): preserve seed validation through shared MCP lifecycle Signed-off-by: yaoyu-33 <[email protected]> * fix(server_runtime): close gaps in the shared resources session lifecycle - 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]> * test(openenv): cover both malformed typed seed shapes behind MCP The malformed typed seed test covered only a body with a resources_session_id and no envelope. Parametrize it over both shapes reject_partial_typed_seed refuses (that one, and dict episode_id plus dict task_id with no resources_session_id), with and without MCP exposure, and assert that the complete typed seed of the same session then returns 200, carrying resources_tools when MCP is on. Both MCP cases fail if the seed wrapper drops include_extras=True. README: say that OpenEnv's own /verify masks a verify after close, moves the typed identity out of _session_episodes and writes _verified_sessions, rather than claiming the base owns all of that bookkeeping; and say that the shipped configs pair OpenEnv with legacy_agent, whose simple_agent seeds by cookie. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]> * fix(server_runtime): retire a hook session without fencing it 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]> * fix(mcp): preserve annotated seed validators and request injection Signed-off-by: yaoyu-33 <[email protected]> * feat(sessions): centralize resources lifecycle and verification ownership Signed-off-by: yaoyu-33 <[email protected]> * fix(sessions): preserve cleanup ownership and shared verification semantics Signed-off-by: yaoyu-33 <[email protected]> * fix(resources): preserve grades and retry cleanup ownership Signed-off-by: yaoyu-33 <[email protected]> * fix(openenv): reject tools after completed verification Signed-off-by: yaoyu-33 <[email protected]> * test(mcp): keep a validator annotated directly on the seed body The wrapper strips Annotated only to recognize an injected Request. A validator written directly on the body parameter, the form an author is most likely to write, was covered only through a union arm, so a wrapper that stripped every parameter still passed. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]> * fix(resources): keep cancellation and reseed cleanup consistent; document the hook contract - A cancellation that arrives while a failed initialization is being cleaned up now propagates instead of being swallowed by the cleanup guard. - A cookie reseed that released the preceding run moves its finished receipt into the retry window, so a failed replacement no longer leaves a pending-cleanup record with nothing to release. - Document that a disconnect leaves a verification release pending, that the release hook runs under the session lock, that state is per worker with session routing keeping a session on its owner, and the override rules for servers that keep their own seed and close. - Rename the example server's private episode table so it no longer shares a name with the base's. - Add regressions for the receipt deadline guard, worker ownership wiring, cookie seed races and fences, typed seed takeover, restore refusals and a cancelled close waiting on verification. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]> * test(openenv): cover a retained zero reward and a partly reset reseed; correct the close wording Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]> * docs(openenv): drop the /run seed explanation The docs now describe only the typed Environment Server path. The cookie seed still works unchanged; the PR description records that compatibility. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: yaoyu-33 <[email protected]> --------- Signed-off-by: yaoyu-33 <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Serve typed Newton sessions through the shared lifecycle while preserving Newton-specific TTL, repeated-seed state checks and cached verification outcomes. Python workers are released on verify/close, including cancelled allocation and skipped verification.
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.
Retains (answer digest, measured result) after a successful evaluation, so a retry of the same answer replays it and a changed answer is masked.
After verification completes, pending cleanup no longer permits new tool calls. The resource handle stays owned until close/retirement succeeds; Newton also rechecks admission after waiting for the session lock.
Validation on
f8207c0f3683f28f729486ca51677c3bb19b3c99, Python 3.13.14, with this checkout first on PYTHONPATH and NEMO_GYM_EXTRA_ROOTS pointing to it:python -m pytest -o addopts='' -o log_cli=false --import-mode=importlib --tb=short -q resources_servers/newton_bench/tests: 100 passed.ruff check,ruff format --checkandgit diff --checkpassed on the changed files. The private guardwords catalog was unavailable, so that scan was skipped. New commits include DCO sign-off.Real-model smoke on preceding migration revision
d93a7366c76c830630161bd455216c492c2e5ee4(shared core4e92d4891) usednvidia/nemotron-3.5-lightning-30b-a3b, Python 3.13.14, the stock gravity task plus an explicit Python arithmetic check, and actual forkserver workers. Both normal and skip-verification cases executed Python, observed 385, acknowledged close and released the actual worker plus metadata/identity. Normal verification scored 0.4 (RMSLE 0; 0.3 x R_symbolic -1 + 0.7 x R_RMSLE +1: the symbolic judge had no credential, so this is the judge-outage value that #5678 masks, not a measured score); skip verification made zero verify calls and returned configured fixed reward 0.0. Both strict rollout receipts remain incomplete_or_failed: the model sent invalid string values for numeric experiment arguments, causing three HTTP 422 responses in the normal case and one in the skip case. Cleanup evidence passed separately. Symbolic judging remains unvalidated without its separate credential. Loaded source hashes matched that revision.; this is not a clean benchmark-score run.These targeted checks do not replace the repository CI matrix or approval of the current head.
The judge-outage fix from #5678 is included here; no separate merge ordering is required.
Compatibility
A tool call for an unknown, closed or verified session is now 404 with
failure_kind(main: 400);/verifyfor such a session is a masked 200 (main: 400); a second/verifyof the same answer returns the cached result;/end_sessionstops the worker but no longer drops the task metadata (it stays until verify, close, the idle sweep or retirement); workers start from a forkserver, so the first worker per server process waits seconds; a cookie reseed now releases the previous run's worker (main leaked it); a typed seed with an unknown module is 422, a cookie seed 400. Concurrentexecute_pythoncalls on one session now run one at a time.Main refresh validation
Merged main at
acb67734cinto 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: 100 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-filespassed 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 --checkpassed for each refreshed branch.Cross-environment consistency fixes
Release workers asynchronously without using the Python execution pool; retain handles on cancellation or failed termination. Shutdown cleanup now runs when the parent lifespan raises. Includes the existing #5678 judge-outage fix, so outages are masked and never cached as measured scores. Startup now requires an OpenAI or OpenRouter symbolic-judge key. After a judge outage, verification releases live state and a retry is masked as session_lost. Tests cover saturated execution pools, cancelled close/reseed, parent lifespan failures, and judge failure/recovery; both lifespan regressions fail against the preceding head.
Validation at
25097f484dcec062efa93fb1e29643ea57b71251onws, Python 3.13.14: this environment suite 110 passed; the three changed environment suites total 228 passed. Fullpre-commit run --all-filespassed 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.Config names
The session-based configuration is now
resources_servers/newton_bench/configs/newton_bench.yaml, sogym env start --resources-server newton_benchselects it. The previous configuration is available asnewton_bench_legacy_agent.yaml; users retaining the legacy-agent route should select that file explicitly. Both YAML contents are preserved exactly, and the README commands and generated catalog links use the new names.Validation for this rename on
ws(Python 3.13.14): both configurations composed successfully withgym env resolve, fullpre-commit run --all-filespassed after regenerating the catalog, andgit diff --checkpassed. No new unit tests or model rollout were needed for this filename and documentation change.Main integration validation (2026-11-10)
Merged main
a5cc1105564f38d7c7be5c86da5892f740d596e2, retaining both the NewtonBench session/judge handling and main's worker-entrypoint guard. The manual conflict resolution is limited to the import union inapp.py; the worker guard from main is preserved.Validation on workstation
ws:gym env test +entrypoint=resources_servers/newton_bench +should_validate_data=true: 110 passed; data validation passed.pytest tests/unit_tests/server_runtime/test_resources_session_lifecycle.py tests/unit_tests/server_runtime/test_session_routing.py tests/unit_tests/utils/test_server_process.py -q: 170 passed.gym env resolvefor both NewtonBench config files together withresponses_api_models/openai_model/configs/openai_model.yamland placeholder model connection values: passed; no model calls.pre-commit run --all-files: passed.No new model rollout was run for this import/worker-startup integration. Earlier model smoke remains historical evidence. A fresh scored NewtonBench rollout still requires an OpenAI/OpenRouter symbolic-judge credential; it cannot be replaced by a numeric-only check or an unverified zero.
Release rehearsal CI repair
Earlier PR rehearsals failed with
Argument list too longwhile generating repository-wide release notes. The earlier default-branch comparison was a temporary repair. This branch now uses main’s previous-release-tag selection from #6066 and the current shared release template, preserving explicit changelog overrides. The earlier CI runs below remain historical evidence.Validation: YAML parsing and
pre-commit run --all-filespassed onws; no model run is applicable to this workflow-only change. The workflow is byte-identical to the version whose release finalization already passed on #5703, #5537, and #5762. Fresh CI is requested for this PR's new source commit.Completed CI for the repair
Source
a8cfe5bd16ab42905be6dbee4aa37d777154a9b3: CICD NeMo Gym and release rehearsal passed. Lint and DCO also passed.Main integration validation (2026-11-12)
Source
596a2c99565b630f4c0fb3a02dc397d1270f7ff6merges main5d22439f4b4d84eaf7ef3d08e9dff1527f775d92. The only manual conflict was the release workflow, which now matches main’s #6066 previous-tag lookup, explicit override, job dependency, and template pin. Prior feature changes remain intact; no lockfile regeneration was needed.Workstation validation on the reviewed tree:
pre-commit run --all-files: passed; no tracked files changed.bash -npassed for both embedded shell blocks.Independent source review passed. New model smoke: N/A for this workflow-only conflict resolution; prior feature and model evidence remains pinned to the revisions recorded above.
CI requested for this exact source: Build, validate, and release NeMo-Gym, CICD NeMo Gym. Current CI status is available in the linked runs.