Skip to content

fix(agents): report unknown cached tokens as null instead of 0 - #6127

Merged
lafrancef merged 6 commits into
mainfrom
flafrance/unknown-cached-tokens
Nov 16, 2026
Merged

lafrancef merged 6 commits into
mainfrom
flafrance/unknown-cached-tokens

Conversation

@lafrancef

Copy link
Copy Markdown
Contributor

What does this PR do?

Agents stop fabricating cached_tokens=0 in the rollout's response.usage.input_tokens_details. A 0 reads as "no
prefix-cache hits"; for these agents it meant "the harness reported no cache count". Following the contract #4761 set
(usage is the sum over policy-model responses; an unknown detail stays unknown), each agent now reports:

  1. the cache reads the harness reported, summed over calls;
  2. None when that cannot be established;
  3. 0 only for a known zero, with a comment saying why.

Pi, OpenClaw, OpenCode, Kilo and Codex write 0 for a counter the backend did not report, so for them only a positive
count is a measurement, and one unmeasured call makes the sum None. That is the rule their sandbox paths already
apply; this PR applies it to the remaining paths.

Agent Before After
prime_agent sum of cacheRead (0 when absent); 0 on failure sum of positive cacheRead, else None
pi_agent (process path) always 0 sum of positive cacheRead, else None
openclaw_agent (CLI envelope) cacheRead or 0 positive cacheRead, else None
pinchbench sum of cacheRead + cached_tokens (0 when absent, double count when both) per call, OpenClaw cacheRead > 0 or reported cached_tokens; else None
opencode_agent (process path) always 0 sum of positive step cache.read, else None
kilocode_agent (process path) always 0 sum of positive step cache.read, else None
codex_agent (process path) cached_input_tokens summed, 0 when absent positive values only, else None; reasoning likewise (one parser for both paths)
cline_agent (process path) always 0 cacheReadTokens / totalCacheReadTokens as reported, else None
harbor_agent ATIF / n_cache_tokens, 0 when absent; error path 0 as reported, else None
harbor_agent_general, terminus_2_agent, terminus_2_sandboxed_agent n_cache_tokens or 0 n_cache_tokens as reported
hermes_sandboxed_agent, verifiers_agent, simple_strands_agent reported value, 0 when absent reported value, else None
mini_swe_agent, mini_swe_agent_2 placeholder usage with 0 placeholder None
harbor_oracle_agent 0 0, a known zero: no model call

Unchanged known zeros: vllm_model's local response for a request the backend rejected before execution (already
commented), and NeMoGymResponseUsage.sum_from_list([]) (the sum over no responses). Downstream readers (ng_perf,
the perf summary, ATIF export and reverification, harness capability checks) already treat None as unobserved.

claude_code_agent is covered by #5227.

Contract and guard

  • NeMoGymResponseUsage docstring, Add or update a harness
    and Rollout evidence state the rule for agent
    authors. The remote-agent example no longer writes 0 for counts it does not read.
  • tests/unit_tests/test_cached_tokens_contract.py fails on a literal cached-token zero
    (cached_tokens=0, "cached_tokens": 0, .get("cached_tokens", 0), also cached_input_tokens) in non-test code
    under responses_api_agents/, unless the line ends with # known-zero. claude_code_agent/app.py is exempt
    until fix(claude-code): count cached and subagent tokens in usage #5227 merges.

Known limitation

Harbor's UsageInfo.cache_tokens is a required int, so in Terminus-2 and Harbor runs a count the backend did not
report reaches Harbor's totals as 0 before Gym reads them. The adapters now say so in a comment.

Compatibility

Rows from these agents carry cached_tokens: null where they carried a fabricated 0; codex_agent process-path rows
also carry reasoning_tokens: null when Codex reported none. Mean cached-token metrics over these agents now include
only rollouts that measured cache reads. No config or API change.

🤖 Generated with Claude Code

Agents wrote input_tokens_details.cached_tokens=0 when the harness reported no
cache reads, so consumers read "no prefix-cache hits" where the truth was
"unknown". Report the harness-reported count summed over calls, None when it
cannot be established, and 0 only for a known zero. Pi, OpenClaw, OpenCode,
Kilo and Codex write zero for a counter the backend did not report, so only
positive counts are measurements there, as their sandbox paths already do.

