Skip to content

feat(core): add a correlation module that reads and builds the rollout path - #5249

Merged
pthombre merged 2 commits into
mainfrom
pranav/agent-instance-01-correlation-module
Nov 10, 2026
Merged

pthombre merged 2 commits into
mainfrom
pranav/agent-instance-01-correlation-module

Conversation

@pthombre

@pthombre pthombre commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

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 adds nemo_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-rollout/<capture key>[/ng-agent-instance/<name>][/training-token-capture][/ng-trace/<traceparent>]/v1/...
  • Grammar. The segments appear in that fixed order; a path may also carry only /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) or v1, 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 frozen CorrelationContext (capture_key, agent_instance, derived agent_kind, token_capture, trace_parent) and the remaining path, or None when 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.
  • Resolve once per request. 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 through scope["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 in detail, 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.
  • Moved onto the module: the capture middleware's _ROLLOUT_PATH_RE, the trace middleware's _ROLLOUT_PREFIX_PATTERN / _TRACE_CONTEXT_PATH_RE, the trace redirect rewrite (_restore_trace_segment_on_redirect), and rollout_path_prefix / apply_rollout_prefix / trace_context_path_segment, which keep their signatures and build through encode. with_rollout_prefix (from feat(telemetry): let fixed-base-URL clients name their rollout in the request URL #4969) now detects an existing prefix with parse_path(rest, allow_empty_rest=True) and leaves a malformed one for the receiving server to answer.
  • resolve reads only the path. Header identity (x-session-id from 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.&lt;id&gt; 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 this
Loading

One request through Gym's middleware:

sequenceDiagram
  participant C as Client
  participant T as TraceContextPathMiddleware
  participant M as Capture middleware (model server)
  participant H as Handler
  C->>T: POST /ng-rollout/k/ng-agent-instance/judge/ng-trace/tp/v1/responses
  Note over T: resolve(scope) once, a malformed prefix gets 404
  T->>T: traceparent header from the segment
  T->>M: path /ng-rollout/k/ng-agent-instance/judge/v1/responses, resolution in scope state
  Note over M: reads the stored resolution: capture key k, agent instance judge
  M->>H: routed path /v1/responses, rollout context k
Loading

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 /run names no agent instance, and its records differ from main only by the new model_ref column.

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.

  1. refactor(capture): name capture keys capture_key on the ledger control surface #5248 (pranav/agent-instance-00-capture-key-rename): refactor(capture): name capture keys capture_key on the ledger control surface (merged, f96e82433)
  2. feat(core): add a correlation module that reads and builds the rollout path #5249 (pranav/agent-instance-01-correlation-module): feat(core): add a correlation module that reads and builds the rollout path (this PR)
  3. feat(model): record agent instance, agent kind and model server on every capture and model-call record #5250 (pranav/agent-instance-02-record-identity): feat(model): record agent instance, agent kind and model server on every capture and model-call record
  4. feat(capture): compute lineage, terminal chains and outcomes per agent instance and model server #5251 (pranav/agent-instance-03-per-agent-capture): feat(capture): compute lineage, terminal chains and outcomes per agent instance and model server
  5. feat(core): let callers name an agent instance on model calls #5252 (pranav/agent-instance-04-direct-call-names): feat(core): let callers name an agent instance on model calls
  6. feat(agent): bind agent sessions to an agent instance at seed time #5253 (pranav/agent-instance-05-agent-session-binding): feat(agent): bind agent sessions to an agent instance at seed time
  7. feat(episode): report terminal calls and rewards per agent instance #5254 (pranav/agent-instance-06-per-agent-results): feat(episode): report terminal calls and rewards per agent instance
  8. refactor(core): read and build every rollout path through the correlation module #5255 (pranav/agent-instance-07-migrate-readers): refactor(core): read and build every rollout path through the correlation module

This 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). The with_rollout_prefix change that #4969 needed is in this PR.

Follow-ups the stack does not cover yet:

The NeMo RL follow-up (selecting agent instances to train on, one RolloutReceipt per 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):

  • Touched suites (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 on main @ 710938e6c in 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 16 and pass in isolation on both trees.
  • ruff check and ruff format --check are clean on every changed file (ruff 0.12.11; pre-commit pins 0.9.9 and runs in CI). Every commit carries a Signed-off-by line.
  • test_correlation.py (new): every combination of segments round-trips through encode and resolve; 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 raise CorrelationPathError; a name or traceparent ending in a newline raises; a malformed bare prefix raises with either allow_empty_rest setting; CorrelationContext takes keyword arguments only; resolve reads 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_segment returns "" 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_prefix leaves 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.
  • The checkpoint admission reader and Switchyard's session middleware still find the capture key when a name follows it (they move onto the module in refactor(core): read and build every rollout path through the correlation module #5255).
  • The Slurm core-suite run in the earlier version of this description predates the rebase and needs to be repeated.

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 detail and a warning log.

Compatibility

  • Malformed prefixes keep 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.
  • Two forms that routed and captured on main now 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-capture to an apply_rollout_prefix URL must put it before /ng-trace.
  • rollout_path_prefix and apply_rollout_prefix raise ValueError for a capture key containing /, where main built a path that did not route.
  • Every other valid URL, including every URL Gym builds today, behaves exactly as before.

🤖 Generated with Claude Code

@pthombre pthombre added feature New capabilities, enhancements, or enablement work area:core Shared APIs, servers, telemetry, health, and registries complexity:medium Single-domain change with interacting parts or a moderate review surface labels Oct 29, 2026
@copy-pr-bot

copy-pr-bot Bot commented Oct 29, 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.

@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 — 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.

Comment thread nemo_gym/core/correlation.py Resolved
Comment thread nemo_gym/core/correlation.py Resolved

@cmunley1 cmunley1 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.

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?

@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Oct 30, 2026
@pthombre
pthombre force-pushed the pranav/agent-instance-01-correlation-module branch from 795d5af to 160b9c9 Compare November 2, 2026 22:29
@pthombre
pthombre force-pushed the pranav/agent-instance-01-correlation-module branch from 160b9c9 to 57a519d Compare November 3, 2026 00:03
@pthombre
pthombre force-pushed the pranav/agent-instance-01-correlation-module branch from 57a519d to 4a60107 Compare November 3, 2026 14:13
@pthombre
pthombre force-pushed the pranav/agent-instance-01-correlation-module branch from 4a60107 to 6479214 Compare November 3, 2026 15:07
@pthombre
pthombre force-pushed the pranav/agent-instance-01-correlation-module branch from 6479214 to 0e0aae8 Compare November 3, 2026 15:22
Comment thread nemo_gym/core/correlation.py Resolved
@github-actions github-actions Bot removed the sla:review-overdue Review response is over the one-business-day SLA label Nov 5, 2026
@pthombre
pthombre force-pushed the pranav/agent-instance-01-correlation-module branch from 9e12d11 to 109a8e8 Compare November 9, 2026 21:31
pthombre and others added 2 commits November 9, 2026 13:38
…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]>
@pthombre
pthombre force-pushed the pranav/agent-instance-01-correlation-module branch from 109a8e8 to 9e4a1f7 Compare November 9, 2026 21:39
@pthombre

pthombre commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 9e4a1f7

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

@ananthsub ananthsub 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.

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 remember coverage: 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#L852 raises HTTPException(400), and external-agent-harnesses.mdx#L162 says "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/responses keeps 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):

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.

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():

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.

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

@ananthsub ananthsub 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.

Approving. The capture key rule and the remember test can follow as discussed on the placement thread.

@pthombre
pthombre 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/42861249712

Merged via the queue into main with commit 736f9d7 Nov 10, 2026
186 of 194 checks passed
@pthombre
pthombre deleted the pranav/agent-instance-01-correlation-module branch November 10, 2026 17:26

This branch was previously deployed

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

Labels

area:core Shared APIs, servers, telemetry, health, and registries complexity:medium Single-domain change with interacting parts or a moderate review surface 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.

4 participants