Skip to content

feat(model): record agent instance, agent kind and model server on every capture and model-call record - #5250

Merged
cmunley1 merged 3 commits into
mainfrom
pranav/agent-instance-02-record-identity
Nov 17, 2026
Merged

cmunley1 merged 3 commits into
mainfrom
pranav/agent-instance-02-record-identity

Conversation

@pthombre

@pthombre pthombre commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

Several agent instances can call one model server in an episode, but nothing recorded which one made a call or which model server served it. This PR puts that identity on every record, so capture (PR 3) can keep agent instances apart and a trainer can select them. It is the design's "identity on every record", for the fields Gym has a source for today.

Field Written on When
agent_instance model-call records, TokenEntry, CallRecord, ManifestFailure, ledger intent, refusal and failure rows, the local store's intent and incomplete marks when the path names one
agent_kind the same when named; the part of the name before the dot
model_ref TokenEntry, CallRecord, ManifestFailure, ledger rows and marks (model-call records already carry it) always: the serving model server, from its own configuration, never from the request (G4)
  • CallIdentity (agent_instance + ModelRef) is carried on CaptureContext, which the capture middleware builds from the resolved path and the server's name. ModelRef has the shape and value of config_types.ModelServerRef; it lives in token_id_capture/records.py so capture records stay importable without Gym's configuration stack.
  • Writes take the identity: begin_call, refuse_call, record_failure and mark_incomplete take a keyword-only identity, and every caller in the sink, the external capture handlers, the model server and the vLLM model server passes the call's identity. commit_entry stamps it on every TokenEntry.
  • Failure attribution: a manifest failure written without an identity inherits it from its call's intent row. A failure with neither applies to the whole episode.
  • No null columns: TokenEntry, CallRecord, ManifestFailure and RolloutReceipt omit agent_instance, agent_kind and model_ref when unset, so a single-agent row serializes exactly as on main except for model_ref. The local store's intent and incomplete marks stay bare call ids unless the call has an identity.
  • RolloutReceipt.agent_instance (optional): None means the receipt covers the whole episode, as today. A trainer that builds one receipt per selected agent instance sets it.
  • Not in the staging digest: none of the new fields enters compute_staging_digest, so the digest version does not change.
  • x-session-id: the header name and its read move into nemo_gym.correlation; it is still recorded as client_session_id and not interpreted.
  • ModelCallRecord reads agent_instance and agent_kind.

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.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 MS,LG this
Loading
flowchart TB
  P["Path /ng-rollout/k/ng-agent-instance/judge.2/training-token-capture/v1/responses"] --> CTX["CaptureContext<br/>capture_key k<br/>identity: judge.2, model_ref policy"]
  CFG["Model server config<br/>name: policy"] --> CTX
  CTX --> I["intent row / mark"]
  CTX --> E["TokenEntry or CallRecord"]
  CTX --> F["failure row<br/>(inherits from the intent when written without one)"]
  CTX --> R["model-call record<br/>agent_instance, agent_kind, model_ref"]
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
  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
  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 (this PR)
  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

The first PR's base is main @ 0b8783981. External dependencies: #5083 (session lifecycle names, open) for PR 5. #4969 (rollout prefix hooks for fixed-base-URL clients, open) needs one small change in whichever of #4969 and PRs 1 and 4 lands second: with_rollout_prefix detects an existing prefix with resolve and takes the name from agent_instance_context.

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

