Skip to content

feat(finance_agent_v2): serve the resources sessions API - #5491

Open
yaoyu-33 wants to merge 17 commits into
yuya/gymint-171-finance-sec-search-sessionsfrom
yuya/gymint-170-finance-agent-v2-sessions
Open

yaoyu-33 wants to merge 17 commits into
yuya/gymint-171-finance-sec-search-sessionsfrom
yuya/gymint-170-finance-agent-v2-sessions

Conversation

@yaoyu-33

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

Copy link
Copy Markdown
Contributor

Main integration after the fix

Final head: f0f81432c; integrated stack head: 95a486692, including main 72275b85d. Resolved the routing conflict by preserving main's pending-cleanup ownership behavior and the new expiration deadline. Both regression suites remain. Independent source recheck found no conflict-induced regression.

Post-merge workstation checks: SEC resources 118 passed, v2 resources 240 passed, finance agent + routing + base resources + new resources lifecycle/policy tests 383 passed (741 total). Full pre-commit was rerun on this tree. The real-model smokes below ran at c3dc26098 before this main integration; they have not been rerun on 95a486692. Fresh GitHub CI is required for the published heads.

AI review follow-up (November 8)

Fixed the expired-session routing finding: retain the owning worker until the expiration metadata deadline, including across late verify/close requests. Verification checks the timestamp directly so stale entries cannot continue masking after the deadline. Document cleanup and checkpoint termination still occur immediately at eviction; fresh seeds and never-seeded stateless reverify keep their existing behavior.

Revision: 5e6b41b6d; integrated validation tree: c3dc26098. The stack was updated with signed additive commits/merges, preserving its bases.

Workstation validation (Python 3.13.14):

  • python -m pytest resources_servers/finance_sec_search/tests -q -o addopts= -o log_cli=false: 117 passed.
  • python -m pytest resources_servers/finance_agent_v2/tests -q -o addopts= -o log_cli=false: 238 passed.
  • python -m pytest responses_api_agents/finance_agent/tests tests/unit_tests/server_runtime/test_session_routing.py tests/unit_tests/server_runtime/test_base_resources_server.py -q -o addopts= -o log_cli=false: 296 passed.
  • python -m pre_commit run --all-files: passed, including guardwords and import-linter. Pre-commit 3.8.0 was used for workstation Git compatibility.
  • The two added regressions in each resources suite fail against the original implementation and pass with the fix. They cover cross-worker expired verification/late close and expiration-record deadlines without another seed.

The shared routing change makes #4948 full-scope for CI. Full repository suites and benchmark score parity were not run locally. Earlier no-real-model statements below are historical; they were already superseded by the November 6 evidence.

Fresh bounded real-NIM smokes at the integrated fixed tree passed for both canonical resources configs (model nvidia/nemotron-3.5-lightning-30b-a3b, temperature 0, max 8192 output tokens, 8 agent steps). Each ran one controlled-report task through real HTTP policy/tools/retrieval/judge: rewards 1.0 / 1.0, 0 failures / 0 masked rows, expected parse/retrieve/submit calls (plus calculator for v2), both close endpoints HTTP 200, and zero document/time/episode-seed/active-agent state afterward. All task HTTP servers stopped. This does not establish full benchmark parity, CLI collection, or live SEC/Tavily/Tiingo coverage. Machine-local evidence: ws:/home/yuya/finance-ai-20261109/ (audit.json, runs/fixed-sec/, runs/fixed-v2/, test/hook logs); source/patch hashes are recorded.


Stack: builds on #4948 (finance_sec_search), so its base is that branch; #5492 (finance_agent agent sessions) builds on this one. The diff against #4948 is only resources_servers/finance_agent_v2/.

What and why

finance_agent_v2 keeps per-rollout state: the documents parse_html_page stores for retrieve_information, and each rollout's time budget. On main it serves only the agent-run seed, so an Environment Server's episode seed gets {} back, which single_agent_turn cannot validate. It also has no close_resources_session, so a rollout that never reaches /verify keeps its state for the server's lifetime.

This applies the resources sessions contract the same way #4948 does for finance_sec_search, whose session code is identical:

  • Episode seed. /seed_session accepts ResourcesSeedSessionRequest | BaseSeedSessionRequest. An episode seed is keyed by resources_session_id under ResourcesSessionLocks.locked.
    • A retry returns the open session and keeps its stored documents.
    • A seed that binds the ID to another episode or task gets ResourcesSessionConflictError (409).
    • The cookie's SESSION_ID_KEY is bound only after those checks, so a refused seed's reply carries no cookie for the live session.
    • The agent-run seed still starts the session afresh and returns {}.
  • Close. close_resources_session releases storage, time budget and episode seed by ID, with or without the cookie, then fences the ID (ResourcesSessionFences.fence): a later episode or agent-run seed gets 409. A close that names another episode gets 409. Repeated closes, and closes of sessions never seeded, succeed. Releasing only drops in-memory entries, so it has no failure to raise.
  • Verify releases an agent-run session. finance_agent's /run never closes it. An episode session keeps its seed and documents until its close, so that close still checks the seed's episode. The score reads only the request (REVERIFY_MODE is stateless, and gym eval reverify seeds nothing), so a verify for a session that was never seeded is scored; a verify after close_session is masked (lost_session_verification), as in feat(finance_sec_search): serve the resources sessions API #4948. Tests pin both.
  • Lost sessions. parse_html_page and retrieve_information raise ResourcesSessionLostError (404, failure_kind=session_lost) when the session is not open, instead of _get_session_storage creating storage nothing would release. The other tools (calculator, submit_final_result, web_search, edgar_search, price_history) ignore state and answer as before.
  • Abandoned sessions. Each seed discards sessions older than the new session_ttl_seconds (default 6 h), and ends their ownership and checkpoint tracking. A verify for an evicted session is masked with failure_kind=session_expired, and an evicted episode session is fenced as after a close. A checkpoint retire releases the retired attempt's session.
  • Docs. The README gains a Sessions section.

Not in this PR:

No separate public issue: this is one server's step in the resources-sessions migration that #4679 defines; the stack's other PRs are listed above.

Compatibility

  • New config field session_ttl_seconds (default 21600). It must exceed the longest rollout; FABv2's agent budget is 3600 s.
  • parse_html_page or retrieve_information on a session that is not open now returns 404 with failure_kind=session_lost instead of a result. finance_agent's /run always seeds first, so the legacy path never hits it.
  • A verify for a session that outlived session_ttl_seconds is masked (failure_kind=session_expired) instead of scored.
  • Agent-run seed and verify responses are otherwise unchanged. No benchmark-number change on the existing relay configs.

Current stack validation (November 6)

Real-model validation is now complete at stack head f0b200ce6568ff02cbc2d51a6dd5d46ccb3d6b5b in #5492. The resources_servers/finance_agent_v2/ implementation and tests are identical to this PR's current head; only README/config changes differ in the top PR. The resource suite passed 237 tests there, and full pre-commit checks passed (the unavailable private guardwords catalog was skipped). The entire selected stack validation passed 822 tests.

The canonical resources config passed a bounded real-NIM HTTP smoke with reward 1.0, actual policy/retrieval/judge calls, successful close responses, zero active agent state and empty captured document/time maps. The policy exercised parse, retrieval, calculator and submission; both rubric criteria passed through six real judge votes. The renamed resources seed map is covered by source/tests, not directly captured by that driver. See #5492's validation for the complete scope and compatibility notes.

This supersedes the earlier no-real-model statements below for the integrated stack. It does not establish standalone lower-PR episode activation, CLI collection, live SEC/Tavily/Tiingo coverage, full benchmark results or relay score parity. Historical evidence retains its original revision.

Historical validation

On 94df069a9:

  • gym env test --resources-server finance_agent_v2 (builds the server venv, runs its tests): exit 0, 218 passed. Rerun with resources_servers/finance_agent_v2/.venv/bin/python -m pytest resources_servers/finance_agent_v2/tests: 218 passed.
    • Includes check_resources_session_contract(..., keeps_state=True, holds_state=...) through the real routes (conflicting seed, conflicting close, cookie-less close after a lost seed reply, late seeds).
    • Plus 13 server-specific session tests: legacy route still {}, retried seed keeps documents, refused seed keeps the caller's cookie, close fences both seed routes, close for another episode gets 409, lost session 404 in-process and on the wire, stateless tools still answer, TTL eviction ends the routing claim and checkpoint tracking, retire, verify releases, verify without a session is scored.
  • pre-commit run --files on the three touched files: clean.
  • The commit is signed off.

Review fixes on 97f9555ba47a (team review)

Merged #4948's updated branch and applied the same fixes:

  • A agent-run seed for a session that holds a episode seed now answers 409, so a {} seed or a tool named seed_session cannot wipe its documents and time budget.
  • Tests: eviction through the public install_session_routing; the episode seed's cookie reaching the tools through the routes; the contract check with a verify body; a seed that keeps other sessions within their TTL; a re-sent verify before close. The never-seeded verify test is renamed test_verify_of_a_never_seeded_session_is_scored.

