Skip to content

fix(agent): reconcile harness-reported and captured token usage - #3981

Open
yaoyu-33 wants to merge 13 commits into
NVIDIA-NeMo:mainfrom
yaoyu-33:codex/harness-token-usage-pr
Open

yaoyu-33 wants to merge 13 commits into
NVIDIA-NeMo:mainfrom
yaoyu-33:codex/harness-token-usage-pr

Conversation

@yaoyu-33

@yaoyu-33 yaoyu-33 commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Hermes could finish a rollout with valid token IDs and reward 1 while reporting zero token usage. #4139 (merged) fixed that by mapping Hermes's own counters. This PR adds the remaining accounting: when Model Server capture is on, the lifecycle owner replaces the agent's response.usage with the sum of the model calls captured during agent execution, so usage no longer depends on what each harness reports.

No public issue: this came from an internal bug report. Builds on #3554, #3961 and #4139.

Changes

  • nemo_gym/rollouts/model_usage.py (new): ModelUsageCapture checkpoints the capture file offset when agent execution starts and sums the exchanges appended after it when execution ends. CaptureStore.offset() and read_available(start_offset=...) support this.
  • single_agent_turn (and single_agent_turn_legacy, which inherits it) starts the capture after the Resources and tool server seeds, through a new before_agent_seed hook on seed_episode_sessions, and reads it after Agent close, before verification. Hermes's /run route (relayed by legacy_agent, as in hermes_reasoning_gym) does the same between its seed and /verify.
  • The two sources are never added together. With capture on, the result is the captured sum or null. With capture off, on direct calls, or on /run requests without rollout identity, the harness's own usage stays.
  • Usage is null, never zero or a partial sum, when:
    • a finished response is missing counts;
    • a stream was truncated;
    • the capture is damaged or incomplete;
    • a claimed capture write has not landed after the drain wait;
    • Agent close failed;
    • capture is enabled but has no usable model_call_capture_dir (logged; the episode still runs);
    • the episode continued from a partial-rollout checkpoint taken before Agent close (the replaced attempt's calls sit under another capture key).
  • As the rollout health contract says, a failed call that returned no response and no usage contributes nothing. Verifier-tagged calls are excluded. Cache-write tokens are summed.
  • The verifier may rewrite response; the result keeps the agent's accounted usage.

Sampling, rewards of the shipped pairings and training-token payloads are unchanged.

Compatibility

  • With capture on (the default for gym eval submit), response.usage for single_agent_turn / single_agent_turn_legacy pairings and Hermes /run is the captured sum and can be null. Consumers must accept nullable usage and details.
  • Verifiers receive this value in response. No shipped pairing of a verifier that reads response.usage (speed_bench, rna_design, officeenv) runs on these paths today.
  • The sum covers every call routed under the episode's rollout prefix, including model calls a Resources or tool server makes while serving the agent's tools.
  • Other Environment Servers (harbor, nemo_user_sim, swe_together) keep the harness's own usage.

Validation

At head f18225a03f (after merging main at ba3cd7e881):

  • tests/unit_tests/rollouts/test_model_usage.py + tests/unit_tests/eval/recovery/test_environment_grading_health.py: 63 passed (macOS).
  • resources_servers/opencode_multimodal_benchmarks/tests: 355 passed (Linux workstation), including the grading-recovery tests that run single_agent_turn with observability_enabled and no capture directory.
  • environment_servers/single_agent_turn/tests/test_app.py: 225 passed (macOS). The new restore-before-close test fails against the pre-fix code.
  • responses_api_agents/hermes_agent/tests: 416 passed (Linux workstation, pinned Hermes 26bb847a runtime, at 56060aa15b; the last commit touches only model_usage.py and its test).
  • pre-commit run --files <changed files>: passed.
pytest tests/unit_tests/rollouts/test_model_usage.py environment_servers/single_agent_turn/tests/test_app.py -q
pytest responses_api_agents/hermes_agent/tests -q

Real-model smoke

gym env start + gym eval run --no-serve --limit 5 on the shipped configs, against hosted nvidia/nemotron-3.5-super-vl-120b-a12b through vllm_model. The "capture" runs set ++observability_enabled=true ++model_call_capture_dir=<abs>.

Pairing Capture Reward response.usage vs provider usage in the capture Rollout quality
hermes_reasoning_gym (Hermes /run via legacy_agent) on 5/5 = 1.0 equal on all 5 rows (e.g. 5070 in / 710 out) 5 healthy
hermes_reasoning_gym off 5/5 = 1.0 Hermes-reported usage (e.g. 5069 / 403) 5 unobserved
reasoning_gym (single_agent_turn_legacy + simple_agent) on 5/5 = 1.0 equal on all 5 rows (e.g. 119 in / 933 out) 5 healthy
reasoning_gym off 5/5 = 1.0 agent-reported usage 5 unobserved

mean/*_tokens in the aggregate metrics match the per-row usage. Every smoke row made one model call; multi-call, failed-call, pending-write and restore cases are covered by the unit tests above, not by the smoke.

Remaining limits

  • rollout_token_count_mismatch compares response.usage with the captured calls the trajectory references. With capture on, usage is itself the captured sum, so the check can no longer catch a harness under-count on these paths. It can also flag a harness whose trajectory does not reference every call it makes. The same holds for the harness conformance usage_retained check, which runs with capture on.
  • Hermes's own counters, used when capture is off, can still read 0 for unknown reasoning or cached-token details with Chat Completions, and can be partial when a provider omits usage. The README says so.

🤖 Generated with Claude Code

@yaoyu-33 yaoyu-33 added bug Something isn't working area:agent Agent harnesses and Responses API agent behavior labels Oct 3, 2026
@copy-pr-bot

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

yaoyu-33 added a commit to yaoyu-33/Gym that referenced this pull request Oct 3, 2026
Token accounting is isolated in NVIDIA-NeMo#3981. Preserve the configuration and lifecycle changes from before the usage work.

Signed-off-by: yaoyu-33 <[email protected]>
yaoyu-33 added a commit to yaoyu-33/Gym that referenced this pull request Oct 6, 2026
Token accounting is isolated in NVIDIA-NeMo#3981. Preserve the configuration and lifecycle changes from before the usage work.

Signed-off-by: yaoyu-33 <[email protected]>
@yaoyu-33
yaoyu-33 marked this pull request as ready for review October 6, 2026 16:07
yaoyu-33 added a commit to yaoyu-33/Gym that referenced this pull request Oct 6, 2026
Token accounting is isolated in NVIDIA-NeMo#3981. Preserve the configuration and lifecycle changes from before the usage work.

Signed-off-by: yaoyu-33 <[email protected]>
@yaoyu-33 yaoyu-33 added complexity:high Cross-component or shared-contract change with a large review surface needs-review PR is ready for code review and waiting on a reviewer labels Oct 6, 2026
yaoyu-33 added a commit to yaoyu-33/Gym that referenced this pull request Oct 6, 2026
…VIDIA-NeMo#3961)

Hermes can be composed with a Resources Server through Environment
Server. This PR decouples its default configuration and extracts a
shared sandbox execution lifecycle for Pi (NVIDIA-NeMo#3626), Codex (NVIDIA-NeMo#3640), and
OpenCode to adopt.

Implements [GYMINT-5](https://linear.app/nvidia/issue/GYMINT-5), follows
NVIDIA-NeMo#3554, and includes merged NVIDIA-NeMo#4053 from main. Only Hermes adopts the
shared session in this PR; the other adapters retain their own output
parsing when they migrate.

## Changes

- Keep shared execution code in `nemo_gym/agent_utils/`, the agreed
package name. This name preserves the agreed organization of the
lifecycle and protocol helpers. Core connection, exec, transfer and
provider lifecycle APIs remain in `nemo_gym/sandbox/`.
- `SandboxSession` uploads its supervisor into the session directory,
executes the harness, confirms cleanup and collects artifacts.
`SandboxCommand` carries only argv and an explicitly installed Python
interpreter. Preflight validates that interpreter before claiming
launch; Python on the task image is not assumed.
- Stage input and upload the supervisor in one cancellable task.
Concurrent/retried closes share work; closing/closed derive from the
close task. Execution retains the sandbox until explicit close. Borrowed
cleanup failures retain state for retry; owned sandboxes can fall back
to provider teardown.
- Use one timeout-budget helper, one set of protocol filenames, and one
cleanup receipt shape. Optional malformed diagnostics remain nonfatal;
literal positive cleanup confirmation is still required. Session log
access preserves diagnostics before files are released.
- Hermes separates seed-time `install_runtime()` from
`stage_activation()` and `collect_artifacts()`. Its process-identity
schema stays in the adapter. The runner receives the stop-marker path
from the session, preserving cancellation versus deadline reporting.
- Keep `upload_text()` / `read_text()` in `sandbox/utils.py`, with
Hemil's import/ordering cleanup. Remove unused byte helpers and their
tests as requested.
- Preserve native Hermes templates with explicit `resources_server:
null` during legacy Environment Server migration. Bound Hermes,
inherited Resources bindings and self-contained agents such as OSWorld
retain their existing migration behavior. This fixes the merge-queue
audit introduced by NVIDIA-NeMo#4084 without adding a conflicting legacy route.
- Default an owned sandbox's missing `ttl_s` to install timeout + runner
timeout + 600 seconds (23,100 seconds with default settings), so
providers that enforce TTL can expire it after an agent-server crash.
Preserve explicit values, including null, and borrowed connections; do
not mutate shared configuration.

## Architecture

From [Ananth's component
diagram](NVIDIA-NeMo#3961 (comment)):

```mermaid
flowchart LR
    subgraph AS["Agent server"]
        A["Harness adapter (Hermes)<br/>installs runtime, stages input, parses output"]
        S["Sandbox session<br/>uploads supervisor, runs, stops, collects, releases"]
        C["Supervisor client<br/>shell protocol over the session files"]
    end
    subgraph TS["Task sandbox"]
        D["Session directory<br/>claim, supervisor pid, stop request, receipt, log"]
        P["Process supervisor<br/>deadline, kills the process tree, writes receipt"]
        H["Harness process<br/>Hermes runner, Codex CLI"]
    end
    A -->|"argv and interpreter"| S
    S -->|"launch, stop, read receipt"| C
    C -->|"runs"| P
    C -->|"reads and writes"| D
    P -->|"starts and reaps"| H
    P -->|"writes receipt"| D
```

The session and supervisor client run on the agent server. Only
`process_supervisor.py` from the shared package is copied into the
sandbox; it uses only the standard library. A common runtime installer
and provider default mounts from [the earlier
diagram](NVIDIA-NeMo#3961 (comment))
remain follow-ups. The [owned-sandbox TTL
request](NVIDIA-NeMo#3961 (comment))
is now implemented in this PR.

## Folder layout

```text
nemo_gym/
├── agent_utils/
│   ├── __init__.py           # Component responsibilities and execution locations
│   ├── sandbox_session.py    # Server: upload supervisor; execute, stop, collect, close
│   ├── supervisor_client.py  # Server: protocol files, timeout budget, launch/stop/receipt
│   └── process_supervisor.py # Sandbox: deadlines, kill/reap descendants, write receipt
└── sandbox/
    ├── api.py                # Core connection, exec, file transfer and provider lifecycle
    ├── providers/            # Backend implementations
    └── utils.py              # Text transfer, CPU caps and image rewriting

responses_api_agents/hermes_agent/
├── app.py                    # Config, request/session hooks and Gym response conversion
├── sandbox.py                # Install Hermes, stage input, parse artifacts/runtime metadata
└── sandbox_runner.py         # Sandbox: Hermes SDK entry point and partial-result capture
```

The control files are `process_supervisor.py`, `launch.claim`,
`supervisor.pid`, `stop.request`, `cleanup.json`, and `output.log`.
`supervisor_client.py` documents each writer and timing. `session_dir`
holds those files; `workdir` is the task repository.

## Compatibility

- Downstream branches must use
`nemo_gym.agent_utils.{sandbox_session,supervisor_client,process_supervisor}`.
Both in-branch Hermes adapters and tests use the new package. Session
adopters use `session_dir`, `stage_activation`, and `stop_harness`; they
no longer upload or choose a supervisor path.
- Default `resources_server` is null; unbound compatibility `/run`
returns 422. Explicitly bound recipes remain supported; legacy agent
swapping must restore that binding. The default model uses
`${policy_model_name}`.
- Owned TTL defaults only when the `ttl_s` key is absent. Explicit null
retains provider defaults; long-lived or delayed sessions can set their
own lifetime. Expiry still depends on provider support; this does not
add TTL support to providers that ignore it.
- No seed protocol or Hermes version change. Token accounting remains
separate in NVIDIA-NeMo#3981. Invalid runtime metadata leaves valid responses
intact and records an observation gap.
- Transport errors remain execution errors after partial capture;
capture failures are independent of cleanup confirmation. Model-writable
output still does not qualify these trajectories for RL training.

## Validation

**Latest reviewed head: `d5e6ad20b733faeeb3a35cabc4288c13609d4b11`.**
[Full CI
37531286874](https://github.com/NVIDIA-NeMo/Gym/actions/runs/37531286874)
and [build
37531287625](https://github.com/NVIDIA-NeMo/Gym/actions/runs/37531287625)
**passed** on this head: core **6,594 passed / 2 skipped**, sandbox
**913 passed / 5 skipped**, **95.25%** coverage, and all eight server
shards. All applicable head checks are complete. The PR currently has no
merge-queue entry; a maintainer needs to re-add it for fresh
combined-tree CI. The prior failed queue run does not validate this fix.

- Reproduced the [merge-queue
failure](https://github.com/NVIDIA-NeMo/Gym/actions/runs/37526772843/job/112486565515)
at combined SHA `0f1001ef33be7f4ab99d0e236a2ce15053f0f64e`. With this
patch applied to that exact tree, migration and configuration tests
passed: **219 passed**, including the unchanged repository-wide audit.
- Final PR checkout: migration, configuration and session-contract tests
**220 passed**. Six new cases cover explicit null versus bound Hermes,
OSWorld, inherited bindings and exactly one native Environment Server
after composition. Two independent reviews found no remaining issues;
the six focused cases also passed independently.
- Full `pre-commit run --all-files`, `git diff --check` and the default
Hermes migration `--check` passed. Model rollout: **N/A for this
follow-up**, which changes offline configuration migration only.
- Prior head `a309dfb9a5cb8c65b6bd7366260c189c3dcd3284`: both Hermes
suites plus shared session/client tests **375 passed, 9 skipped**;
mocked Docker TTL contract tests **2 passed**. No live provider
expiry/model run was performed for the TTL change; earlier model
evidence remains scoped to its recorded revisions.
- That prior head passed [CICD
37525046614](https://github.com/NVIDIA-NeMo/Gym/actions/runs/37525046614):
core **6,588 passed, 2 skipped**, sandbox **913 passed, 5 skipped**,
combined coverage **95.25%**, and all eight server shards. [Wheel/build
37525047397](https://github.com/NVIDIA-NeMo/Gym/actions/runs/37525047397)
and lightweight checks also passed. These results do not validate this
new migration commit or the failed merge-group tree.
- All 20 implementation review requests remain addressed, including
owned TTL; reviewer threads remain for reviewers to resolve. Shared
Python provisioning remains future installer work.

```sh
python -m pytest tests/unit_tests/test_add_legacy_agent_environment_servers.py \
  tests/unit_tests/test_global_config.py tests/unit_tests/test_session_contract_repo.py \
  --import-mode=importlib -q -o addopts='' -o log_cli=false --tb=short
# Exact failed merge-group source plus the two-file patch:
python -m pytest tests/unit_tests/test_add_legacy_agent_environment_servers.py \
  tests/unit_tests/test_global_config.py \
  --import-mode=importlib -q -o addopts='' -o log_cli=false --tb=short
python scripts/add_legacy_agent_environment_servers.py --check \
  responses_api_agents/hermes_agent/configs/hermes_agent.yaml
pre-commit run --all-files
git diff --check
```

---------

Signed-off-by: yaoyu-33 <[email protected]>
Preserve the Hermes lifecycle refactor and usage integration. Align the capture regression with integer details on synthesized Responses SSE, and retain a raw-stream case for genuinely absent details.

Signed-off-by: yaoyu-33 <[email protected]>
@ananthsub

Copy link
Copy Markdown
Contributor

/ok to test cedcd1b

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team October 7, 2026 16:12
@github-actions github-actions Bot added the sla:triage-overdue Review assignment is over the one-business-day SLA label Oct 7, 2026
giuliolovisotto and others added 2 commits October 7, 2026 09:36
Signed-off-by: Giulio Lovisotto <[email protected]>
(cherry picked from commit 8892025)
Signed-off-by: yaoyu-33 <[email protected]>
@yaoyu-33 yaoyu-33 changed the title fix(agent): derive token usage from shared model capture fix(agent): report native and captured token usage Oct 7, 2026
svcnemo-autobot pushed a commit to svcnemo-autobot/Gym that referenced this pull request Oct 7, 2026
Hermes returned zero input and output tokens for every rollout, even
when the pinned native harness supplied nonzero usage. Export its
cache-inclusive `prompt_tokens` and `completion_tokens` through the
shared host/sandbox response converter, with cache and reasoning
details. Missing native totals now remain unknown instead of becoming
zero. This preserves the provider-failure and partial-result behavior
established in NVIDIA-NeMo#3720 and NVIDIA-NeMo#3554.

No linked issue: this fixes a token-accounting failure found during
conformance validation.

Validation:
- Seven regression cases failed against the original converter and pass
with this change; they cover cache-inclusive totals, partial results and
missing usage/details.
- `gym env test +entrypoint=responses_api_agents/hermes_agent
+should_validate_data=true +skip_venv_if_present=true`: 222 passed, 4
skipped.
- `pre-commit run --all-files`: passed.
- Final-head CI passed, including core tests, all eight server-test
shards, lint and DCO.
- Real ReasoningGym `manipulate_matrix`, seed 42, one task/repeat with
the same model and native verifier: reward 1.0, health **healthy**,
1,235 input / 376 output tokens. Original run was unhealthy because its
response reported zero tokens. Capture and observability were enabled;
the live agent source hash matches this commit.
- Seven fresh controlled scenarios through the native adapter: five
healthy, one correctly unhealthy for intentionally omitted provider
usage, one unobserved terminal-error sidecar. Before the fix: zero
healthy, six unhealthy, one unobserved. P0 conformance remains
incomplete for missing retry/terminal-error evidence.

- Real native SWE-Pro NodeBB sandbox rollout: 91 model calls,
**healthy**, no findings or unobserved rollout checks. Independent
capture reconciliation matched all 1,874,133 input / 4,611 output /
1,830,400 cached input tokens. The native verifier completed with reward
0: the model supplied a plan and only created a backup file; the
required `getOrCreate()` implementation remained missing. This validates
accounting, not task correctness.
- Sandbox run used the pinned native Hermes revision
`26bb847a88493342ca1b194e0455b479073ae21d` and task image
`sha256:605b6da16030d20129e0b9f9376fd494d60ec5f68f5e05f608742133bd39ae98`.
A Linux-prepared runtime was mounted to meet the documented host/sandbox
architecture requirement, and the existing
`chat_template_kwargs_enabled=false` option was used for hosted GPT-4.1.
Agent/resource/verifier code and task contents were unmodified. The
all-P0 artifact assessment still lacks sandbox lifecycle evidence;
healthy does not imply full conformance.

This exposes the aggregates produced by pinned Hermes. It does not
repair native omissions from auxiliary or delegated calls, nor infer
missing usage from the health check's capture data. Both live runs
exercised ordinary root calls; the SWE-Pro run completed before its
100-turn limit, so limit-summary and delegated-call accounting remain
unvalidated.

Review coordination: a maintainer requested consolidation with NVIDIA-NeMo#3981,
which derives usage from shared lifecycle capture and leaves direct
`/v1/responses` usage null. This narrower implementation exports native
Hermes aggregates without requiring capture. The approaches overlap and
should be consolidated deliberately; the live results above validate
this PR's implementation, not NVIDIA-NeMo#3981.

Signed-off-by: Giulio Lovisotto <[email protected]>
Preserve the parameterized native usage test while incorporating the landed native mapping. Keep the separate capture cancellation fix deferred.

Signed-off-by: yaoyu-33 <[email protected]>
yaoyu-33 pushed a commit to yaoyu-33/Gym that referenced this pull request Oct 12, 2026
…o#4040)

Pinned Hermes replays internal tool-call fields when it asks for a
summary at the iteration limit. Gym rejects that request with HTTP 422,
and the summary call bypasses Gym's observed model-call path. Delegated
`delegate_task` children construct fresh Hermes agents, so they need the
same adapter; otherwise their limit summaries fail and lack child
invocation ownership.

Keep the existing `cmunley1/hermes-agent@26bb847a` pin. Gym now installs
its summary adapter before root and delegated child agents run,
sanitizes only the outgoing summary history, and routes summaries and
retries through the observed model-call method. The original trajectory
stays intact and no turns are added. A documented
`on_iteration_limit_reached(*, invocation_id: str) -> None` observer
hook records `stop_reason=max_iterations` and `incomplete` once on the
affected invocation before summary dispatch. A child's limit does not
mark or terminate its parent. The sandbox observation bridge preserves
this invocation-scoped outcome. No hook registry, budget change, or
dependency repin is introduced.

This addresses the follow-up to NVIDIA-NeMo#3554 and is tracked by
[FEA-399](https://linear.app/nvidia/issue/FEA-399/hermes-observe-limit-summaries-and-invocation-stops).
Native usage accounting is supplied by NVIDIA-NeMo#4139 on main. The adapter uses
private methods of this pinned Hermes version, so a future dependency
update must recheck these hooks. No configuration migration is needed. A
valid terminal summary may change the final trajectory and benchmark
result.

Validation after rebasing onto main
`4a9236e48c82f0dc23365a4c0088b1e54d00d3a8` (head
`eb435d5da130538e2d87cd9ca0c384444aba9c54`):
- Hermes component suite plus shared observability tests: **293 passed,
6 skipped**. The delegated-child regression uses Hermes's pinned child
constructor in both host and sandbox observer paths and both
installation orders. It verifies strict Gym schema acceptance,
child-owned summary response IDs and limit outcome, and unchanged parent
state. Other tests cover summary-error independence, one notification
per limit, and sandbox observation import.
- `pre-commit run --all-files` and `git diff --check` passed. All
commits have DCO sign-off. Rebase compatibility changes are limited to
the supervisor import and the sandbox observation test’s required
`runtime_info` argument.
- Fresh controlled conformance suite: `python
scripts/run_harness_conformance.py --harness hermes --output
<new-directory>` passed **7/7 scenarios** on the rebased head, including
retry, omitted usage, terminal model error, and verifier failure
scenarios.
- Earlier controlled HTTP check: pinned Hermes → live Gym Model Server →
scripted upstream returned HTTP 200 for a forced root summary, with an
owned response ID and captured call. Outgoing tool calls had no internal
fields. Script: `/tmp/hermes-summary-http-smoke-gym.py`.
- Real-model root-summary smoke: HSG job `7676935` completed against
earlier Gym commit `030307b48d4267a58b5c952cde1f0dd758b56a3c` on Super
3.5 direct P/D serving with `max_turns=1`, observability and model-call
capture. Initial and limit-summary calls returned HTTP 200 and belong to
the root invocation, with no trajectory gaps. The response is
`incomplete` with `stop_reason=max_iterations` and no error. The
verifier applied a patch and graded it unresolved; cleanup job `7676936`
found zero sandboxes. Its summary response was reasoning-only, so Hermes
appended no substantive assistant summary. Evidence:
`/lustre/fsw/portfolios/nemotron/users/glovisotto/nemo-evaluator-rundirs/super-3dot5-pd/swe-bench-pro-hermes-summary-smoke/20261005_102034-a219dd2ebd76f36d/results`
on HSG. This predates the child and invocation-hook changes, so it
validates only the root summary path.
- Real-model delegated-child smoke before this rebase: HSG job `7755765`
completed against `5a6784a69c7cb8e13ee7643db14469cfddd87b1f` on Super
3.5 direct P/D serving with explicit delegation tools, parent cap 3,
child cap 1, observability, and model-call capture. The model created
`root.child-1` through `delegate_task`; all six calls returned HTTP 200,
with two response IDs owned by the child and four by the root. The child
is `incomplete` with `stop_reason=max_iterations`; the parent made two
more model calls after the child returned, then independently reached
its own limit and has the same stop reason. The rollout has no failure
row or observation/trajectory gaps. The verifier applied a patch and
graded it unresolved; cleanup job `7755766` found zero remaining
sandboxes. Capture request bodies contain no internal
`call_id`/`response_item_id` fields. Evidence:
`/lustre/fsw/portfolios/nemotron/users/glovisotto/nemo-evaluator-rundirs/super-3dot5-pd/swe-bench-pro-hermes-child-summary-smoke/20261006_193101-3549a070ecb3cafb/results`
on HSG. Health flags only the separate zero-aggregate-usage mismatch
tracked by NVIDIA-NeMo#3981 /
[FEA-397](https://linear.app/nvidia/issue/FEA-397/hermes-report-native-token-usage).

The [rebased CI
run](https://github.com/NVIDIA-NeMo/Gym/actions/runs/38126348032)
records validation of the current head. The live-model smokes above are
historical, with their source commits stated explicitly; this rebase
changes no intended runtime behavior.

CI: core coverage, all eight server-suite shards, `Nemo_CICD_Test`,
lint, and DCO passed on the rebased head.

CI conformance: Hermes passes **7/7** on this head. The overall P0 check
remains red for OpenCode (2 failed scenarios), Pi (1), and Codex (7),
matching the [current-main
baseline](https://github.com/NVIDIA-NeMo/Gym/actions/runs/38123997566)
exactly. Those failures are outside this Hermes summary fix.

---------

Signed-off-by: Giulio Lovisotto <[email protected]>
yaoyu-33 and others added 2 commits October 20, 2026 09:31
Re-apply the lifecycle usage capture onto main's checkpointed
single_agent_turn run(): start after Resources seeding and before Agent
session creation, resume at invoke_agent with a fresh capture, and report
unknown usage when a continuation resumes after the agent already ran.
Document that enabled capture replaces agent usage in the model-call
capture page and that zero captured calls report null.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Resolve the harness conformance registry conflict by taking main's
harness list, and restore every file outside this PR to main's version
so the branch differs from main only by the token usage change.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
yaoyu-33 and others added 2 commits November 17, 2026 16:08
Keep main's seed_episode_sessions flow and start usage capture after the
Resources and tool server seeds. Move model_usage into nemo_gym.rollouts
and its test into tests/unit_tests/rollouts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
- Wait for pending capture writes before reading usage; report null if a
  claimed write never lands.
- Report null usage for any checkpoint continuation before Agent close,
  including invoke_agent: the replaced attempt's calls sit under another
  capture key.
- Skip failed calls that returned no response and no usage, as the
  rollout health contract documents; all-rejected windows sum to zero.
- Exclude verifier-tagged exchanges and sum cache-write tokens.
- Do not create the capture directory on the lifecycle owner's host.
- Scope the docs to single_agent_turn(_legacy) and Hermes /run, and
  replace vague "native"/"legacy" wording with the actual source.
- Add tests for restores, pending writes, failed calls, skipped
  verification and CaptureStore offsets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@yaoyu-33 yaoyu-33 changed the title fix(agent): report native and captured token usage fix(agent): reconcile harness-reported and captured token usage Nov 18, 2026
@yaoyu-33

Copy link
Copy Markdown
Contributor Author

/ok to test 56060aa

@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 18, 2026 00:33
@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

An Environment Server or Hermes /run that sees observability_enabled
without a usable model_call_capture_dir failed every episode while
parsing the capture config. Treat that as unknown usage and log it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@yaoyu-33

Copy link
Copy Markdown
Contributor Author

/ok to test f18225a

This branch was previously deployed

1 inactive (outdated) deployment
public — cedcd1bc Deployed Oct 7, 2026 by copy-pr-bot[bot] via release / finalize / notify #4556
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:agent Agent harnesses and Responses API agent behavior bug Something isn't working complexity:high Cross-component or shared-contract change with a large review surface needs-review PR is ready for code review and waiting on a reviewer sla:triage-overdue Review assignment is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants