Repository navigation
feat(core): add a correlation module that reads and builds the rollout path - #5249
Conversation
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP WITH CARE — two RISK findings in correlation-prefix validation.
Reviewed all seven changed files and traced URL construction, trace rewriting, capture routing, redirects, and checkpoint/Switchyard readers. The findings concern malformed inputs; no broader production or security impact is demonstrated.
Review complete. Tests were inspected, not executed. Suggested changes require author verification.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
cmunley1
left a comment
There was a problem hiding this comment.
Beyond the bot's two notes: malformed prefixes moved from 404 (routing) to 400 here. AgentOutcomePolicyConfig maps 400 to VERIFY (agent_outcome.py:83), so a harness that builds a bad prefix (doubled /ng-rollout, ng-trace first) gets its episode graded 0 and kept for training. The old 404 fell through to FAIL and stayed ungraded. Nothing in this PR emits a malformed prefix, but a URL bug in a harness or a later PR would turn into silent training signal. Should we consider returning a status the outcome policy treats as an infra failure, or mapping CorrelationPathError there?
795d5af to
160b9c9
Compare
160b9c9 to
57a519d
Compare
57a519d to
4a60107
Compare
4a60107 to
6479214
Compare
6479214 to
0e0aae8
Compare
9e12d11 to
109a8e8
Compare
…t path
Add nemo_gym/core/correlation.py, the one place that reads and builds the request
path prefix:
/ng-rollout/<key>[/ng-agent-instance/<name>][/training-token-capture][/ng-trace/<tp>]/v1/...
- `resolve(scope)` returns the context the path carries and the remaining
path; `encode(context)` builds the prefix. A segment out of order or
repeated, a missing value, or an invalid agent instance name or
traceparent raises CorrelationPathError.
- Agent instance names are `<agent kind>[.<n>]` and may not equal a segment
literal or `v1`.
- TraceContextPathMiddleware, the outermost layer on every Gym server,
resolves each request once and shares the result through scope["state"];
the model server's capture middleware reads it instead of parsing again.
- The capture middleware, the trace middleware, the trace redirect rewrite,
rollout_path_prefix and apply_rollout_prefix move onto the module.
The model server accepts and strips an agent instance name but does not
record it yet. Valid URLs behave as before. A malformed correlation prefix
now gets 400 instead of 404.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Prashant Thombre <[email protected]>
- Rebase onto main: with_rollout_prefix (#4969) detects an existing prefix with parse_path(rest, allow_empty_rest=True) instead of the deleted _ROLLOUT_PREFIX_RE, which broke importing base_server. - A malformed correlation prefix keeps main's 404, which the agent outcome policy does not grade, now with the reason in the body and a warning log at both the trace and capture middleware. - Match agent instance names and traceparents whole (\Z, fullmatch), and validate before the empty-rest return, so a malformed value raises whether or not a path follows the prefix. - resolve() leaves scope["state"] untouched for paths without a prefix and for non-http scopes. CorrelationContext is keyword-only. The reserved names derive from the segment literals. - The trace middleware cuts the trace segment out of the path; the redirect rewrite leaves a target with a malformed prefix untouched. - Correct docstrings, and test a named training prefix through both middlewares (token capture and redirect). Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Pranav Prashant Thombre <[email protected]>
109a8e8 to
9e4a1f7
Compare
|
/ok to test 9e4a1f7 |
ananthsub
left a comment
There was a problem hiding this comment.
Thanks for the quick turnaround. Every item from the last round holds at this head; I re-ran each original case, and the replies on those threads say what I checked. Nothing here blocks merge.
- Capture key rule and
remembercoverage: reply on the placement thread. - Two optional test tightenings: inline.
- The upper PRs still expect 400. At #5255's head, the tests at L1407 and L1470 assert 400,
base_responses_api_agent.py#L852raisesHTTPException(400), andexternal-agent-harnesses.mdx#L162says "HTTP 400". They need updating when the stack is rebased onto this head. - Overlap with #5463 and #5562. Both add a
/ng-sampling/segment through their own regexes. With this grammar,/ng-rollout/0-0/ng-sampling/null/ng-trace/<traceparent>/v1/responseskeeps the trace segment in the routed path, and #5463's middleware then answers 422. #5463 edits_TRACE_CONTEXT_PATH_RE, which this PR deletes, so whichever lands second gets a conflict. That one should add the sampling segment as a fixed slot in this grammar rather than a separate regex. - Description: the follow-up bullet says session routing and
simple_agent"move in #5255 before #5253", but #5255 does not move them and sits above #5253.
Validation: the touched test files at this head with the CI extras, the original cases from each thread, mutation runs on the new tests, and the #5463 path through both middlewares.
| "/ng-rollout/3-0/ng-agent-instance/Judge/v1/chat/completions", | ||
| ], | ||
| ) | ||
| def test_a_malformed_prefix_is_refused_with_404(path, with_trace_middleware): |
There was a problem hiding this comment.
The warning log is not asserted at either site. Dropping the logger.warning in trace_context.py or in model_call_capture.py passes every test, and the log is the only record of a refused request. Optional, but this pins which middleware refused it:
def test_a_malformed_prefix_is_refused_with_404(path, with_trace_middleware, caplog):
...
with caplog.at_level(logging.WARNING):
response = TestClient(app).post(path, json={})
assert response.status_code == 404
assert path in response.json()["detail"]
refusing = (
"nemo_gym.server_runtime.request_handling.trace_context"
if with_trace_middleware
else "nemo_gym.models.model_call_capture"
)
assert [r.name for r in caplog.records if "malformed correlation prefix" in r.getMessage()] == [refusing]Each mutant fails with this change, and the test passes at this head.
| assert resolve(rewritten) == (CorrelationContext(capture_key="k"), "/v1/responses") | ||
|
|
||
|
|
||
| def test_resolve_ignores_non_http_scopes(): |
There was a problem hiding this comment.
A lifespan scope has no path, so this test passes without the http check. Removing the type check in resolve passes every test. Optional: a websocket scope with a path fails without the check.
@pytest.mark.parametrize(
"scope",
[{"type": "lifespan"}, {"type": "websocket", "path": "/ng-rollout/k/ng-agent-instance/Judge/v1/responses"}],
)
def test_resolve_ignores_non_http_scopes(scope):
assert resolve(scope) is None
assert "state" not in scope|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42861249712 |
What changed and why
The
/ng-rollout/...path prefix was read by three hand-written regexes (the model server's capture reader, the trace middleware, the trace redirect rewrite) and built by hand in two helpers. The next PRs add a segment that names the agent instance making a call, so the grammar needs one owner. This PR addsnemo_gym/core/correlation.py, which reads and builds the prefix, and moves those readers and builders onto it. It is the design's "one resolver" (G1), for the path./ng-trace/<traceparent>. An agent instance name is<agent kind>[.<n>]and matches^[a-z][a-z0-9_-]*(?:\.[a-z0-9_-]+)?\Z(assistant,judge,user,debater.1). A name may not equal a segment literal (ng-rollout,ng-agent-instance,training-token-capture,ng-trace) orv1, so a missing name can never swallow the next segment. Names and traceparents are matched whole (\Z, so a trailing newline is rejected), and a malformed value raises whether or not a path follows the prefix.resolve(scope)returns a frozenCorrelationContext(capture_key,agent_instance, derivedagent_kind,token_capture,trace_parent) and the remaining path, orNonewhen the path carries no prefix. A segment out of order or repeated, a missing value, or an invalid name or traceparent raises one typed error,CorrelationPathError, with a reason.encode(context)builds the prefix;encode(resolve(path)[0]) + rest == path.TraceContextPathMiddleware, the outermost layer that reads the path on every Gym server (request-context isolation is outside it), resolves the path and shares the result throughscope["state"]; after it cuts the trace segment out it stores the resolution of the rewritten path, so the model server's capture middleware reads the stored context instead of parsing again. The cache is keyed by path and skipped for paths that do not start with/ng-and for non-http scopes. A malformed prefix is answered there with 404, the reason indetail, and a warning log. Resources and agent servers still read the path with their own readers until refactor(core): read and build every rollout path through the correlation module #5255._ROLLOUT_PATH_RE, the trace middleware's_ROLLOUT_PREFIX_PATTERN/_TRACE_CONTEXT_PATH_RE, the trace redirect rewrite (_restore_trace_segment_on_redirect), androllout_path_prefix/apply_rollout_prefix/trace_context_path_segment, which keep their signatures and build throughencode.with_rollout_prefix(from feat(telemetry): let fixed-base-URL clients name their rollout in the request URL #4969) now detects an existing prefix withparse_path(rest, allow_empty_rest=True)and leaves a malformed one for the receiving server to answer.resolvereads only the path. Header identity (x-session-idfrom feat(model): record agent instance, agent kind and model server on every capture and model-call record #5250, vendor mappings,x-ng-request-id,x-ng-context) is read separately.After this PR the model server accepts and strips an agent instance name but does not record it; PR 2 records it.
How it works
Where this PR sits in the overall flow; the highlighted part is what this PR changes.
flowchart LR ENV["Environment server<br/>seeds and activates agent sessions"] AG["Agent server<br/>session bound to its agent instance"] RS["Resources server<br/>verify(), judges"] MS["Model server<br/>capture middleware"] CM["nemo_gym.core.correlation<br/>resolve / encode"] LG[("Capture ledger and token store<br/>rows carry agent_instance, model_ref")] DL["Delivery and manifest<br/>chains and outcomes per agent instance"] RR["Episode result<br/>agent_instances map"] ENV -->|"/ng-rollout/k/ng-agent-instance/user/v1/responses"| AG AG -->|"model calls named user"| MS RS -->|"verify.<id> and judge calls"| MS MS --> CM MS --> LG --> DL --> RR ENV --> RR classDef this fill:#fde68a,stroke:#b45309,stroke-width:2px,color:#1f2937 class CM,MS thisOne request through Gym's middleware:
Where this sits in the stack
This is one PR in a stack of draft PRs that implements agent instance identity from the Gym capture identity design (draft 2): several agent instances (assistant, judge, simulated user, debaters) can call model servers in one episode, every record says which one made each call, capture computes lineage and outcomes per agent instance, and the trainer chooses which agent instances it trains on. Gym records; trainers select. Single-agent episodes do not change: an agent's own
/runnames no agent instance, and its records differ frommainonly by the newmodel_refcolumn.Each PR is one commit, and its base is the branch of the PR before it, so each diff shows only that PR's change.
pranav/agent-instance-00-capture-key-rename): refactor(capture): name capture keys capture_key on the ledger control surface (merged,f96e82433)pranav/agent-instance-01-correlation-module): feat(core): add a correlation module that reads and builds the rollout path (this PR)pranav/agent-instance-02-record-identity): feat(model): record agent instance, agent kind and model server on every capture and model-call recordpranav/agent-instance-03-per-agent-capture): feat(capture): compute lineage, terminal chains and outcomes per agent instance and model serverpranav/agent-instance-04-direct-call-names): feat(core): let callers name an agent instance on model callspranav/agent-instance-05-agent-session-binding): feat(agent): bind agent sessions to an agent instance at seed timepranav/agent-instance-06-per-agent-results): feat(episode): report terminal calls and rewards per agent instancepranav/agent-instance-07-migrate-readers): refactor(core): read and build every rollout path through the correlation moduleThis PR is rebased onto
main@710938e6c; #5248 has merged. Both external dependencies have merged too: #5083 (session lifecycle names,0f64fca48) and #4969 (rollout prefix hooks for fixed-base-URL clients,cc8991e4c). Thewith_rollout_prefixchange that #4969 needed is in this PR.Follow-ups the stack does not cover yet:
with_rollout_prefix,rollout_prefix_hook) add only the capture key. They should take anagent_instanceargument and build throughencode, so judge calls fromServerClient(the verifier header) carryverify.<id>after feat(core): let callers name an agent instance on model calls #5252.session_routing._ROLLOUT_PREFIXand simple_agent's_ROLLOUT_PREFIX_SUFFIXstill parse the path by hand, and refactor(core): read and build every rollout path through the correlation module #5255 does not move them. Session routing allows one segment after the capture key, so it would not match named prefixes; both move in refactor(core): read and build every rollout path through the correlation module #5255 before feat(agent): bind agent sessions to an agent instance at seed time #5253 sends named URLs to agent servers.The NeMo RL follow-up (selecting agent instances to train on, one
RolloutReceiptper selected agent instance, per-agent rewards) is separate; until NeMo RL bumps its Gym pin, none of these PRs affect NeMo RL training runs.Issue
No tracking issue exists; the work follows the Gym capture identity design (draft 2) and its implementation plan.
Validation
After the rebase onto
main@710938e6c, run locally (CPU, Python 3.13,uv sync --extra dev --extra telemetry):test_correlation.py,test_trace_context_path.py,test_base_responses_api_model.py,test_observer.py,test_rollout_url_prefix.py,test_moved_paths.py): 378 passed.tests/unit_tests/{core,server_runtime,telemetry,models,client}plus the import-linter and public API tests: 5418 passed. The failures and errors are the same set that fails onmain@710938e6cin this environment (checkpoint participant workers, checkpoint sequences, session routing, runtime dir: Unix sockets in the sandbox). Three timing tests failed in one run or the other under-n 16and pass in isolation on both trees.ruff checkandruff format --checkare clean on every changed file (ruff 0.12.11; pre-commit pins 0.9.9 and runs in CI). Every commit carries aSigned-off-byline.test_correlation.py(new): every combination of segments round-trips throughencodeandresolve; trace-only paths; paths without a prefix or without a rest; out-of-order, repeated and value-less segments, invalid and reserved names and an invalid traceparent each raiseCorrelationPathError; a name or traceparent ending in a newline raises; a malformed bare prefix raises with eitherallow_empty_restsetting;CorrelationContexttakes keyword arguments only;resolvereads a path once, re-reads a changed path, and leaves unprefixed and non-http scopes untouched.test_trace_context_path.py: a named prefix with a trace segment is stripped to the named prefix; malformed prefixes, including newline values and bare prefixes, get 404 without reaching the app; the redirect rewrite puts the trace segment after a named prefix and leaves a target with a malformed prefix untouched;trace_context_path_segmentreturns""for a traceparent with a trailing newline.test_base_responses_api_model.py: a named URL with a trace segment passes through both middlewares and routes; a named prefix with the training segment, with and without a trace segment, opens token capture and a redirect keeps the full prefix; a malformed prefix gets 404 with and without the trace middleware.test_rollout_url_prefix.py:with_rollout_prefixleaves a named prefix, a bare/ng-rollout/<key>and a malformed prefix alone, and puts the capture key in front of a trace-only path.Rollout evidence
N/A: every URL Gym builds routes and captures exactly as before. A malformed prefix still gets 404, now with the reason in
detailand a warning log.Compatibility
main's 404 (which the agent outcome policy treats as an ungraded failure), now with{"detail": <reason>}and a warning log: segments out of order or repeated, an invalid agent instance name, an invalid/ng-trace/value.mainnow get 404: the trace segment before the training segment (/ng-rollout/<key>/ng-trace/<tp>/training-token-capture/v1/...) and the trace segment first (/ng-trace/<tp>/ng-rollout/<key>/v1/...). No Gym builder emits them; a client that appends/training-token-captureto anapply_rollout_prefixURL must put it before/ng-trace.rollout_path_prefixandapply_rollout_prefixraiseValueErrorfor a capture key containing/, wheremainbuilt a path that did not route.🤖 Generated with Claude Code