Validation at 97f9555ba47a: pytest resources_servers/finance_agent_v2/tests: 233 passed; resources_servers/finance_sec_search/tests: 111 passed; pre-commit run --files: passed. Not run: a real-model smoke (see below).

Review fixes on 5f0975c0c (second team review)

Merged #4948's updated branch (with main at 379ae226d) and applied the same fixes: the port to main's ResourcesSessionLocks / ResourcesSessionFences (after #5083 the merged server no longer imported), verify keeping an episode session's seed until its close, and session_expired masking for evicted sessions. Names follow #5083's glossary.

Validation at 5f0975c0c: pytest resources_servers/finance_agent_v2/tests with the server venv: 237 passed; resources_servers/finance_sec_search/tests: 116 passed; test_session_contract_repo.py + test_global_config.py: 233 passed; pre-commit run --files: clean. Not run: a real-model smoke.

Rollout evidence

No model endpoint or API key is configured on the machine that produced this stack, so there is no real-model rollout. Instead, an Environment Server plumbing smoke ran with a scripted OpenAI-compatible stub (policy, retrieval and judge) behind real openai_model servers, at #5492's head:

  • gym env start --config resources_servers/finance_agent_v2/configs/finance_agent_v2_single_agent_turn.yaml --model-type openai_model ..., then gym eval run --no-serve --agent finance_agent_v2 on the first row of data/example.jsonl.
  • Result type single_agent_turn_legacy, reward 1.0, no failure rows. The verifier made 27 judge calls (9 rubric criteria × 3 votes).
  • Tool sequence parse_html_page → retrieve_information → calculator → submit_final_result. retrieve_information answered from the document parse_html_page stored, so the episode seed's session reached both tools through the agent's direct HTTP grant.

This proves the wiring, not model quality.

🤖 Generated with Claude Code

finance_agent_v2 keeps per-rollout state (the documents parse_html_page
stores and each rollout's time budget) but served only the legacy seed, so
an Environment Server's typed seed got {} back, and it had no close, so a
rollout that never reached /verify kept its state for the server's
lifetime. This follows finance_sec_search (#4948), whose session code is
the same.

- /seed_session accepts ResourcesSeedSessionRequest as well as the legacy
  body. A typed seed is keyed by resources_session_id under the
  ResourcesSessionFence lock; a retry keeps the stored documents, and a
  seed that binds the ID to another episode or task gets 409. The cookie
  is bound only after those checks.
- close_resources_session releases the session by ID, with or without the
  cookie, and fences it so a late typed or legacy seed gets 409. A close
  for another episode gets 409. Verify still releases the session, since
  finance_agent's legacy /run never closes it. The score reads only the
  request (REVERIFY_MODE is stateless), so verify is not masked.
- parse_html_page and retrieve_information raise ResourcesSessionLostError
  (404) for a session that is not open instead of creating storage; the
  other tools ignore the session state and answer as before.
- A seed discards sessions older than session_ttl_seconds (default 6 h),
  and a checkpoint retire releases the retired attempt's session.

Closes GYMINT-170.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@yaoyu-33
yaoyu-33 added this pull request to stack #5493 November 3, 2026 05:58
@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 changed the title yuya/gymint 170 finance agent v2 sessions feat(finance_agent_v2): serve the typed resources sessions API Nov 3, 2026
@yaoyu-33 yaoyu-33 added feature New capabilities, enhancements, or enablement work area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers labels Nov 3, 2026
@yaoyu-33

yaoyu-33 commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 94df069

yaoyu-33 and others added 3 commits November 2, 2026 22:52
…losed

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
…gymint-170-finance-agent-v2-sessions

Brings in main via #4948 (12db466).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
yaoyu-33 added a commit that referenced this pull request Nov 3, 2026
…mint-134-finance-agent-sessions

Brings in main via #4948 and #5491 (511e5ed).

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 511e5ed

yaoyu-33 and others added 2 commits November 3, 2026 19:49
…ym.server_runtime

main removed nemo_gym.testing.session_conformance; the check now lives in the
server_runtime facade.

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

yaoyu-33 commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test f9a50e4

yaoyu-33 and others added 4 commits November 6, 2026 11:14
…gymint-170-finance-agent-v2-sessions

Signed-off-by: yaoyu-33 <[email protected]>
…gymint-170-finance-agent-v2-sessions

Signed-off-by: yaoyu-33 <[email protected]>
The same port as finance_sec_search: after merging main, the server imported
ResourcesSessionFence, which main's #5083 split into ResourcesSessionLocks and
ResourcesSessionFences.

- Use the locks and fences; the tests use owned_session_routing.
- Verify releases only an agent-run session; an episode session keeps its seed until
  its close, so a close that names another episode is refused after verify too.
- A session that outlived session_ttl_seconds is masked at verify as session_expired;
  an evicted episode session is fenced as after a close.
- Name sessions as main does: episode seed/session and agent-run seed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
…gymint-170-finance-agent-v2-sessions

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

yaoyu-33 commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 5f0975c

@yaoyu-33 yaoyu-33 changed the title feat(finance_agent_v2): serve the typed resources sessions API feat(finance_agent_v2): serve the resources sessions API Nov 6, 2026
@yaoyu-33
yaoyu-33 marked this pull request as ready for review November 6, 2026 20:56
@yaoyu-33 yaoyu-33 added the needs-review PR is ready for code review and waiting on a reviewer label Nov 6, 2026

@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

I found one expired-session routing defect, detailed inline, and a validation gap.

RISK — Provide the required real-model validation

The PR explicitly reports no real-model rollout. The scripted policy/retrieval/judge smoke establishes plumbing, but it doesn't meet the required representative real-model smoke validation. This PR also changes verification's score/mask decisions for a fixed benchmark that inherits this server, so the pinned rubric requires before/after reward-profiling evidence. The claimed absence of an unintended benchmark-number change remains unverified.

Could you run the existing benchmark recipe on base and head with the same representative tasks and real policy/judge configuration, inspect the tool and verifier behavior, and attach the revisions, commands, artifact locations, sample counts, reward summaries, and mask/failure counts? This needs validation evidence, not a speculative code patch.

Preservation and acceptance: Explain any reward or mask changes without weakening the intended lifecycle distinctions. Retain the existing assertions that episode verification preserves state until close, repeated verification before close stays unmasked, and never-seeded verification remains unmasked with reward 1.0 under the deterministic judge. Closed and expired sessions should remain masked.

I inspected all three changed files and traced the affected session routes, legacy agent caller, routing/checkpoint contracts, and mask aggregation. This was a static review; I didn't execute tests or rollouts.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

if participant is not None:
participant.ended(session_id)
if lifetimes is not None:
lifetimes.ended(session_id)

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.

RISK — Keep expiration metadata available after ownership ends

With multiple workers, this releases routing ownership before the expiration record stops affecting verification. For example, seed session s on worker A, let it exceed its TTL, and seed another session on A to evict it. A keeps s in _expired_session_ids for another TTL, but lifetimes.ended(s) makes its owner expire after the close retry window—5 minutes by default. The routing sweep then releases ownership, and a subsequent request can run on worker B. A stateful tool there returns 404, but /verify sees neither the expiration record nor a fence and scores the failed rollout normally. On A, the same verification would be masked as session_expired. This makes score inclusion depend on which worker receives the late request.

Correction: Coordinate _evict_stale_sessions' expiration-record retention and routing ownership: while an expiration record can cause verification to mask a session, every worker receiving that session must reach that record. Retain the owner until the record expires, or make the expiration record available across workers; release the corresponding tracking together. The exact routing implementation needs care, so I wouldn't suggest a one-line patch. Simply masking every absent session would break stateless reverify.

Preservation: Keep document/start-time cleanup and checkpoint termination at eviction. Preserve unmasked never-seeded verification, normal open-session scoring, and the fresh agent-run seed's clearing of its expired status. Any ownership-retention correction also needs to update the current eviction test, whose assertion currently requires ownership to disappear while the expiration record remains.

Proposed acceptance check, not executed: Run two server instances with the same configuration and shared routing directory, a short close retry window, and a longer session TTL. Seed and evict s on A, wait beyond the close retry window but remain within the expiration-record interval, then send a stateful tool call and verification through B using s's cookie. Expect 404 from the tool and mask_sample=true, failure_kind=session_expired, reward=0.0 from verification. Also retain the existing assertions that a never-seeded session scores unmasked with reward 1.0 and that a fresh agent-run seed clears expiration and scores normally.

@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team November 6, 2026 22:03
@yaoyu-33

yaoyu-33 commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test f0f8143

@yaoyu-33

Copy link
Copy Markdown
Contributor Author

/ok to test 1b8af5c

This branch was previously deployed

1 inactive (outdated) deployment
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 feature New capabilities, enhancements, or enablement work 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.

2 participants