Tests ran on Slurm (one node, rl-gym.nightly container), each branch against a baseline worktree of main @ 0b8783981:

  • Baseline core suite (python -m pytest -n 32 tests/unit_tests): 33 failed, 12,191 passed, 4 errors. Every one is environmental in this container (docker-compose, OpenSandbox compose, Harbor compose overlay, eval resubmit, reward profile, dataset orchestrator and sandbox supervisor tests, and four exporter modules that fail to import), and the same set fails on every branch of the stack. The docker-compose tests are flaky: one or two of them pass or fail from run to run.
  • Server-local suites ran in one venv per server built from its requirements.txt or pyproject.toml, as gym env test does.
  • pre-commit could not fetch its hook repositories from the build environment, so ruff check --fix, ruff check --select I --fix and ruff format ran with ruff 0.9.9 (the hook's pinned version) on every changed file. The guardwords and end-of-file hooks did not run here; CI runs them.
  • Every commit carries a Signed-off-by line.
  • Core suite on this branch's first head: 33 failed, 12,288 passed, 4 errors. One failure beyond the baseline, test_checkpoint_model.py::test_a_failed_publication_poisons_the_call_and_sends_no_answer, asserted a failure row without model_ref; its expectation now includes the call's identity, and the core suite of PR 3, whose branch contains the fixed commit, fails only the baseline set.
  • test_token_capture_ledger.py: on both ledger stores, unnamed rows carry only model_ref; one episode with assistant and judge.1 names its agent instance and agent kind on every row (calls, failures, intents, refusals); a failure written without a name inherits its intent's identity; a failure with neither stays episode-wide.
  • test_token_id_capture.py: two agent instances on one model server name every token entry, intent and model-call record; an unnamed call records only the model server, and its token entry, model-call record and intent line match main except for model_ref.
  • test_token_capture_staging_core.py: a RolloutReceipt without agent_instance validates and serializes as on main; one with it validates; the identity fields are not part of a CallRecord's digest and are omitted when unset.
  • test_correlation.py: x-session-id is read only when it has one non-empty value.

Rollout evidence

Not yet run. Before this leaves draft: smoke rollouts with capture on for one single-agent example and one multi-agent environment, checking agent_instance and model_ref in the ledger and model-call records.

Compatibility

  • New columns. Single-agent rows gain only model_ref. Like every column of the staging wire models (extra="forbid"), the new fields bind the model server and the framework to one Gym version, as source_capture_key and finish_reason already do.
  • Protocol change: an external CaptureLedger or TokenSink must accept the keyword-only identity on begin_call, refuse_call, record_failure and mark_incomplete. The in-repo implementations and conformance fakes are updated.
  • The local store's intent and incomplete files gain a JSON line form for calls with an identity; bare call-id lines are still read.

🤖 Generated with Claude Code

@pthombre pthombre added feature New capabilities, enhancements, or enablement work area:model Model servers, inference providers, and model adapters area:training Training framework integrations and training-data interfaces 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: checkpoint export loses inherited failure identity, and the transport conformance kit still accepts write signatures that runtime no longer supports.

Reviewed all 21 changed files and their directly affected contracts, callers, and failure paths. This was static source review; tests and smoke rollouts were not executed.


Inline comments (escaped v1):

  • nemo_gym/_checkpoint/model.py line 648: RISK — Preserve inherited failure identity across checkpoint export

    Failure: On a FileLineageStore, run begin_call("r1", "j1", identity=CallIdentity("judge.1", ModelRef(name="policy"))), then record_failure("r1", "j1", "worker_capture_failed") without identity. The live manifest attributes the failure correctly through the new intent fallback. However, export_model_records(store, [EpisodeId(rollout_id="r1")], [], {}) discards the intent here but retains the identity-free failure. After import_model_records into a fresh ledger, the failure loses its agent instance, kind, and model reference and becomes episode-wide. This affects checkpointed failures using the documented optional-identity contract.

    Correction: Could export materialize the manifest's inherited identity onto retained rows before removing intents? Keep removing intents—restoring them would resurrect dead calls as pending. Suggested replacement for the rows = [...] block in export_model_records, with CallIdentity imported from the capture records module:

    live_rows = ledger.export_rows(key)
    intent_identity = {
        row["model_call_id"]: CallIdentity.from_columns(row).columns()
        for row in live_rows if row.get("intent")
    }
    rows = [
        {
            **row,
            **intent_identity.get(row.get("model_call_id"), {}),
            **CallIdentity.from_columns(row).columns(),
        }
        if row.get("agent_instance") is None else row
        for row in live_rows
        if not row.get("intent")
        and not row.get("admissions_closed")
        and row.get("model_call_id") not in undelivered
    ]

    This preserves the existing fallback precedence without mutating the live ledger. Please verify the suggested code before adopting it.

    Preservation and proposed acceptance checks: Export/import the setup above and assert the restored failure identity is ("judge.1", "judge", ModelRef(name="policy")). Check separately that an explicitly named failure keeps its own identity, a model-only failure inherits the intent's agent while retaining its explicit model reference, and a failure without identity or intent stays episode-wide. Retain the existing checkpoint regression: restored pending IDs remain empty, the live ledger still reports "undelivered", and the delivered row keeps source_capture_key == "r1". These checks are proposed, not executed.

  • nemo_gym/token_id_capture/conformance.py line 256: RISK — Exercise the new write keyword in transport conformance checks

    Failure: An otherwise conforming external adapter retaining begin_call(rollout_id, model_call_id) or mark_incomplete(rollout_id, model_call_id="") can still pass run_conformance, because its write probes omit identity. But register_call_intent now always supplies the keyword, causing an old-signature adapter to raise TypeError before generation. Likewise, _mark_incomplete cannot persist a failure through an old-signature adapter. The protocol break is intentional; the defect is that the verification kit still certifies incompatible implementations.

    Correction: Could the existing probes mirror runtime arguments? Import CallIdentity and ModelRef, and define:

    _CALL_IDENTITY = CallIdentity(
        agent_instance="judge.1", model_ref=ModelRef(name="conformance-model")
    )

    Replace this call with:

    await sink.mark_incomplete(rollout_id, "call-2", identity=_CALL_IDENTITY)

    Also supply identity=_CALL_IDENTITY to the mark(...) and begin(...) probes in retirement checks and intent/refusal checks. Passing the kit must require accepting the write arguments Gym actually sends.

    Preservation: Keep begin_call optional, so sinks without it still skip those checks. Do not add this keyword to record_engine_refusal, whose contract did not change. Preserve retirement fences, refusal resolution, and stale-snapshot version assertions.

    Proposed acceptance checks: Wrap the working file store with an override async def begin_call(self, rollout_id, model_call_id) that forwards to the store; the kit must reject it with ConformanceError. Separately override the working memory sink's mark_incomplete with its old signature; the kit must reject it at mark_incomplete_durability. The updated file and memory backends must still pass. Preserve the memory test's skipped-extension assertions and the intent-only sink's successful custody check plus refusal warning. These are source-derived proposed checks, not executed results; verify the suggested changes before adopting them.

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

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

This breaks test_cancelled_chat_keepalive_retains_uncertain_capture[True] in responses_api_models/vllm_model/tests/test_framework_context.py (passes on the base commit, fails at this head). Its stub delayed_failure(*args) replaces ledger.record_failure and now gets identity=. The TypeError is swallowed in _fail_uncommitted_external_call and logged as "Could not poison uncommitted call", so no failure row is written. The test fix is *args, **kwargs. The silent swallow is the same pattern as the conformance gap: a wrapper that drops a new keyword loses the failure instead of failing loudly.

@cmunley1

Copy link
Copy Markdown
Contributor

/ok to test 3c5f4fc

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team October 30, 2026 03:32
@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Oct 30, 2026
@github-actions github-actions Bot added sla:review-overdue Review response is over the one-business-day SLA and removed sla:review-overdue Review response is over the one-business-day SLA labels Oct 30, 2026
@pthombre
pthombre force-pushed the pranav/agent-instance-02-record-identity branch from 3c5f4fc to 6d74fc6 Compare November 2, 2026 22:29
@pthombre
pthombre force-pushed the pranav/agent-instance-02-record-identity branch from 60a071c to 54ede9d Compare November 4, 2026 01:33
@ananthsub
ananthsub force-pushed the pranav/agent-instance-02-record-identity branch from 54ede9d to 87e9475 Compare November 4, 2026 06:08
Base automatically changed from pranav/agent-instance-01-correlation-module to main November 10, 2026 17:26
pthombre and others added 2 commits November 15, 2026 08:07
…ery capture and model-call record

Every capture and model-call record now says who made the call and which
model server served it:

- `agent_instance` and `agent_kind` come from the `/ng-agent-instance/<name>`
  path segment and are written only when a name is present, so single-agent
  rows carry no null columns.
- `model_ref` comes from the serving model server's own configuration, never
  from the request, and is written on every row. It has the shape and value
  of the `model_ref` on model-call records.

They are carried on CaptureContext and written onto TokenEntry, CallRecord,
ManifestFailure, ledger intent, refusal and failure rows, the local store's
intent and incomplete marks, and model-call records (ModelCallRecord reads
them). begin_call, refuse_call, record_failure and mark_incomplete take a
keyword-only `identity` (CallIdentity). A manifest failure written without
an identity inherits it from its call's intent row; a failure with neither
applies to the whole episode.

RolloutReceipt gains an optional `agent_instance`; `None` means the receipt
covers the whole episode and serializes as before. None of the new fields
enter the staging digest.

The `x-session-id` header name and its read move into nemo_gym.correlation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Prashant Thombre <[email protected]>
…nt line, and test every identity write site

- conformance kit: pass an identity on its begin_call and mark_incomplete probes, as Gym does at runtime
- local store: read a torn JSON intent line as an unresolved call, so the rollout freezes incomplete instead of raising
- tests: cover each site that writes the call identity, and the two fixes above

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
…nd carry agent_kind on trajectory model calls

- checkpoint: export copies the identity a row reads from its call's intent onto the row, since the intents stay with the old attempt; a restored failure no longer turns episode-wide
- trajectory: TrajectoryModelCall has agent_kind beside agent_instance, the collector copies it from the captured call, and the 1.0 projection drops it
- docs: say which records leave out the identity of an unnamed agent and which write null, and that rollout_id and capture_key are one value

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Signed-off-by: Pranav Thombre <[email protected]>
@pthombre

Copy link
Copy Markdown
Contributor Author

Reply to the automated review (both RISK findings), now at 613ae73, rebased onto current main:

1. Checkpoint export loses inherited failure identity — fixed in 613ae73. export_model_records copies the identity a row reads from its call's intent onto the row before the intents are left behind, so a restored failure keeps its agent instance, kind and model reference. Intents are still not exported. test_checkpoint_export_keeps_the_identity_a_failure_inherits_from_its_intent covers the four cases listed: inherited, explicitly named, model-only (keeps its own model reference, inherits the agent), and no intent (stays episode-wide). The existing test_checkpoint_restores_delivered_calls_without_dead_attempt_intents is unchanged and passes.

2. Conformance kit does not exercise the new write keyword — fixed in 7655146. Every begin_call and mark_incomplete probe now passes an identity, as Gym does at runtime. test_kit_rejects_a_sink_whose_begin_call_takes_no_identity and test_kit_rejects_a_sink_whose_mark_incomplete_takes_no_identity check that an adapter with the old signature fails the kit. record_engine_refusal is untouched, and begin_call stays optional.

Validation: the core unit suite at this head, run on Slurm against main (951ee9e) in the same environment, has no failure that main does not also have.

@pthombre

Copy link
Copy Markdown
Contributor Author

@cmunley1 thanks for catching this.

  • Broken test: fixed in 7655146. The delayed_failure stub in test_cancelled_chat_keepalive_retains_uncertain_capture now takes (*args, **kwargs) and forwards identity=.
  • Conformance gap: the kit's begin_call and mark_incomplete probes now pass an identity, so an adapter that kept the old signature fails the kit instead of passing it and breaking at runtime.
  • Silent swallow in _fail_uncommitted_external_call: I left the handler as it is. It logs at error level with the traceback, and it is the boundary where a capture problem must not fail the model request, so raising there would turn a bookkeeping failure into a failed generation. If you would rather it fail loudly, I can change it; tell me which you prefer.

The branch is rebased onto current main; the new head is 613ae73.

@pthombre

Copy link
Copy Markdown
Contributor Author

@marcromeyn thanks, all three are in 613ae73:

  1. Identity on ng_trajectory: TrajectoryModelCall already had a nullable agent_instance on main, and the projection copies it. I added a nullable agent_kind beside it and copy it from the captured call. The 1.0 projection drops it, as it drops agent_instance. Tests: test_trajectory_model_call_carries_the_captured_agent_instance_and_kind and test_v1_projection_drops_the_agent_identity_of_a_model_call.
  2. Omitted vs null: omitting is deliberate, so a record of an unnamed agent keeps the shape it had before these fields existed. I documented it instead of changing it: model-server/model-call-capture.mdx now says that the raw record and the training-token records (ledger rows, manifest records and failures, receipts) leave the fields out for an unnamed agent, that ModelCallRecord writes null, and that readers should treat the two the same.
  3. rollout_id vs capture_key: observability/rollout-evidence.mdx now says they are the same value.

If the health checks or EvalRDL would be simpler with null everywhere, say so and I will switch the raw records.

@pthombre

Copy link
Copy Markdown
Contributor Author

/ok to test 613ae73

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 16, 2026 23:05
@github-actions

Copy link
Copy Markdown
Contributor

@cmunley1
cmunley1 added this pull request to the merge queue Nov 17, 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/44022114561

Merged via the queue into main with commit cd899ca Nov 17, 2026
78 checks passed
@cmunley1
cmunley1 deleted the pranav/agent-instance-02-record-identity branch November 17, 2026 05:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:model Model servers, inference providers, and model adapters area:training Training framework integrations and training-data interfaces 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 sla:review-overdue Review response is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants