Skip to content

feat(capture): compute lineage, terminal chains and outcomes per agent instance and model server - #5251

Merged
pthombre merged 5 commits into
mainfrom
pranav/agent-instance-03-per-agent-capture
Nov 20, 2026
Merged

pthombre merged 5 commits into
mainfrom
pranav/agent-instance-03-per-agent-capture

Conversation

@pthombre

@pthombre pthombre commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • a judge prompt that contains the assistant's transcript extends the assistant's calls, so the parent search links it into the assistant's chain (and, under worker custody, an "unresolved continuation" is poisoned);
  • two agent instances with byte-identical first prompts are grouped as retries of each other and masked;
  • a judge's capture failure masks the assistant's training sample;
  • terminal selection sees several unrelated roots.

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:

  • LineageIndex keeps one RolloutLineage per lineage scope inside each episode's entry; the incremental and file stores keep per-scope lineages inside the episode's cache row; FileLineageStore matches its shared custody rows by scope; source-history candidates come from the scope's manifest rows. resolve() and has_rows() take a required keyword-only identity.
  • A request whose only match was served by another model server for the same agent instance is a root with root_reason="model_server_changed" (new RootReason, also set on fingerprint-mode root admissions).
  • A request that carries model turns while its lineage scope has made no call is a root with reason 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. FileLineageStore calls 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. InMemoryLineageStore cannot tell an evicted rollout from a scope that made no call, so it never roots with first_call: such a request stays unresolved there.
  • has_rows(identity=...) counts only the call's own lineage scope, and raises RolloutRetiredError whenever that scope has no row and the capture key is retired.
  • ambiguous_candidate keeps 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 with declared_terminal_not_captured; it never falls back to the heuristic. The top-level build is the primary agent instance's: assistant when the episode has one, else the unnamed agent, else the only agent instance. A named episode also returns every named agent instance's build under agent_instances. An episode whose named agent instances include no assistant and are more than one has no primary: its top-level build is masked with no primary agent instance captured.

Outcomes: TokenCaptureSnapshot adds incomplete_agent_instances (the unnamed agent is None) and incomplete_episode beside the aggregate incomplete, plus incomplete_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 of mask_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_incomplete writes 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 main calls them: the manifest filters (agent_instance, agent_kind, model_ref on manifest), check_one_capture_directory, staging.select_terminal_calls and OutcomeAttribution.masks. The filters and the per-scope terminal selection return with their first caller; #5254 is where per-agent-instance results first need select_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.&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 LG,DL this
Loading
flowchart 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 scope
Loading

Outcomes of one frozen snapshot:

flowchart TB
  S["Snapshot<br/>entries, intents, incomplete marks"] --> G["lineage_scope.py<br/>scope entries; attribute lost calls and marks"]
  G --> BA["build assistant<br/>masked by its own lost calls<br/>or an episode-wide mark"]
  G --> BJ["build judge<br/>masked by its own lost calls<br/>or an episode-wide mark"]
  BA --> TOP["top-level build (primary)"]
  BA & BJ --> MAP["agent_instances builds"]
Loading

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.

  1. refactor(capture): name capture keys capture_key on the ledger control surface #5248: refactor(capture): name capture keys capture_key on the ledger control surface (merged)
  2. feat(core): add a correlation module that reads and builds the rollout path #5249: feat(core): add a correlation module that reads and builds the rollout path (merged)
  3. feat(model): record agent instance, agent kind and model server on every capture and model-call record #5250: feat(model): record agent instance, agent kind and model server on every capture and model-call record (merged)
  4. feat(capture): compute lineage, terminal chains and outcomes per agent instance and model server #5251: feat(capture): compute lineage, terminal chains and outcomes per agent instance and model server (this PR, base main)
  5. feat(core): let callers name an agent instance on model calls #5252: 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: feat(agent): bind agent sessions to an agent instance at seed time
  7. feat(episode): report terminal calls and rewards per agent instance #5254: feat(episode): report terminal calls and rewards per agent instance
  8. refactor(core): read and build every rollout path through the correlation module #5255: refactor(core): read and build every rollout path through the correlation module

