Repository navigation
fix(agents): report unknown cached tokens as null instead of 0 - #6127
Conversation
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]>
|
/ok to test c7e9646 |
|
/review |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
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.pyline 607: RISK — Let a measured nested detail survive an unmeasured aliasFor an assistant message with
usage={"input_tokens":10,"output_tokens":2,"cacheRead":0,"input_tokens_details":{"cached_tokens":5}}, this selection block returnscached_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 whencacheReadis 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
cacheReadprecedence 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 thatcacheRead=0or null plus nested 5 yields 5; both aliases reporting 5 yield 5, not 10; nested zero alone yields zero; and zerocacheReadwithout 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.pyline 595: RISK — Include missing usage objects in the completeness decisionWith two assistant transcript messages, one reporting
usage={"input":10,"output":2,"cacheRead":5}and one withoutusage,_usage_from_transcriptreturnscached_tokens=5instead of null. An empty usage dictionary makes the new accumulator unknown, but an absent, null, or non-dictionary object takes this early continue without clearingcache_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]>
|
/ok to test 596e9f2 |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
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 totalnull, 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
left a comment
There was a problem hiding this comment.
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]>
|
/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]>
|
/ok to test 27c56ba |
|
@lafrancef if you sign your commits, you don't need to write /ok to test anymore. |
|
/ok to test 852dfd7 |
giuliolovisotto
left a comment
There was a problem hiding this comment.
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]>
852dfd7 to
f729911
Compare
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]>
95ae590
|
Smoke rollouts on an OpenAI-compatible endpoint that sometimes omits |
giuliolovisotto
left a comment
There was a problem hiding this comment.
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
|
/ok to test 95ae590 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/43898524384 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/43899118797 |
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]>
What does this PR do?
Agents stop fabricating
cached_tokens=0in the rollout'sresponse.usage.input_tokens_details. A 0 reads as "noprefix-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:
Nonewhen that cannot be established;0only 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 alreadyapply; this PR applies it to the remaining paths.
prime_agentcacheRead(0 when absent); 0 on failurecacheRead, elseNonepi_agent(process path)cacheRead, elseNoneopenclaw_agent(CLI envelope)cacheReador 0cacheRead, elseNonepinchbenchcacheRead+cached_tokens(0 when absent, double count when both)cacheRead> 0 or reportedcached_tokens; elseNoneopencode_agent(process path)cache.read, elseNonekilocode_agent(process path)cache.read, elseNonecodex_agent(process path)cached_input_tokenssummed, 0 when absentNone; reasoning likewise (one parser for both paths)cline_agent(process path)cacheReadTokens/totalCacheReadTokensas reported, elseNoneharbor_agentn_cache_tokens, 0 when absent; error path 0Noneharbor_agent_general,terminus_2_agent,terminus_2_sandboxed_agentn_cache_tokens or 0n_cache_tokensas reportedhermes_sandboxed_agent,verifiers_agent,simple_strands_agentNonemini_swe_agent,mini_swe_agent_2Noneharbor_oracle_agentUnchanged known zeros:
vllm_model's local response for a request the backend rejected before execution (alreadycommented), 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
Noneas unobserved.claude_code_agentis covered by #5227.Contract and guard
NeMoGymResponseUsagedocstring, Add or update a harnessand 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.pyfails on a literal cached-token zero(
cached_tokens=0,"cached_tokens": 0,.get("cached_tokens", 0), alsocached_input_tokens) in non-test codeunder
responses_api_agents/, unless the line ends with# known-zero.claude_code_agent/app.pyis exemptuntil fix(claude-code): count cached and subagent tokens in usage #5227 merges.
Known limitation
Harbor's
UsageInfo.cache_tokensis a required int, so in Terminus-2 and Harbor runs a count the backend did notreport 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: nullwhere they carried a fabricated 0;codex_agentprocess-path rowsalso carry
reasoning_tokens: nullwhen Codex reported none. Mean cached-token metrics over these agents now includeonly rollouts that measured cache reads. No config or API change.
🤖 Generated with Claude Code