Repository navigation
feat(capture): compute lineage, terminal chains and outcomes per agent instance and model server - #5251
Conversation
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
HOLD — three BLOCKERs can substitute another agent’s tokens or lose required failure masking. Three RISKs affect terminal attribution, context measurement, and filtered manifests.
Reviewed all 19 changed files and their directly affected callers, contracts, and regression tests. This was static inspection; no tests were executed. One delegated report was unavailable, so its manifest/startup/terminal-helper area was re-inspected directly.
NOTE — Document the new framework-consumer contract. Suggest adding a compact subsection to the external-harness integration guide. It currently describes rollout-wide reconstruction without explaining the new per-agent builds, primary-agent precedence, or manifest filters and resolver identity keywords. These are observable integration changes; the pinned rubric requires documentation for notable user-facing features. Keep the existing unnamed single-agent workflow intact, and distinguish the returned build map from what the existing finalizer persists. Acceptance is a static documentation check: include a minimal per-agent build/filter example, explain episode-wide versus agent-specific incompleteness, and identify the required custom-resolver signature update.
Note: formal approval is not available for this request, so this review is posted as a comment only.
Inline comments (escaped v1):
-
nemo_gym/token_id_capture/consumer.pyline 320: BLOCKER — A completely lost assistant capture promotes the judge into the training sample.Failure: Retain one clean judge entry and an unmatched assistant intent. Using the existing fixture,
_freeze_and_build(tmp_path, [judge_call], intents=[("a1", ASSISTANT)])producesincomplete_agent_instances={"assistant"}, but this roster contains onlyjudge. The sole-agent fallback selects it, andincomplete_for("judge")is false. The top-level result therefore contains judge tokens withmask_sample=False, rather than a failed assistant build. Finalization can replace the scored response’s output with those tokens while preserving its reward.Correction: Include known incomplete agents before primary selection and emit a failed build for agents with no entries. A known incomplete primary must not be replaced by another captured agent. Suggested changes, to verify before adopting:
Replace the opening empty-entry branch and roster assignment in
_build_snapshotwith:agents = by_agent_instance(group_entries(snapshot.entries).items(), key=lambda item: item[0]) for name in snapshot.incomplete_agent_instances: agents.setdefault(name, []) if not agents: built = _failed_build(rollout_id, builder, "capture contains no token records") _apply_snapshot_outcome(built, snapshot, None, always=mask_incomplete_when_attributed) return built
At the start of its per-agent loop, before
_assemble_agent_instance, add:if not groups: built = _failed_build(rollout_id, builder, "capture contains no token records for agent instance") _apply_snapshot_outcome(built, snapshot, agent_instance, always=mask_incomplete_when_attributed) builds[agent_instance] = built continue
Preservation / acceptance — proposed, not run: The trigger must return a masked top-level result with no rebuilt response and a separate unmasked judge build, under both incomplete-mask settings. Captured assistant plus lost judge must retain the existing unmasked-assistant assertions. A genuinely sole named judge must still be eligible as primary; unnamed-primary precedence and the flat unnamed result must remain unchanged. An entirely empty snapshot with known incomplete agents must produce failed builds without indexing an empty group list.
-
nemo_gym/token_id_capture/consumer.pyline 273: RISK — Independent terminal attribution per model server rejects an attributable sample.Failure: One assistant has two root calls on
policyandpolicy-b, with identical output text but different token sequences and response IDs. Supply a verified response whose ID uniquely names the second call and whose output contains that shared text. The first group attributes by content despite its response-ID miss; the second attributes by ID and content. Both reportchain="delivered", so the group selection masks the sample. Across the assistant’s complete candidate set, the existing resolver would make the ambiguous content witness abstain and retain the unique response-ID witness.Correction: Resolve terminal witnesses once over the current agent instance’s candidate groups, then hand the resulting attribution into
_assemblewithout independently resolving it again. Only the group containing the attributed call should deliver its chain. Keep chain construction and retry grouping group-local. Merely preferring the response-ID group after these independent builds would bypass contradictory explicit/item/content witnesses. I have not established a complete minimal patch covering token-equivalent cross-server attribution; that handoff must preserve the resolver’s corroboration contract rather than introduce a new precedence rule.Preservation / acceptance — proposed, not run: Create two stamped roots with the same output text, different prompt/generation tokens, distinct response IDs, and different model references. A verified response naming the second ID must deliver only the second group’s tokens unmasked. With no terminal witness, retain the existing two-server masked result. Conflicting witnesses across servers must not choose either group, and equal-content roots must never become cross-server retries or a joined chain. Retain the single-group witness-disagreement assertion.
-
nemo_gym/token_id_capture/store.pyline 434: BLOCKER — An unrelated named mark hides a conflicting-payload failure.Failure: Append a clean assistant entry, mark a judge call incomplete with its identity, then attempt a different payload under the assistant entry’s existing call ID and catch the expected
ValueError. The conflict branch sets durablestate["incomplete"]without writing a call mark. Because the judge mark exists, this condition leavesoutcomes.episode_wide=False. The snapshot attributes incompleteness only to the judge, allowing the assistant’s retained first payload to be delivered unmasked under the default policy. Previously the aggregate incomplete flag masked it.Correction: Preserve a durable episode-wide failure fact independently of named marks. In both conflicting-payload branches—
appendand_sync_entry_index—add this before the existing state write:state["incomplete_episode"] = True
Then replace this outcome condition with:
if state.get("incomplete_episode", False) or (state.get("incomplete", False) and not marks): outcomes.episode_wide = True
This suggested change retains the aggregate flag and legacy no-mark fallback. Adding an agent-specific mark must never erase another failure’s required masking.
Preservation / acceptance — proposed, not run: The trigger must yield
snapshot.incomplete_episode=True,snapshot.incomplete_for("assistant")=True, and a masked assistant build under the default mask policy. Repeat with the conflict preceding the judge mark. Inspect both conflict branches for the durable flag. Preserve identical re-put idempotency and the existing conflict-rejection assertions; a judge-only lost call without a conflict must still leave the assistant unmasked. Suggested code has not been executed. -
nemo_gym/token_id_capture/store.pyline 407: BLOCKER — An anonymous episode-wide mark disappears beside a named mark.Failure: Append clean assistant and judge entries, call
mark_incomplete(capture_key, "j-lost", identity=JUDGE), then callmark_incomplete(capture_key)with its public defaults. _call_line serializes the latter as a blank line, which this reader discards._outcomessees only the judge mark, so itsstate.incomplete and not marksfallback does not fire. The assistant remains unmasked despite an explicit episode-wide mark. The new test with only an anonymous mark passes through that fallback and misses this combination.Correction: Preserve empty lines specifically when reading incomplete marks, while leaving intent-file handling unchanged. A narrow suggested patch is:
def _call_lines(self, path: Path, *, preserve_empty: bool = False) -> list[dict[str, Any]]: if not path.exists(): return [] return [ _read_call_line(line) for line in path.read_bytes().splitlines() if preserve_empty or line.strip() ]
In
_outcomes, read marks with:marks = self._call_lines(self.incomplete_path_for(rollout_id), preserve_empty=True)
_read_call_line(b"")already produces{"model_call_id": ""}, whichOutcomeAttribution.addclassifies episode-wide. This also recognizes existing blank marker lines rather than only changing future serialization.Preservation / acceptance — proposed, not run: Extend the episode-wide-mark test with an additional judge-specific mark and test both write orders. The snapshot must have
incomplete_episode=True; both builds must be masked under the default policy. Retain judge-only mark isolation, inheritance from a named intent, and the flat unnamed single-agent behavior. Blank intent lines must continue to be ignored. Verify the suggested code before adopting it. -
responses_api_models/vllm_model/app.pyline 726: RISK — Context measurement needs the same group identity as generation.Failure: With source-history capture on a named model server such as
policy, capture one response, then measure its echoed history plus a user continuation. This synthetic context sets neithermodel_refnoragent_instance, so its group is(None, None). The new candidate filter excludes the earlier record, which generation stamps with the serving identity. Measurement sends a text-root admission while the corresponding generation sends a candidate admission. This affects unnamed single-agent episodes too and breaks the API’s same-admission measurement contract; workers reusing exact stored prefixes can consequently measure a different prompt.Correction: Carry the resolved correlation through the non-generating route and populate measurement’s identity exactly as generation does. A suggested minimal change, requiring author verification:
- Import
rememberalongsideresolvein the capture middleware, and immediately afterscope = scope_with_routed_path(scope, path)add:
remember(scope, (correlation, rest))
This uses the existing correlation contract instead of reparsing the stripped URL.
- In
measure_context, importresolveand the captureModelRef, resolverequest.scope, and add these context fields:
resolved = resolve(request.scope)
agent_instance=resolved[0].agent_instance if resolved else None, model_ref=ModelRef(name=self.config.name) if self.config.name else None,
Measurement must use the same
(agent_instance, model_ref.name)group while writing no intents, entries, or incomplete marks.Preservation / acceptance — proposed, not run: Retain the existing assertion that measurement sends
mode="candidate", names the accepted first call, and leaves the manifest unchanged. Retain measured/generated admission equality, includingwith_parent=True. Extend with assistant and judge prefixes sharing identical histories: each must select only its own predecessor. No own-group predecessor must remain a text root; another server’s chain must never be borrowed. Preserve rollout-affine backend routing and measurement’s no-write behavior. - Import
-
nemo_gym/token_id_capture/lineage.pyline 187: RISK — Filtering can hide episode-wide failures synthesized from malformed custody rows.Failure: Put a valid named assistant row beside an identity-less custody row whose
response_idor chain digest is missing. The unfiltered manifest converts the malformed row into an episode-wide failure through the existing fail-closed branches. Butmanifest(..., agent_instance="assistant")drops that row here: it does not match the filter and has no storedfailure_reasonyet. The filtered manifest looks healthy, contrary to the contract that episode-wide failures survive every filter. This affects both ledger implementations and the HTTP route because they share this helper.Correction: Apply the episode-wide exception to the two supported synthesized-failure cases as well as explicit failure rows, or synthesize failures before filtering. A small suggested replacement for this inner exception predicate is:
( row.get("failure_reason") is not None or ( row.get("staging_key") is not None and ( not row.get("response_id") or not row.get("chain_hash") or not row.get("cumulative_hash") ) ) ) and is_episode_wide(row.get("model_call_id"), columns, named_episode=named_episode)Use it within the existing
or (...); the later branches still construct the actual failure. The invariant is that filtering cannot turn an unattributable fail-closed custody error into a clean manifest.Preservation / acceptance — proposed, not run: Extend the missing-chain-digest regression with a valid named assistant row and repeat under assistant and nonmatching-model filters. Each must retain the malformed row’s failure; repeat for a missing response ID. A malformed row inheriting a named judge intent must remain confined to that judge’s filters. Valid unrelated custody rows and lineage-only rows must remain excluded, and the existing filter assertions must remain unchanged. Suggested code has not been executed.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
|
Two more beyond the bot's list, both reproduced locally:
|
90333a7 to
1d92fa3
Compare
d95ca67 to
cb2c713
Compare
cb2c713 to
5c2fcb9
Compare
5c2fcb9 to
6530d1f
Compare
…st call, attribute the terminal once per agent instance, and drop manifest filters and the capture-directory check Review changes for #5251: - primary_agent_instance prefers `assistant` over the unnamed agent, so an unnamed caller beside it never takes the scored response. - A request that carries model turns while its lineage scope has made no call is a root with reason `first_call`, under local capture as under worker custody. The file store checks entries, custody rows, intents and retirement first; the memory index roots only when it still holds another scope of the rollout. - An agent instance on several model servers has its terminal call attributed once over all its calls. - A mark that names no model call belongs to the agent instance that made the request when it is known. - `identity` is required on `LineageResolver.resolve` and `CaptureLedger.has_rows`. - `has_rows` refuses a first call on a retired capture key that still has another scope's rows. - `_mark_incomplete` writes the mark line before the state. - Remove the manifest filters, `check_one_capture_directory`, `select_terminal_calls` and `OutcomeAttribution.masks`, which have no caller. - Rename "group" to "lineage scope" (`groups.py` -> `lineage_scope.py`), merge `tests/unit_tests/test_agent_instance_capture.py` into `tests/unit_tests/models/test_token_capture_lineage_scope.py`, and document agent instances, the `assistant` name and `model_server_changed`. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]>
|
/ok to test a488b69 |
main's #5771 added the allow_system_suffix check inside the source-history loop that this branch moved into _source_history_matches, which has no capture context. Pass the flag in. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]>
|
/ok to test 40111fc |
…memory lineage store and state the episode-wide rule in three comments After an eviction, a put from another lineage scope recreates the rollout's index row, so the in-memory store rooted the evicted scope's continuation as a first call. It cannot tell the two cases apart, so it no longer roots with first_call. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: Pranav Thombre <[email protected]>
|
/ok to test b8c60a0 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/44649973685 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/44703503323 |
…stance and model server Since NVIDIA-NeMo/Gym#5251, Gym resolves a call's parent only among the calls of the same agent instance and model server. The test's after-restart context set neither, so it searched an empty scope and found no chain. It now carries the identity of the calls it continues, as the model server's own context does. Signed-off-by: Marc Romeyn <[email protected]>
What changed and why
With the identity recorded (#5250), capture still treated an episode's calls as one pool. That broke multi-agent episodes four ways:
This PR computes lineage, chains and outcomes per lineage scope: the calls of one agent instance on one model server. It is the design's "scoped lineage" (G5) and "outcomes are per agent instance" (G6). The helpers live in
nemo_gym/models/token_capture/lineage_scope.py.Parent search only links a call to an earlier call of its own lineage scope:
LineageIndexkeeps oneRolloutLineageper lineage scope inside each episode's entry; the incremental and file stores keep per-scope lineages inside the episode's cache row;FileLineageStorematches its shared custody rows by scope; source-history candidates come from the scope's manifest rows.resolve()andhas_rows()take a required keyword-onlyidentity.root_reason="model_server_changed"(newRootReason, also set on fingerprint-mode root admissions).first_call: the turns are input, such as the assistant's transcript in a judge's prompt. Local capture and worker custody now agree on this.FileLineageStorecalls it a first call only when the scope has no entry, no custody row and no intent, and the capture key is not retired, so a scope whose first call was lost does not start over as a root.InMemoryLineageStorecannot tell an evicted rollout from a scope that made no call, so it never roots withfirst_call: such a request stays unresolved there.has_rows(identity=...)counts only the call's own lineage scope, and raisesRolloutRetiredErrorwhenever that scope has no row and the capture key is retired.ambiguous_candidatekeeps its name and now means ambiguous within one agent instance and one model server.Chains and terminal calls: delivery builds each lineage scope separately with the existing builder, so retry grouping runs once per scope and no chain crosses model servers. The terminal call is attributed once per agent instance, over all its calls, and only the scope that holds the attributed call delivers. Retries are still grouped by content within a scope (the design wants
x-ng-request-id, which no client sends yet). A declared terminal that names another agent instance's call is masked withdeclared_terminal_not_captured; it never falls back to the heuristic. The top-level build is the primary agent instance's:assistantwhen the episode has one, else the unnamed agent, else the only agent instance. A named episode also returns every named agent instance's build underagent_instances. An episode whose named agent instances include noassistantand are more than one has no primary: its top-level build is masked withno primary agent instance captured.Outcomes:
TokenCaptureSnapshotaddsincomplete_agent_instances(the unnamed agent isNone) andincomplete_episodebeside the aggregateincomplete, plusincomplete_for(agent_instance). An agent instance's sample is masked by its own lost calls or by an episode-wide mark, never by another agent instance's, under both values ofmask_incomplete_when_attributed. A lost call inherits its intent's identity. A mark that names no model call, which the model server writes for a request it could not classify, belongs to the agent instance that made the request. Episode-wide are: a mark with no identity, a conflicting write, and a mark or failure with no agent instance in an episode that names them._mark_incompletewrites the mark line before the state, so a crash between the two cannot leave an episode-wide mark recorded only as the aggregate flag.Caches: a rollout's lineage scopes share one cache entry, so they count once against
max_rollouts/max_cached_rollouts. Retire and delete clear every scope's cached lineage and materialized tokens.Removed after review, because nothing in this stack or in NeMo RL
maincalls them: the manifest filters (agent_instance,agent_kind,model_refonmanifest),check_one_capture_directory,staging.select_terminal_callsandOutcomeAttribution.masks. The filters and the per-scope terminal selection return with their first caller; #5254 is where per-agent-instance results first needselect_terminal_calls.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.<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 LG,DL thisflowchart LR subgraph Episode k A1["assistant a1<br/>model_server_a"] --> A2["assistant a2<br/>model_server_a"] J1["judge j1<br/>model_server_a<br/>prompt embeds a1's transcript"] B1["assistant b1<br/>model_server_b<br/>continues a2's text"] end A2 -. "no link: other lineage scope" .-> J1 A2 -. "root: model_server_changed" .-> B1 classDef scope fill:#e0f2fe,stroke:#0369a1 class A1,A2,J1,B1 scopeOutcomes of one frozen snapshot:
Where this sits in the stack
This is one PR in a stack 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.
main)NeMo RL: NeMo RL
mainrunsselect_terminal_callover the whole manifest. Once a named judge has its own root, NeMo RL sees several roots and masks the rollout as ambiguous. Training on multi-agent episodes therefore needs the NeMo RL follow-up (selecting agent instances to train on, oneRolloutReceiptper selected agent instance, per-agent rewards). That change has no pull request yet and will be linked here when it is opened. Until NeMo RL bumps its Gym pin, this PR does not 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
Head
b8c60a09fmergesmain(6ff3f0b25) and adds two fixes from review after the runs below:_source_history_matchestakesallow_system_suffix(needed after #5771 onmain), and the in-memory store no longer roots a first call. Atb8c60a09f, on Slurm in the same container:tests/unit_tests/models,rollouts,trajectoryandserver_runtimegave 12 failed, 8,063 passed, 12 skipped, andresponses_api_models/vllm_model/testsgave 1,274 passed. The 12 failures (test_tool_telemetry.pyandserver_runtime/supervisor/) also fail in the baseline run and none is a token capture test. The full core suite and the smoke rollouts were not rerun at this head.At head
a488b691e, on Slurm (one node,nemo-rl-nightly-gym-2026-08-10container), against a baseline of this branch's base commitcd899cad5:python -m pytest -n 24 tests/unit_tests): 405 failed, 24,064 passed, 247 skipped, 2 errors. The baseline run has 409 failures and errors; every failure here but one is in the baseline set. They are environmental in this container (orchestration tests that needpython3on the host path, isolated exporter environments, docker-compose, CLI server resolution). The one that is not in the baseline run istests/unit_tests/orchestration/test_reader_srun.py::test_the_watcher_ends_a_reader_with_a_step_when_the_shell_input_closes[step], which this PR does not touch; it failed in both runs of this branch, and the baseline was not rerun to check whether it is flaky there.responses_api_models/vllm_model/tests: 1,222 passed.pre-commitcould not fetch its hook repositories from the build environment, soruff check --fixandruff formatran on every changed file. CI runs the remaining hooks.Signed-off-byline.tests/unit_tests/models/test_token_capture_lineage_scope.py(new; the earliertests/unit_tests/test_agent_instance_capture.pyis merged into it), onInMemoryLineageStoreandFileLineageStore:first_calland its build is unmasked; local capture and worker custody both admit it as a root; the same request as the assistant resolves to the assistant's call;model_server_changed;assistantis the primary before the unnamed agent, and an unnamed caller beside it does not take the scored response;Rollout evidence
Smoke rollouts ran at head
a488b691eand at its basecd899cad5(gym eval runagainst Qwen3-0.6B on a local vLLM 0.33.0, token capture on for all agents, one node each):cd899cad5a488b691eequivalence_llm_judge_simple_agent, 4 rolloutsmask_samplefalse on all 4tau2_agent(assistant and simulated user), 2 rollouts,max_steps=12mask_sampletrue on both (content_ambiguous)mask_sampletrue on both (content_ambiguous)The single-agent run is unchanged: same rewards, same delivered tokens, nothing masked, and the judge's calls do not disturb the agent's sample. The tau2 run is masked on the base for the same reason as here: on this branch nothing names the assistant and the simulated user, so their calls share one unnamed lineage scope. It shows capture and delivery complete without error, not an unmasked multi-agent sample; naming arrives with #5252 and #5253.
Not covered by a rollout: an unnamed agent that calls two capturing model servers, and a run resumed across #5250. Unit tests cover the first; see Compatibility for both.
Compatibility
LineageResolver.resolveandCaptureLedger.has_rowsnow receive a required keyword-onlyidentityon every call. A custom store configured throughtoken_id_capture.lineage_storemust accept it and search only the calls of that identity's agent instance and model server. A store that does not accept the keyword raisesTypeError: under worker custody the model call fails; under local capture the continuation is recorded as unresolved, so multi-call rollouts are masked.CaptureLedger.manifestis unchanged. NeMo RLmainconfigures Gym's ownFileLineageStoreand is not affected.identityto everyresolve, and fails a resolver that resolves another agent instance's request to that call.agent_instancesmap. A build can be the new failed resultno primary agent instance captured.model_server_changedroot, and delivery masks the sample unless the terminal call is attributed to one of them. Onmainthe same sample trained.model_ref. They form a lineage scope of their own, so a continuation of them after the upgrade is amodel_server_changedroot.FileLineageStore, the first request of a lineage scope that carries model turns is now a root (first_call) instead of unresolved, as worker custody already admitted it.RootReasongainsmodel_server_changed;ambiguous_candidatenow means ambiguous within one agent instance and one model server (heads-up to feat(capture): support framework-owned context reconstruction #4128's authors).TokenCaptureSnapshotgainsincomplete_agent_instancesandincomplete_episode.incompleteis the aggregate across agent instances. A source that reports only the aggregate is treated as episode-wide.🤖 Generated with Claude Code