NeMo RL: NeMo RL main runs select_terminal_call over 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, one RolloutReceipt per 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 b8c60a09f merges main (6ff3f0b25) and adds two fixes from review after the runs below: _source_history_matches takes allow_system_suffix (needed after #5771 on main), and the in-memory store no longer roots a first call. At b8c60a09f, on Slurm in the same container: tests/unit_tests/models, rollouts, trajectory and server_runtime gave 12 failed, 8,063 passed, 12 skipped, and responses_api_models/vllm_model/tests gave 1,274 passed. The 12 failures (test_tool_telemetry.py and server_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-10 container), against a baseline of this branch's base commit cd899cad5:

  • Core suite (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 need python3 on the host path, isolated exporter environments, docker-compose, CLI server resolution). The one that is not in the baseline run is tests/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-commit could not fetch its hook repositories from the build environment, so ruff check --fix and ruff format ran on every changed file. CI runs the remaining hooks.
  • Every commit carries a Signed-off-by line.

tests/unit_tests/models/test_token_capture_lineage_scope.py (new; the earlier tests/unit_tests/test_agent_instance_capture.py is merged into it), on InMemoryLineageStore and FileLineageStore:

  • a judge's first request that replays the assistant's turns is a root with first_call and 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;
  • a request with unmatched model turns stays unresolved once its lineage scope has called; a scope whose first call was lost (intent only) or failed (custody row only) does not start over as a root; the memory index keeps a request unresolved when it holds no call of the rollout;
  • a continuation on another model server is a root with model_server_changed;
  • a scope's first call is refused on a retired capture key that still has another scope's rows;
  • assistant is the primary before the unnamed agent, and an unnamed caller beside it does not take the scored response;
  • when two model servers served the scored text, the response id picks the server; witnesses naming calls on two servers deliver neither;
  • identical first prompts of two agent instances are two roots, not retries; identical roots on two model servers are not grouped as retries;
  • a mark naming no model call masks only the agent instance that made the request; an episode-wide mark survives a crash before the state is written; a judge mark does not hide a conflicting write or a mark with no identity;
  • retire leaves no lineage scope in the caches and returns the materialized token count to its earlier value.

Rollout evidence

Smoke rollouts ran at head a488b691e and at its base cd899cad5 (gym eval run against Qwen3-0.6B on a local vLLM 0.33.0, token capture on for all agents, one node each):

Scenario Base cd899cad5 This PR a488b691e
equivalence_llm_judge_simple_agent, 4 rollouts 4 rows, rewards 1/0/1/1, tokens delivered, mask_sample false on all 4 identical
tau2_agent (assistant and simulated user), 2 rollouts, max_steps=12 2 rows, 23 captured calls, mask_sample true on both (content_ambiguous) 2 rows, 24 captured calls, mask_sample true 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

  • Protocol change for custom lineage stores: LineageResolver.resolve and CaptureLedger.has_rows now receive a required keyword-only identity on every call. A custom store configured through token_id_capture.lineage_store must accept it and search only the calls of that identity's agent instance and model server. A store that does not accept the keyword raises TypeError: under worker custody the model call fails; under local capture the continuation is recorded as unresolved, so multi-call rollouts are masked. CaptureLedger.manifest is unchanged. NeMo RL main configures Gym's own FileLineageStore and is not affected.
  • Conformance kit: the lineage check now commits its call with an identity, passes identity to every resolve, and fails a resolver that resolves another agent instance's request to that call.
  • Build result: a named episode's build carries an agent_instances map. A build can be the new failed result no primary agent instance captured.
  • Incomplete marks file: a blank line now means an episode-wide mark and is kept when read.
  • Single-agent behavior that changes:
    • An unnamed agent that calls two capturing model servers now has two lineage scopes. A continuation across them is a model_server_changed root, and delivery masks the sample unless the terminal call is attributed to one of them. On main the same sample trained.
    • A run resumed across feat(model): record agent instance, agent kind and model server on every capture and model-call record #5250 has earlier rows without model_ref. They form a lineage scope of their own, so a continuation of them after the upgrade is a model_server_changed root.
    • Under local capture with 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.
  • RootReason gains model_server_changed; ambiguous_candidate now means ambiguous within one agent instance and one model server (heads-up to feat(capture): support framework-owned context reconstruction #4128's authors).
  • TokenCaptureSnapshot gains incomplete_agent_instances and incomplete_episode. incomplete is the aggregate across agent instances. A source that reports only the aggregate is treated as episode-wide.

🤖 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:high Cross-component or shared-contract change with a large 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.

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.py line 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)]) produces incomplete_agent_instances={"assistant"}, but this roster contains only judge. The sole-agent fallback selects it, and incomplete_for("judge") is false. The top-level result therefore contains judge tokens with mask_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_snapshot with:

    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.py line 273: RISK — Independent terminal attribution per model server rejects an attributable sample.

    Failure: One assistant has two root calls on policy and policy-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 report chain="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 _assemble without 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.py line 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 durable state["incomplete"] without writing a call mark. Because the judge mark exists, this condition leaves outcomes.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—append and _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.py line 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 call mark_incomplete(capture_key) with its public defaults. _call_line serializes the latter as a blank line, which this reader discards. _outcomes sees only the judge mark, so its state.incomplete and not marks fallback 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": ""}, which OutcomeAttribution.add classifies 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.py line 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 neither model_ref nor agent_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:

    1. Import remember alongside resolve in the capture middleware, and immediately after scope = scope_with_routed_path(scope, path) add:
    remember(scope, (correlation, rest))

    This uses the existing correlation contract instead of reparsing the stripped URL.

    1. In measure_context, import resolve and the capture ModelRef, resolve request.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, including with_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.

  • nemo_gym/token_id_capture/lineage.py line 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_id or chain digest is missing. The unfiltered manifest converts the malformed row into an episode-wide failure through the existing fail-closed branches. But manifest(..., agent_instance="assistant") drops that row here: it does not match the filter and has no stored failure_reason yet. 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.

