Repository navigation
fix(ollama): use CJK-aware char estimate for usage fallback - #110073
Conversation
|
Codex review: needs maintainer review before merge. Reviewed July 31, 2026, 5:17 AM ET / 09:17 UTC. ClawSweeper reviewWhat this changesThis PR makes Ollama’s missing-usage fallback estimate CJK-heavy prompt and completion text with CJK-aware character weighting before deriving token counts. Merge readinessThe previous SDK-surface and release-note concerns are resolved: the estimator is now private to the Ollama extension, provider-reported usage remains authoritative, and the PR includes focused regression coverage plus real-daemon after-fix evidence. This remains a useful, bounded bug fix rather than a cleanup-close candidate. Priority: P2 Review scores
Verification
How this fits togetherThe Ollama provider extension converts native flowchart LR
A[Agent chat request] --> B[Ollama provider extension]
B --> C[Native NDJSON response]
C --> D{Usage counts present?}
D -->|Yes| E[Provider-reported usage]
D -->|No| F[CJK-aware character estimate]
E --> G[Assistant message usage]
F --> G
G --> H[Context telemetry and compaction]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +51, Tests +103. Total +154 across 3 files. View PR surface stats
Review metricsNone. Stored data modelPersistent data-model change detected: Technical reviewBest possible solution: Land the extension-private fallback change after the required checks finish on the current merge result, preserving provider-reported counts as the first-choice usage source. Do we have a high-confidence way to reproduce the issue? Yes. A final Ollama NDJSON response without valid prompt/output evaluation counts enters the local estimation path; the PR supplies focused coverage and real-daemon strip-proxy evidence for that condition. Is this the best way to solve the issue? Yes. Keeping the CJK weighting private to the Ollama extension fixes its provider-specific fallback without creating a public Plugin SDK contract, while retaining provider-reported counts when they exist. AGENTS.md: unclear because the file could not be read completely. Codex review notes: model internal, reasoning high; reviewed against f03dc9785e48. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (8 earlier review cycles)
|
e69e492 to
7ff839f
Compare
|
@clawsweeper re-review Updated with production-path proof:
|
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
7ff839f to
a7b2363
Compare
|
@clawsweeper re-review Narrowed further after the last review:
|
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review Added real Ollama daemon proof (not loopback-only): Case A — Case B — transparent strip-proxy in front of the real daemon deletes final-chunk eval counts after real CJK generation; production PR body |
|
@clawsweeper automerge |
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
The CJK fallback estimator is now plugin-private rather than expanding the public Plugin SDK, and the release-owned CHANGELOG edit is gone. Focused stream tests, the SDK surface gate, targeted checks, and fresh autoreview are clean. @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Merged via squash.
|
* origin/main: (1976 commits) fix(ollama): models advertise tools when /api/show fails (openclaw#109971) fix(ollama): use CJK-aware char estimate for usage fallback (openclaw#110073) fix(ollama): release failed setup response bodies before returning (openclaw#111802) feat(plugins): externalize Synthetic provider (openclaw#116720) fix(agents): unblock channel turns after restart recovery (openclaw#116728) fix(telegram): keep typing alive during active steered tasks (openclaw#116721) fix(gateway): admit standalone MCP app work (openclaw#116727) fix(googlechat): record canonical receipt thread (openclaw#116717) test(ui): cover the Talk relay start-stop race fix(ui): close superseded Talk allocations fix(agents): resume interrupted turns past progress commentary (openclaw#116725) fix(gateway): sign device proofs with challenge time (openclaw#116679) fix(testing): load relay smoke through UI Vite config test(testing): guard realtime relay smoke module path fix(testing): repair realtime relay live smoke import test: type session request parameters (openclaw#116713) fix: retain event invalidation for pagination docs: note queued session refresh fix fix: preserve queued session refresh options fix(exec): require approval for abbreviated inline eval flags [AI] (openclaw#116529) ...
* commit 'refs/frozen/talk-pcm-output-main': (21 commits) fix(agents): compact session status change text (#116742) fix(llama-cpp): recover plaintext tool calls (#116736) fix(telegram): validate native queue arguments before fallback (#116726) chore(skills): add autonomous issue sweep workflow docs(auto-qa): require clean root-cause refactors fix(ollama): models advertise tools when /api/show fails (#109971) fix(ollama): use CJK-aware char estimate for usage fallback (#110073) fix(ollama): release failed setup response bodies before returning (#111802) feat(plugins): externalize Synthetic provider (#116720) fix(agents): unblock channel turns after restart recovery (#116728) fix(telegram): keep typing alive during active steered tasks (#116721) fix(gateway): admit standalone MCP app work (#116727) test(ui): cover the Talk relay start-stop race fix(ui): close superseded Talk allocations test(google): cover expired CLI OAuth compatibility docs(google): document supported auth paths fix(ui): clarify blocked inference setup fix(google): guide broken CLI profiles to supported auth fix(onboarding): hide unsupported Google CLI setup routes fix(google): retire Gemini CLI OAuth setup ...
* origin/main: (38 commits) fix(agents): compact session status change text (#116742) fix(llama-cpp): recover plaintext tool calls (#116736) fix(telegram): validate native queue arguments before fallback (#116726) chore(skills): add autonomous issue sweep workflow docs(auto-qa): require clean root-cause refactors fix(ollama): models advertise tools when /api/show fails (#109971) fix(ollama): use CJK-aware char estimate for usage fallback (#110073) fix(ollama): release failed setup response bodies before returning (#111802) feat(plugins): externalize Synthetic provider (#116720) fix(agents): unblock channel turns after restart recovery (#116728) fix(telegram): keep typing alive during active steered tasks (#116721) fix(gateway): admit standalone MCP app work (#116727) fix(googlechat): record canonical receipt thread (#116717) test(ui): cover the Talk relay start-stop race fix(ui): close superseded Talk allocations fix(agents): resume interrupted turns past progress commentary (#116725) fix(gateway): sign device proofs with challenge time (#116679) test(google): cover expired CLI OAuth compatibility fix(testing): load relay smoke through UI Vite config test(testing): guard realtime relay smoke module path ...
…#110073) * fix(ollama): use CJK-aware char estimate for usage fallback * fix(ollama): keep CJK estimator plugin-private --------- Co-authored-by: Vincent Koc <[email protected]>
* commit 'refs/frozen/talk-pcm-output-main': (21 commits) fix(agents): compact session status change text (openclaw#116742) fix(llama-cpp): recover plaintext tool calls (openclaw#116736) fix(telegram): validate native queue arguments before fallback (openclaw#116726) chore(skills): add autonomous issue sweep workflow docs(auto-qa): require clean root-cause refactors fix(ollama): models advertise tools when /api/show fails (openclaw#109971) fix(ollama): use CJK-aware char estimate for usage fallback (openclaw#110073) fix(ollama): release failed setup response bodies before returning (openclaw#111802) feat(plugins): externalize Synthetic provider (openclaw#116720) fix(agents): unblock channel turns after restart recovery (openclaw#116728) fix(telegram): keep typing alive during active steered tasks (openclaw#116721) fix(gateway): admit standalone MCP app work (openclaw#116727) test(ui): cover the Talk relay start-stop race fix(ui): close superseded Talk allocations test(google): cover expired CLI OAuth compatibility docs(google): document supported auth paths fix(ui): clarify blocked inference setup fix(google): guide broken CLI profiles to supported auth fix(onboarding): hide unsupported Google CLI setup routes fix(google): retire Gemini CLI OAuth setup ...
* origin/main: (38 commits) fix(agents): compact session status change text (openclaw#116742) fix(llama-cpp): recover plaintext tool calls (openclaw#116736) fix(telegram): validate native queue arguments before fallback (openclaw#116726) chore(skills): add autonomous issue sweep workflow docs(auto-qa): require clean root-cause refactors fix(ollama): models advertise tools when /api/show fails (openclaw#109971) fix(ollama): use CJK-aware char estimate for usage fallback (openclaw#110073) fix(ollama): release failed setup response bodies before returning (openclaw#111802) feat(plugins): externalize Synthetic provider (openclaw#116720) fix(agents): unblock channel turns after restart recovery (openclaw#116728) fix(telegram): keep typing alive during active steered tasks (openclaw#116721) fix(gateway): admit standalone MCP app work (openclaw#116727) fix(googlechat): record canonical receipt thread (openclaw#116717) test(ui): cover the Talk relay start-stop race fix(ui): close superseded Talk allocations fix(agents): resume interrupted turns past progress commentary (openclaw#116725) fix(gateway): sign device proofs with challenge time (openclaw#116679) test(google): cover expired CLI OAuth compatibility fix(testing): load relay smoke through UI Vite config test(testing): guard realtime relay smoke module path ...
What Problem This Solves
Ollama's chat stream reports real usage via
prompt_eval_count/eval_counton the final response chunk. When those fields are missing or invalid (e.g. a
native stream that ends early),
extensions/ollama/src/stream.tsfalls backto estimating tokens as
chars / 4using plain UTF-16.lengthon themessage content, tool-call JSON, and tool names.
That heuristic assumes ~4 chars/token, which holds for Latin/English text but
badly undercounts CJK (Chinese/Japanese/Korean) text, which tokenizes at
roughly 1 char/token. For CJK-heavy conversations that hit this fallback path,
usage is undercounted by 2-4x.
This fallback usage feeds
assistantMessage.usage, which is used both forusage/context telemetry (
/context, treemap, totals) and forcalculateContextTokens→shouldCompactproactive context-windowcompaction decisions. Undercounting on CJK sessions means the agent believes
it has more context headroom than it actually does, delaying proactive
compaction until the provider itself errors on overflow.
Why This Change Was Made
The core already has the correct weighting formula in
src/utils/cjk-chars.ts(
estimateStringChars). Ollama's extension cannot import core internals, andexposing that helper through the public plugin SDK would create a new stable
API commitment for a single consumer. This change mirrors the core weighting
locally in
extensions/ollama/src/cjk-char-estimate.tsand applies it on theproduction stream fallback path only.
This change:
text with the CJK-aware char estimate before the existing
chars / 4rounding.
prompt_eval_count/eval_countauthoritativewhen present.
(2) live generation against a real Ollama daemon, including a strip-proxy
run that forces the missing-count fallback.
User Impact
No change for ASCII/Latin content (the fallback estimate is unchanged for
that case). For CJK-heavy Ollama conversations that hit the native-usage
fallback path, usage/context accounting and proactive compaction triggering
are now accurate instead of undercounting by 2-4x. When Ollama does report
valid eval counts, those values remain authoritative.
Evidence
extensions/ollama/src/stream.ts,extensions/ollama/src/cjk-char-estimate.ts,extensions/ollama/src/stream.test.ts,extensions/ollama/src/stream.usage-fallback.http.proof.test.tscreateOllamaStreamFn→ guarded fetch → NDJSON parse →fallback estimators →
buildAssistantMessage→done.message.usageReal behavior proof
Behavior or issue addressed
When an Ollama NDJSON stream's final chunk omits
prompt_eval_count/eval_count, the production stream path writes CJK-aware fallback usage ontodone.message.usage(roughly 1 token per CJK char) instead of the old rawUTF-16
length / 4undercount. Valid provider-reported eval counts stilloverride the fallback.
Canonical reachability path
createOllamaStreamFn→fetchWithSsrFGuard→/api/chatNDJSON final chunkwithout eval counts →
estimateOllamaPromptTokens/estimateOllamaCompletionTokens→buildAssistantMessage→done.message.usageShared helper / provider constraint check
Local
estimateStringCharsmirrorssrc/utils/cjk-chars.tsso the extensionstays inside the plugin boundary without growing the public SDK surface.
Provider-reported eval counts remain authoritative via
resolveUsageCount.Real environment tested
ollama0.9.6 on macOS arm64, modelqwen2.5:0.5b,listening on
http://127.0.0.1:11434, Node v22.23.1createOllamaStreamFnagainst thereal daemon through a same-request pass-through recording proxy.
done.message.usagematched the daemon final-chunkprompt_eval_count/eval_countexactly.strip-proxy in front of the real daemon. The proxy deletes
prompt_eval_count/eval_countonly on the final NDJSON chunk after thedaemon has already generated the CJK completion — forcing the production
fallback. Observed usage matched
estimateStringChars(...)/4and was~3.8× the naive
length/4undercount.node:httpOllama-shaped NDJSON + focused streamunit tests (real
fetchWithSsrFGuard, no fetch mock).Healthy Ollama almost always emits eval counts, so Case B uses a strip-proxy
in front of the real daemon rather than a fake generator. Generation still
comes from the real model; only the final-chunk usage fields are removed to
enter the production fallback path that this PR fixes.
Exact steps or command run after this patch
Evidence after fix
Case A — real daemon, provider counts authoritative (same HTTP response)
Case B — real daemon + strip-proxy, CJK-aware fallback
Focused harness (production path, loopback NDJSON)
Observed result after fix
Against a real Ollama 0.9.6 daemon (
qwen2.5:0.5b):done.message.usageequals those daemoncounts (
input: 40,output: 17on the recorded Case A request).fallback usage is CJK-aware (
input: 19,output: 60) — about 3.8× theold naive
length/4undercount, and identical toestimateStringChars(...)/4.What was not tested
/contexttreemap UI and end-to-endshouldCompactcompactiontrigger against a long CJK session
eval-count trigger matters)
Fix classification
bugfix — usage accounting / CJK undercount
AI Assistance
AI-assisted. Author reviewed the local CJK mirror (no public SDK export),
real-daemon Case A/B proof, loopback HTTP caller-path proof, and CI
unused-export cleanup.