Document the rule for agent authors and add a unit test that rejects a literal
cached-token zero under responses_api_agents/ without a known-zero comment.

Signed-off-by: Frederic Lafrance <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Nov 13, 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.

@lafrancef

Copy link
Copy Markdown
Contributor Author

/ok to test c7e9646

@lafrancef

Copy link
Copy Markdown
Contributor Author

/review

@svcnvidia-nemo-ci svcnvidia-nemo-ci left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SHIP WITH CARE — two PinchBench cache-accounting issues and missing rollout-validation evidence.

The inline findings cover a newly introduced alias-fallback regression and a pre-existing missing-usage guard that still bypasses the completeness rule this PR adds. Both affect cache telemetry, not demonstrated reward correctness.

RISK — Record representative real smoke-rollout evidence

The supplied PR description lists no executed validation or representative model-backed rollout results. These changes alter agent responses, so the smoke-rollout requirement in AGENTS.md applies. The PR guidance also requires recording the exact validation and rollout evidence.

Could you add representative real rollout results for the changed usage-extraction and forwarding paths, identifying the commands, harness versions, raw usage artifacts, emitted responses, and verifier outcomes? Compare the raw cache evidence with the response: reported positive counts must survive, unavailable details must become null, and directly measured zeros must remain zero. Include a multi-call case showing that an unknown count prevents publishing a subtotal. Confirm that text, tool calls/results, and verification still work. These are requested acceptance checks, not executed results.

I inspected all 40 changed files and traced the affected response construction, nullable usage models, accumulation, metrics, and ATIF consumers. The artifact-review child's report wasn't available, so I independently checked its assigned paths. This was a static review; I didn't execute tests or model-backed rollouts, and external harness implementations weren't available for independent inspection.


Inline comments (escaped v1):

  • responses_api_agents/pinchbench/app.py line 607: RISK — Let a measured nested detail survive an unmeasured alias

    For an assistant message with usage={"input_tokens":10,"output_tokens":2,"cacheRead":0,"input_tokens_details":{"cached_tokens":5}}, this selection block returns cached_tokens=None, although the nested detail reports 5. The base returned 5. Testing alias presence rather than whether it supplies a measurement drops valid cache data when cacheRead is zero or null.

    Could you replace lines 607–614 with:

    cache_read = usage.get("cacheRead")
    if type(cache_read) is int and cache_read > 0:
        call_cached = cache_read
    else:
        cache_read = input_details.get("cached_tokens")
        call_cached = cache_read if type(cache_read) is int and cache_read >= 0 else None

    This counts one measured alias per call. Preserve positive cacheRead precedence when both fields exist, so the double-counting fix remains intact; preserve nested measured zero and an unknown result when neither field establishes a measurement.

    Proposed regression checks, not executed: through _response_from_transcript_events, assert that cacheRead=0 or null plus nested 5 yields 5; both aliases reporting 5 yield 5, not 10; nested zero alone yields zero; and zero cacheRead without a nested count yields null. Retain the existing mixed-call assertions that make the total unknown when any call lacks a measured count. Verify this suggested replacement before adopting it.

  • responses_api_agents/pinchbench/app.py line 595: RISK — Include missing usage objects in the completeness decision

    With two assistant transcript messages, one reporting usage={"input":10,"output":2,"cacheRead":5} and one without usage, _usage_from_transcript returns cached_tokens=5 instead of null. An empty usage dictionary makes the new accumulator unknown, but an absent, null, or non-dictionary object takes this early continue without clearing cache_measured. This guard gap already existed in the base; it remains in the changed accounting path and contradicts the new every-call completeness rule.

    Could you change that branch to:

    usage = message.get("usage")
    if not isinstance(usage, dict):
        cache_measured = False
        continue

    The invariant is that every counted assistant call must establish its cache count before the rollout reports a measured sum. Preserve available input/output subtotals, all-measured positive sums, and nested measured zero. Continue ignoring non-assistant messages and malformed non-message records.

    Proposed regression checks, not executed: pair a call reporting 5 cache reads with an assistant message whose usage is absent, null, or a string, in both orders; assert that the response's cached-token detail is null. A user or tool-result message without usage must leave an otherwise measured total of 5 intact. Retain the malformed-usage regression's Done. output and zero input/output total. Verify this suggested change before adopting it.

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