@cmunley1

Copy link
Copy Markdown
Contributor

Two more beyond the bot's list, both reproduced locally:

  1. primary_agent_instance (groups.py:99) returns the unnamed agent before checking for assistant, so an episode with a named assistant plus any unnamed caller on the capture prefix promotes the unnamed caller to the top-level build. Its tokens take the scored response and the single-chain fallback leaves it unmasked (repro: top-level output is the helper's tokens, mask_sample False). This is also what makes feat(agent): bind agent sessions to an agent instance at seed time #5253's SWE-Together judge, whose calls arrive unnamed, become the training build. Preferring assistant when present, or refusing to mix named and unnamed agents in one episode, would close both.

  2. Under local capture, a named judge's first call whose prompt carries the assistant's turns resolves UNRESOLVED/no_match, because its own group is empty. Only worker custody turns that into a root (per-group has_rows). So agent_instances['judge'] is always masked with unresolved_parent_calls. The consumer test stamps the judge ROOT by hand, so it doesn't catch this. The two capture paths should agree.

@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-03-per-agent-capture branch from 90333a7 to 1d92fa3 Compare November 2, 2026 22:29
@pthombre
pthombre force-pushed the pranav/agent-instance-03-per-agent-capture branch 2 times, most recently from d95ca67 to cb2c713 Compare November 3, 2026 14:13
@pthombre
pthombre force-pushed the pranav/agent-instance-03-per-agent-capture branch from cb2c713 to 5c2fcb9 Compare November 3, 2026 15:07
@pthombre
pthombre force-pushed the pranav/agent-instance-03-per-agent-capture branch from 5c2fcb9 to 6530d1f Compare November 3, 2026 15:22
…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]>
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the risk:high Autobot PR risk: high label Nov 19, 2026
@pthombre

Copy link
Copy Markdown
Contributor Author

/ok to test a488b69

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 19, 2026 22:42
@github-actions

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

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]>
@pthombre

Copy link
Copy Markdown
Contributor Author

/ok to test 40111fc

ananthsub
ananthsub previously approved these changes Nov 19, 2026
…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]>
@pthombre

Copy link
Copy Markdown
Contributor Author

/ok to test b8c60a0

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 20, 2026 00:41
@pthombre
pthombre added this pull request to the merge queue Nov 20, 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/44649973685

@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 20, 2026
@pthombre
pthombre added this pull request to the merge queue Nov 20, 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/44703503323

Merged via the queue into main with commit 04e6ff4 Nov 20, 2026
79 of 82 checks passed
@pthombre
pthombre deleted the pranav/agent-instance-03-per-agent-capture branch November 20, 2026 08:50
marcromeyn added a commit to NVIDIA-NeMo/RL that referenced this pull request Nov 24, 2026
…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]>
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 blocked Work cannot move forward until an external dependency is cleared complexity:high Cross-component or shared-contract change with a large review surface feature New capabilities, enhancements, or enablement work risk:high Autobot PR risk: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants