Skip to content

fix(frontend): don't count a held tool call as reasoning tokens - #18656

Merged
indrajit96 merged 3 commits into
ai-dynamo:mainfrom
cipheraxat:fix/18573-reasoning-tokens-held-tool-call
Nov 19, 2026
Merged

indrajit96 merged 3 commits into
ai-dynamo:mainfrom
cipheraxat:fix/18573-reasoning-tokens-held-tool-call

Conversation

@cipheraxat

@cipheraxat cipheraxat commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Overview

With --dyn-tool-call-parser glm47, usage.completion_tokens_details.reasoning_tokens counted almost a whole tool call as reasoning: 1,309 of 1,311 tokens in the issue's example, where the thought was about 13. This PR makes the frontend estimate count only the thought.

Root cause: ReasoningUsageEstimator counted every chunk that showed nothing, for a choice still in reasoning, as reasoning, to cover a parser holding back a partial </think>. The glm47 unified parser emits a tool call only once it is complete, so every chunk of the call after </think> is empty and was counted.

Key Changes

About 35 core-logic lines, all in preprocessor.rs:

  • ReasoningUsageEstimator holds the tokens of those empty chunks per choice instead of counting them at once, and settles them by what the parser releases next: reasoning or text keeps them as reasoning (a held </think>), a tool call drops them.
  • Tokens still held when the usage chunk arrives count as reasoning, as before. A positive count from the backend stays authoritative.

Streaming parsers (qwen3, hermes), text answers and the legacy parser path behave as before.

Validation

Case Before After
glm47: 4 thought chunks, then a tool call held until complete reasoning_tokens 33 4
Empty chunk (held </think>), then text counted as reasoning unchanged
Positive backend count authoritative unchanged

New tests:

  • reasoning_usage_excludes_a_held_tool_call (the issue's reproducer) runs the real glm47 unified parser through apply_unified_response_policies. It also asserts that the call is emitted, so it can't pass by dropping it.
  • reasoning_usage_settles_held_tokens_per_choice covers two choices: a token still held at the usage chunk stays reasoning, and a tool call drops only its own choice's held tokens.

Run on a Colab L4 VM (12 vCPU, Linux x86_64; CPU-only test):

cargo test -p dynamo-llm --no-default-features --lib -- reasoning_usage
  • Base 3e84909a19 with only the new tests: both fail, Some(33) vs Some(4) and Some(4) vs Some(3).
  • With the fix: 6/6 pass. The full dynamo-llm lib suite passes (3,754 passed, 0 failed).

Known limits:

  • If a partial </think> is held together with the following tool call, its one or two marker tokens are dropped with the call. The estimate can be slightly low in that case, never high.
  • When tool calls aren't emitted (tool_choice: none), apply_tool_call_response_policy strips the call before the estimator sees it, so the held call still counts as reasoning, as on main.

Issues and Ongoing Work

Pull Request Checklist
  • I used Dynamo's /pr-checklist skill.

AI assistance was used to prepare this change. Every result above was run and checked.

ReasoningUsageEstimator counted every chunk that showed nothing, for a
choice still in reasoning, as reasoning. A parser that emits a tool call
only once it is complete (glm47) makes every chunk of the call empty, so
the whole call was counted. Hold those tokens per choice and settle them
by what the parser releases next: reasoning or text keeps them as
reasoning (a held </think>), a tool call drops them.

Fixes ai-dynamo#18573

Signed-off-by: cipheraxat <[email protected]>
@copy-pr-bot

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

@cipheraxat
cipheraxat temporarily deployed to external_collaborator November 12, 2026 11:23 — with GitHub Actions Inactive
@cipheraxat
cipheraxat temporarily deployed to external_collaborator November 12, 2026 11:23 — with GitHub Actions Inactive
@github-actions github-actions Bot added the fix label Nov 12, 2026
@github-actions

Copy link
Copy Markdown
Contributor

👋 Hi cipheraxat! Thank you for contributing to ai-dynamo/dynamo.

Just a reminder: The NVIDIA Test Github Validation CI runs an essential subset of the testing framework to quickly catch errors.Your PR reviewers may elect to test the changes comprehensively before approving your changes.

🚀

@github-actions github-actions Bot added external-contribution Pull request is from an external contributor frontend `python -m dynamo.frontend` and `dynamo-run in=http|text|grpc` labels Nov 12, 2026
@cipheraxat
cipheraxat marked this pull request as ready for review November 12, 2026 11:42
@cipheraxat
cipheraxat requested a review from a team as a code owner November 12, 2026 11:42
@coderabbitai

coderabbitai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The estimator now defers token counts for active choices with no visible output. It classifies held counts when reasoning text or visible output arrives, excludes held tool-call tokens, and includes unresolved counts in usage unless the backend provides a positive reasoning-token count. A regression test covers a parser-buffered tool call.

Changes

Reasoning usage estimation

Layer / File(s) Summary
Held token classification and regression coverage
lib/llm/src/preprocessor.rs
ReasoningUsageEstimator holds counts for active choices with no visible output. It settles those counts as reasoning when reasoning text arrives, or excludes them when visible output contains a tool call. Usage annotation includes unresolved counts when the backend has no positive reasoning-token count. A test verifies that buffered tool-call tokens are excluded from the reasoning estimate.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Severity of issue fixed: Medium

Merge Risk: Minimal · up to a632d

The change stops a held tool call from being counted as reasoning tokens in usage reporting. No concrete merge-blocking risk was identified.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: a held tool call is no longer counted as reasoning tokens in the frontend usage estimate. It is specific, uses a conventional prefix, and matches the raw summary and o…
Linked Issues check Passed [#18573] The issue requires that reasoning_tokens count only the thought for the glm47 unified parser. Held tool-call chunks after </think> must not count as reasoning. The PR changes `Reasoning…
Out of Scope Changes check Passed The raw summary places the change in lib/llm/src/preprocessor.rs (+119/-8). It covers the ReasoningUsageEstimator buffering logic and a regression test for the same behavior. The summary reports n…
Description check Passed The description follows the template's main sections: Overview, Key Changes, Validation, and Issues and Ongoing Work, and it includes the checklist. It explains the root cause, the code change, the te…
Full details: Title check

Explanation

The title names the main change: a held tool call is no longer counted as reasoning tokens in the frontend usage estimate. It is specific, uses a conventional prefix, and matches the raw summary and objectives. It is 63 characters and 10 words, within a concise range.

Full details: Linked Issues check

Explanation

[#18573] The issue requires that reasoning_tokens count only the thought for the glm47 unified parser. Held tool-call chunks after &lt;/think&gt; must not count as reasoning. The PR changes ReasoningUsageEstimator in lib/llm/src/preprocessor.rs to hold empty-chunk token counts per choice. A later tool_call release drops them. Reasoning or text release keeps them as reasoning, so a held &lt;/think&gt; still counts. Tokens still held at usage time count as reasoning, and a positive backend count stays authoritative. The raw summary states that a new test verifies held tool-call tokens are excluded from the reasoning estimate. The PR description reports the reproducer (reasoning_usage_excludes_a_held_tool_call) asserts Some(4), runs the real glm47 parser through apply_unified_response_policies, and also asserts the call is emitted. The issue's proposed fix (a crate-level in_reasoning() accessor) differs from this approach. The issue requires the behavior, not that mechanism. The issue states that streaming qwen3/hermes, text answers, and completion_tokens are unaffected. The PR description reports those paths are unchanged. Limit: the diff read failed, so the code and test were not read directly. The verdict relies on the PR description and raw summary, and on the reported test results (5/5 targeted tests; 3,753 lib tests passed).

Full details: Out of Scope Changes check

Explanation

The raw summary places the change in lib/llm/src/preprocessor.rs (+119/-8). It covers the ReasoningUsageEstimator buffering logic and a regression test for the same behavior. The summary reports no changes to exported or public declarations. The PR description states the streaming parsers, text answers, and legacy parser path are unchanged. It also says the Anthropic stream converter (anthropic/stream_converter.rs, PR #18377) is not touched. All changed behavior maps to #18573. Limit: the file diff could not be read, so the claim that no other hunks exist rests on the summary and PR description.

Full details: Description check

Explanation

The description follows the template's main sections: Overview, Key Changes, Validation, and Issues and Ongoing Work, and it includes the checklist. It explains the root cause, the code change, the test results, and the known limits. It links the issue with "Closes #18573". The checklist item is marked as used. The template's "Closes #XXXX" line is filled in. Nothing critical is missing, so the check passes.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between a355698 and a632dba.

Files selected for processing: 1

  • lib/llm/src/preprocessor.rs

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.

@cipheraxat
cipheraxat temporarily deployed to external_collaborator November 12, 2026 12:29 — with GitHub Actions Inactive
@KrishnanPrash

Copy link
Copy Markdown
Contributor

/ok to test d4b268e

@devin-ai-integration

Copy link
Copy Markdown
Contributor

✅ Dynamo PR CI passed — run 43894788914 (attempt 1) on d4b268e59f

Gate checks: ✅ backend-status-check · ✅ deploy-status-check · ✅ dynamo-status-check

Posted automatically by Devin for run 43894788914. Updated on every full-CI run of this PR.

@devin-ai-integration

Copy link
Copy Markdown
Contributor

External PR triage

Blocker: Review requested on 2026-11-12 and idle for more than 72h. Trusted CI is green for the current head (approved 2026-11-16).

Next action: @ai-dynamo/dynamo-frontend-codeowners: please review/approve.

Written by Devin

@indrajit96

Copy link
Copy Markdown
Contributor

LGTM, thanks for the fix! Reviewed at d4b268e59f; here's what I ran.

Existing tests

  • New tests in this PR: 6/6 pass
  • preprocessor:: + protocols::openai::chat_completions unit suites: 821 passed, 0 failed

Reasoning-token count by family and tool_choice mode

Each case: a 4-token thought, then a write_file call, streamed in 4-character chunks through apply_stream_with_constraint + apply_unified_response_policies. Families tested: qwen3, kimi_k2, kimi_k3, deepseek_v4, deepseek_v41, gemma4, glm47, muse_glimmer.

tool_choice base (3e84909a19) this PR
auto 28–62 (by family) 4
structural tag 28–62 (by family) 4
required, 1 call 12 4
required, 2 calls 12 4
named 4 4
required, DYN_ENABLE_GUIDED_TOOL_STREAMING=0 28 4
named, DYN_ENABLE_GUIDED_TOOL_STREAMING=0 19 4

All 56 cases count correctly on this PR (base over-counted in 48), and every case still emits the right number of tool calls.

Edge cases (glm47)

  • Two calls in one turn: 33 → 4
  • </think> split across chunks with the call right after: 35 → 5 (one marker token, fine)
  • Text before the call, and text-only answers: unchanged from base
  • Multiple choices (n > 1): covered by reasoning_usage_settles_held_tokens_per_choice

Other paths

  • Legacy (non-unified) parser path: unchanged
  • Python --dyn-chat-processor vllm: not affected; it counts reasoning by token IDs

Latency
No TTFT impact: the estimator runs synchronously on each chunk and never holds one back. In a debug build over 200k chunks, the first chunk took 20 µs on both base and this PR; the per-chunk cost went up by 0.15–0.22 µs.

Not changed by this PR (already wrong on base, out of scope)

  • With tool_choice: "none", call text the model still writes is counted as reasoning
  • A call cut off by max_tokens is counted as reasoning

@indrajit96
indrajit96 merged commit 58b3ce8 into ai-dynamo:main Nov 19, 2026
125 checks passed

This branch was previously deployed

1 inactive deployment
external_collaborator — d4b268e5 Deployed Nov 12, 2026 by cipheraxat via ok-to-test #50505
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

external-contribution Pull request is from an external contributor fix frontend `python -m dynamo.frontend` and `dynamo-run in=http|text|grpc` size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG]: reasoning_tokens counts a held tool call as reasoning (glm47 unified parser)

3 participants