…as unknown

Signed-off-by: Frederic Lafrance <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

github-actions Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

@lafrancef

Copy link
Copy Markdown
Contributor Author

/ok to test 596e9f2

@lafrancef
lafrancef marked this pull request as ready for review November 13, 2026 15:31

@svcnvidia-nemo-ci svcnvidia-nemo-ci left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SHIP WITH CARE — both PinchBench code findings are fixed; the prior rollout-validation finding remains unresolved.

The current implementation now preserves a measured nested cache count when cacheRead is zero or null, and makes the total unknown when an assistant message lacks valid usage. The regression assertions cover those failures, double-count prevention, nested measured zero, both missing-usage orders, and non-assistant preservation. I verified these fixes statically; I didn't execute the tests.

RISK — Record representative real smoke-rollout evidence

This remains the validation gap reported in review 5892576545. The supplied current description and comments still contain no executed validation or representative model-backed rollout results. Behavior-changing agent work requires real smoke rollouts, with exact validation and rollout evidence recorded. Synthetic usage fixtures don't establish that the supported harness versions emit the assumed records or that the converted responses work through verification. Compatibility remains unvalidated; this is not evidence of incorrect rewards.

Could you run representative model-backed smoke rollouts on the final head and add the commands/configurations, model and harness versions, raw usage artifacts, emitted responses, and verifier outcomes to the PR description? Cover representative changed extraction and forwarding paths with these expected outcomes:

  • Positive reported cache counts survive conversion and sum across measured calls.
  • Missing details and harness zeros meaning unavailable become null; one unknown call makes a mixed-call total null, not a subtotal.
  • A directly measured zero remains zero on a path that distinguishes it from unavailable data.
  • Text, tool-call arguments, tool-result linkage/content, and verification remain intact. Retain the concrete behavior in the existing trajectory assertions.

These are requested acceptance checks, not executed results.

This was a follow-up against c7e9646, limited to the prior findings, subsequent PinchBench changes, and directly affected response/usage paths—not a fresh whole-PR review. All three delegated topics reached terminal status; one detailed child report wasn't available, so I independently inspected that topic. I didn't execute tests or model-backed rollouts.

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

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

Reviewed 596e9f2. No blocking findings. The PinchBench fixes preserve measured aliases and make mixed known/unknown totals unknown. Changing cache details from zero to null leaves the input/output-token health checks unchanged.

Non-blocking follow-up: exercise the supported harness versions in conformance testing, comparing raw emitted usage with the converted response for positive counts, unavailable details, measured zero, and mixed-call totals. Verifying what an external harness actually emits belongs in that coverage; it is not a unit-test responsibility or a blocker for this approval.

Separately, ng_perf still sums available per-call cache counts when other calls are unknown, and its coverage measures matched calls rather than cache-count completeness. That predates this PR and can be addressed independently.

Validation: 1,869 distinct tests passed across usage contracts, affected harnesses, rollout health, performance aggregation, ATIF and conformance checks; 19 skipped. Harbor, Terminus and Verifiers suites could not run because their optional dependencies were unavailable. No live model rollouts were run.

— @codex

Resolve prime_agent: keep main's agent-session parsing (timed_out, failed flag)
and this branch's measured-only cache-read sum.

Signed-off-by: Frederic Lafrance <[email protected]>
@lafrancef

Copy link
Copy Markdown
Contributor Author

/ok to test 31c2569

