Skip to content

feat(core): give stateful resources servers a teardown hook and an optional idle sweeper - #2612

Closed
waple0820 wants to merge 1 commit into
NVIDIA-NeMo:mainfrom
waple0820:feat/session-lifecycle
Closed

waple0820 wants to merge 1 commit into
NVIDIA-NeMo:mainfrom
waple0820:feat/session-lifecycle

Conversation

@waple0820

@waple0820 waple0820 commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Closes #2609

/seed_session allocates a browser, container, sandbox or provider lease; nothing releases it. A rollout that fails, times out, is cancelled or loses its seed response leaves that resource alive, and a retry allocates another while the first stays unreachable.

Identity comes from the caller

The caller creates _ng_session_id before the first seed transmission, so the id survives a response that never arrives. The provider's own handle cannot serve here — it is learned from that response, which is exactly what goes missing. A separate _ng_session_close_token is stored only as a digest and authorizes releasing exactly that one session when the cookie is gone.

Seeding deduplicates

The transport may repeat a seed it is not sure was delivered.

  • same id, same payload → the stored response is replayed, nothing is allocated
  • same id, different payload → 409
  • released id → 409, kept as a bounded tombstone

The last rule is not spelled out in the design. Replaying the stored response would hand the caller a session that no longer exists, so a released id is treated as spent.

The adapter owns everything that is not release

POST /close_session                    public route
_close_session_endpoint                identity, conflict checks, idempotency, response
release_session(session_id, reason)    release, and only release

The hook is deliberately not named close_session. GymnasiumServer, TALES and OpenAir already define that name with a different signature, and a base method sharing it would silently override theirs. Migration is one line, and is tested:

async def release_session(self, session_id, reason):
    await self.close_session(session_id)

We hit a version of that collision already: close_session as a typed POST route meant MCP auto-exposure published it as a model-callable tool, so a policy could have ended its own episode's resources.

Release runs once

The first closer creates the release task and concurrent closers await it, so provider cleanup does not run per caller. A failed release reports release_failed with 503 and leaves the session retryable rather than marking it closed.

An unknown id and an already-released one answer identically. There is no not_found status — that would let the endpoint be used to probe whether another rollout's session exists. This follows the close-session design rather than the five outcomes listed in #2609's body.

Expiry does not trust idle time alone

A rollout can sit in a model call for minutes without touching the resources server, so a session with handlers in flight is skipped. An absolute lifetime that activity does not suppress covers the case the first rule cannot: a handler that has hung. active_session() marks a handler in flight and refuses to start one once release has begun, so close cannot tear a resource down while verification is still reading it. The base uses it on its own routes; broad adoption across environment tool routes is #3037.

Scope

Agent-side orchestration, the bounded cancellation shield, X-NeMo-Gym-Cleanup-Status and the collector's _ng_run_info.cleanup are a follow-up, per "Agent and resources-server adoption are separate" in the design. The TTL mechanism stays here as the reference implementation; #3037 owns adoption across stateful servers.

Tests

27 cases over seven groups: seed replay does not allocate twice, payload conflict is 409, a delayed seed cannot resurrect a tombstone; the four terminal outcomes, a cookie/id conflict releasing neither, unknown and already-closed responses being byte-identical, ten concurrent closes releasing once, a failed release staying retryable; capability match, mismatch, id-alone rejection, and the token never reaching the record; idle expiry, busy suppression, absolute lifetime overriding busy, tombstone cleanup; handler counting and refusal after close; the base not defining close_session and the bridge working; route registration and release_session never reaching the model.

uv run --extra dev pytest tests/unit_tests -q → 4367 passed. test_e2b_provider and test_enroot_provider fail on a clean upstream/main too.

@copy-pr-bot

copy-pr-bot Bot commented Aug 19, 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.

@nemo-automation-bot nemo-automation-bot Bot added the community-request Issue reported or requested by someone from the community label Aug 19, 2026
@waple0820
waple0820 force-pushed the feat/session-lifecycle branch from 70f0b3e to eec331c Compare August 25, 2026 03:49
@waple0820
waple0820 force-pushed the feat/session-lifecycle branch from eec331c to 52adc3b Compare August 27, 2026 07:09
@waple0820
waple0820 marked this pull request as ready for review August 27, 2026 09:36
@waple0820

waple0820 commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Rebased onto main and out of draft.

Worth flagging what the rebase surfaced: six tests in responses_api_agents/simple_agent started failing, all of them asserting an exact POST sequence — /seed_session, /v1/responses, /verify — with no release at the end. session_scope() adds /close_session there, including on the skip-verification path from #2279. Updated those assertions rather than the behaviour: skipping the score does not skip the release.

One of the failures doubles as evidence for the design. When the release call itself fails, the episode logs

WARNING nemo_gym.base_responses_api_agent:217 failed to close the environment session on resources: ...

and returns its result normally. A reclaim that can break a rollout is worse than the leak it fixes, so the failure path is a warning by construction.

Also see #2750 (comment) on why a caller-driven release is necessary but not sufficient — the sweeper here is the part that survives a killed collector.

@github-actions github-actions Bot added the sla:triage-overdue Review assignment is over the one-business-day SLA label Aug 28, 2026
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the waiting-on-maintainers Waiting on maintainers to respond label Aug 29, 2026
@waple0820
waple0820 force-pushed the feat/session-lifecycle branch from 52adc3b to 753c2fb Compare August 31, 2026 06:58
@waple0820

Copy link
Copy Markdown
Contributor Author

#2886 landed yesterday — workplace_assistant now wraps its whole verify in a try/finally to drop the session's tool environment, including when scoring raises.

That is the same shape as interactive_browser in #1865 and the SWE agents' own paths, and all of them share one blind spot: the cleanup only runs when the episode reaches verify. An episode that times out, that crashes, or whose collector is killed never gets there, and whatever it allocated stays allocated.

That is what the hook here is for — the same guarantee in one place, plus the idle sweeper for the cases no call can reach.

@ananthsub

Copy link
Copy Markdown
Contributor

The lifecycle hook, agent finally block, TTL sweeper, and tests remain useful, but #2609 now owns a stricter wire contract: caller-created session identity, one-session close capability, seed deduplication and conflict detection, dedicated close outcomes, and idempotent recovery after lost responses. #3037 owns generic TTL and server adoption. This PR should be refactored or replaced against #2609 rather than merged as the final API.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added waiting-on-customer Waiting on the original author to respond and removed waiting-on-maintainers Waiting on maintainers to respond labels Sep 9, 2026
@waple0820
waple0820 force-pushed the feat/session-lifecycle branch from 99fc941 to a0f7e02 Compare September 10, 2026 08:02
@waple0820

Copy link
Copy Markdown
Contributor Author

@ananthsub reworked against the #2609 contract rather than merging the old shape.

What's in now: caller-created _ng_session_id with a close capability stored as a digest; seed deduplication that replays the stored response on the same payload, 409s on a different one, and keeps a bounded tombstone for a released id; the four terminal close outcomes, with unknown and already-closed answering identically; _close_session_endpoint owning identity, conflict checks and idempotency while release_session(session_id, reason) owns only release; concurrent closers joining one release task; and expiry that active handlers suppress, plus an absolute lifetime they do not.

Three calls where the spec left room, all easy to overturn:

release_session is the hook name, per the design — GymnasiumServer, TALES and OpenAir already define close_session with a different signature, so a base method sharing it would silently override theirs. The one-line bridge is tested.

There is no not_found status. The design says an unknown id and an already-closed one must answer identically, which an explicit not_found would defeat. That differs from the five listed in #2609's body.

A seed arriving for a released id returns 409 rather than replaying the stored response. Replaying it would hand the caller a session that no longer exists, so the id is treated as spent. Not spelled out either way in the design.

Agent-side orchestration, the bounded cancellation shield, X-NeMo-Gym-Cleanup-Status and the collector's _ng_run_info.cleanup are a follow-up, per "Agent and resources-server adoption are separate". The TTL mechanism stays here as the reference implementation with #3037 owning adoption.

27 tests over seven groups; 4318 unit tests pass.

@svcnvidia-nemo-ci svcnvidia-nemo-ci removed the waiting-on-customer Waiting on the original author to respond label Sep 12, 2026
@waple0820
waple0820 force-pushed the feat/session-lifecycle branch from a0f7e02 to 9564a60 Compare September 14, 2026 03:37
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the waiting-on-maintainers Waiting on maintainers to respond label Sep 14, 2026
@waple0820
waple0820 force-pushed the feat/session-lifecycle branch 2 times, most recently from 625df28 to ecdf327 Compare September 15, 2026 05:45
@waple0820
waple0820 force-pushed the feat/session-lifecycle branch 2 times, most recently from 2924f80 to 448fd79 Compare September 19, 2026 02:09
Built against NVIDIA-NeMo#2609's contract rather than patched onto the earlier shape.

Caller-created `_ng_session_id` with a close capability stored as a digest. Seed
deduplication replays the stored response on the same payload, 409s on a
different one, and keeps a bounded tombstone for a released id. Four terminal
close outcomes, with an unknown id and an already-released one answering
identically so the endpoint cannot probe another rollout's session.
`_close_session_endpoint` owns identity, conflict checks and idempotency;
`release_session(session_id, reason)` owns only release. Concurrent closers join
one release task. Expiry that active handlers suppress, plus an absolute
lifetime they do not.

Three calls where the spec left room, all easy to overturn:

`release_session` is the hook name, per the design — `GymnasiumServer`, TALES and
OpenAir already define `close_session` with a different signature, so a base
method sharing it would silently override theirs.

There is no `not_found` status. The design says an unknown id and an
already-closed one must answer identically, which an explicit `not_found` would
defeat.

A seed arriving for a released id returns 409 rather than replaying the stored
response: replaying it would hand the caller a session that no longer exists, so
the id is treated as spent.

Agent-side orchestration, the bounded cancellation shield,
`X-NeMo-Gym-Cleanup-Status` and the collector's `_ng_run_info.cleanup` are a
follow-up, per "Agent and resources-server adoption are separate". The TTL
mechanism stays here as the reference implementation with NVIDIA-NeMo#3037 owning adoption.

Signed-off-by: waple0820 <[email protected]>
@waple0820

Copy link
Copy Markdown
Contributor Author

@ananthsub closing this in favour of #3717, which landed #2609 with the same shape this PR was arguing for: the caller assigns resources_session_id and registers cleanup before the seed goes out, so a lost seed response still leaves something to close. That answers the question I raised on #3544 too.

The caller half of this PR is now in main under different names and a different layer, and the resources-server half — seed dedup, idempotent and coalesced close, idle expiry — is something the new design leaves to each server's close_resources_session override. So this branch no longer fits either side, and rebasing it would just be carrying a parallel implementation.

Two pieces I'll pick up separately:

  • interactive_browser overriding close_resources_session, so the browser environment actually releases its cloud session under the new protocol.
  • Idle expiry, on feat(resources): add session TTL and lifecycle adoption #3037 — the tested parts here (idle plus absolute lifetime, retry after a failed release, concurrent closes running the hook once) may be useful there, depending on whether you want it in the base or per server.

@waple0820 waple0820 closed this Sep 30, 2026
@svcnvidia-nemo-ci svcnvidia-nemo-ci removed the waiting-on-maintainers Waiting on maintainers to respond label Sep 30, 2026
yuhezhang-ai pushed a commit to ManoharPaturi/Gym that referenced this pull request Oct 1, 2026
NVIDIA-NeMo#3812)

## What

`interactive_browser` now serves the resources-session protocol an
Environment Server uses (NVIDIA-NeMo#3717): a typed `/seed_session` under the
caller's `resources_session_id`, and a `/close_session` that actually
releases the browser.

This is the follow-up I mentioned when closing NVIDIA-NeMo#2612.

## Why

Two gaps under Environment Server episodes today:

1. **Typed seed is swallowed.** `BrowserSeedSessionRequest` allows extra
fields, so a `ResourcesSeedSessionRequest` body validates as a legacy
seed and gets an empty `{}` back. `single_agent_turn` then fails
validating the seed response.
2. **Close is a no-op.** `/close_session` falls through to the base
default, so an episode that ends before `verify` (timeout, cancelled
agent) keeps its browser. With a remote provider that is a paid session
held until the provider reclaims it.

## How

Same shape as `swebench_pro`:

- `seed_session` takes `Union[ResourcesSeedSessionRequest,
BrowserSeedSessionRequest]` with `union_mode="left_to_right"`, so the
typed body wins. It opens the browser from `task_data` under the
caller's id and binds the cookie to that id, so direct-HTTP tool calls
and the MCP token both land on that browser. A retried seed for the same
`(episode_id, task_id)` returns the existing session; a different
episode on the same id is rejected.
- `close_resources_session` releases the browser, is idempotent, checks
`episode_id`, and remembers closed ids. A seed that arrives after its
close is rejected, so it can't open a browser nobody will close. An
empty body still closes the cookie session for `/run` callers.
- A per-id lock serializes seed and close. A close that arrives while
the browser is still opening waits for it, then releases it.
- `num_workers` other than 1 is refused, since browsers live in process.

Legacy `/run` seeding is unchanged and still returns `{}`.

## Tests

`tests/test_resources_sessions.py` (15 new): typed seed over HTTP, tool
calls reaching the seeded browser over direct HTTP and over MCP, retried
seed, id reuse across episodes, close before verify, double close,
mismatched episode, malformed close (422), legacy seed and empty close,
close during a slow seed, seed after close, `num_workers` guard, verify
after close.

```
cd resources_servers/interactive_browser && pytest tests -q   # 49 passed
pytest tests/unit_tests/test_mcp_auto_exposure.py tests/unit_tests/test_base_resources_server.py -q   # 60 passed
```

## Not in this PR

Idle expiry for sessions whose Environment Server never closes them
(process killed mid-episode). I'll ask on NVIDIA-NeMo#3037 whether that belongs in
the base class or per server before opening anything.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Signed-off-by: waple0820 <[email protected]>
Co-authored-by: waple0820 <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-request Issue reported or requested by someone from the community sla:triage-overdue Review assignment is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(core): define resources-session identity and close protocol

3 participants