Terminus 2 now tracks unknown cache reads per call (#5650); keep that and
leave a missing total_cached_tokens unknown instead of defaulting it to 0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@lafrancef

Copy link
Copy Markdown
Contributor Author

/ok to test 27c56ba

@iguehring-nvidia

Copy link
Copy Markdown
Contributor

@lafrancef if you sign your commits, you don't need to write /ok to test anymore.

Comment thread responses_api_agents/cline_agent/app.py Resolved
Comment thread responses_api_agents/cline_agent/app.py Resolved
@lafrancef

Copy link
Copy Markdown
Contributor Author

/ok to test 852dfd7

@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team November 16, 2026 08:32

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

Re-reviewed 852dfd7 against the previously approved 596e9f2. No blocking findings.

The main-merge resolutions preserve Prime's retry/timeout handling and Terminus's per-call cache completeness tracking. The new Cline process-path change preserves unknown counts, omits usage when input/output totals are unavailable, and avoids adding cache reads twice for the openai-compatible provider.

Non-blocking documentation follow-up: cline_agent/README.md still says the host path double-counts cache reads for openai-compatible (the usage paragraph and Limitations section). That caveat can now be removed or updated to describe the provider-aware accounting.

Fresh validation: 629 tests passed, 8 skipped across the Cline and Prime app/session suites, cached-token contract guard, and rollout health. Five focused probes of the actual Terminus response-conversion method also passed (missing, zero, positive, unknown cache evidence, and unknown overall usage); the external Harbor runtime was not exercised. No live model rollouts run. The earlier conformance-testing follow-up remains non-blocking.

— @codex

Reasoning, input and output counts Cline does not report stay None instead
of 0, and the response's usage is None without input and output counts.
openai-compatible's inputTokens already include cache reads (as the session
path notes), so cache reads are added only for other providers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Frederic Lafrance <[email protected]>
@lafrancef
lafrancef force-pushed the flafrance/unknown-cached-tokens branch from 852dfd7 to f729911 Compare November 16, 2026 14:05
Cline 3.0.55 leaves cacheReadTokens out of a call's usage event when the
provider reported no cache reads, but counts that call as 0 in its run_result
aggregate and running totals. A rollout with an unreported call therefore
showed the sum of the reported calls (or 0) instead of an unknown count.

Trust the aggregate cache reads only when every per-call usage event reported
them, on both the host and the sandbox path; otherwise cached_tokens is None
(and so is the prompt total for providers that report cache reads separately).

Signed-off-by: Frederic Lafrance <[email protected]>

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@lafrancef

Copy link
Copy Markdown
Contributor Author

Smoke rollouts on an OpenAI-compatible endpoint that sometimes omits prompt_tokens_details and otherwise reports positive cached_tokens: opencode_agent (f729911) reported null for every rollout with an unmeasured step (per-step cache reads 0/23040, 0/32512/33280, and a single unmeasured step) and 24896 when both steps reported cache reads (7232 + 17664). cline_agent (95ae590) kept 16832 when all three calls reported cache reads (5952 + 10752 + 128), and reported null instead of Cline's 0-filled aggregate when one call was unmeasured (47360 and 135552 aggregates) or when the endpoint reported none (aggregate 0).

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

Re-reviewed current head 95ae590. No blocking findings.

The rewritten f729911 has the same tree as the previously reviewed 852dfd7. The new Cline change correctly makes cache totals unknown when any observed per-call usage event lacks a valid cache count, in both the process and sandbox paths. Measured zero and fully measured positive totals remain intact; providers whose input totals exclude cache reads also leave the input total unknown when those reads are missing.

Fresh validation: 197 tests passed across Cline's app/session suites and the cached-token contract guard. Read the author's posted OpenCode/Cline smoke results; those live rollouts were not independently rerun in this review.

— @codex

@lafrancef

Copy link
Copy Markdown
Contributor Author

/ok to test 95ae590

@lafrancef
lafrancef enabled auto-merge November 16, 2026 15:22
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team November 16, 2026 15:23
@lafrancef
lafrancef added this pull request to the merge queue Nov 16, 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/43898524384

@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/43899118797

Merged via the queue into main with commit 2ec7ca0 Nov 16, 2026
92 of 94 checks passed
@lafrancef
lafrancef deleted the flafrance/unknown-cached-tokens branch November 16, 2026 15:56
yaoyu-33 added a commit to yaoyu-33/Gym that referenced this pull request Nov 16, 2026
Keep the deletion of responses_api_agents/hermes_sandboxed_agent, whose
app.py and tests main's cached-token change (NVIDIA-NeMo#6127) modified.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@svcnvidia-nemo-ci svcnvidia-nemo-ci added bug Something isn't working area:agent Agent harnesses and Responses API agent behavior ready-to-merge PR is approved, current, and waiting for final CI or merge labels Nov 16, 2026
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 ready-to-merge PR is approved, current, and waiting for final CI or merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants