Repository navigation
tokenUsage projection never folds compaction/summary.usage, and replaces rather than adds across a retried step
#1886
Replies: 31 comments
|
Implemented on a fork: 63688b0
No |
|
Corpus-verified against the commit itself, not the description. Both scopes, bucket-exact. I transcribed
Zero difference, all four buckets, both scopes. Two implementations sharing no code landing on the same number is what makes this checkable rather than a matter of opinion. The One thing worth a second look
event.data.chunk.reason.kind === 'error' || event.data.chunk.reason.kind === 'aborted'An adapter that merges in a third failure kind gets the old behaviour back silently: no boundary, so the retry's sample replaces the failed attempt's instead of adding to it. That is the exact undercount this commit fixes, returning for one adapter and for nobody else, which is the hard kind to notice. Testing One question, not a findingAfter the boundary clears I could not produce one. An errored step assembles no message in my corpus, and the crash-recovery closers carry no usage, so this may be structurally impossible. If it is, it is worth a test name saying so. What my verification does not cover
Happy to run any fixture against the corpus, or to publish the retry sequence as a standalone regression fixture. The probe is stdlib-only and the check is one command: https://github.com/lizhuojunx86/traceguard/blob/main/usage-tracker-audit/dsh-probe/README.md |
Verified fix: account for compaction calls and preserve usage across retriesI validated a concrete fix against the current public source snapshot ( The fix belongs in 1. Add
|
|
Ran the patched projection itself against a real log, rather than a transcription of it. Imported
Same numbers as my independent fold, bucket for bucket, and
That covers the one thing a unit suite cannot: the patch on a real session log rather than a fixture. Agreed on treating the |
|
我把这里的 probe、四条评论、63688b0、#2426 的另一种实现和当前 master 对了一遍,并在一个下游 usage parser 的本地分支里按相同思路做了最小 synthetic projection fixture。它不是可回放 transcript,也没有使用或公开真实 transcript。 目前 fixture 覆盖:
手算 aggregate 是 6 个 usage-bearing calls:input 207、cacheRead 137、cacheWrite 23、output 43、reasoning 20;本地 parser 与独立 verifier 都对上。它也复现了旧逻辑的两个方向:parent 从应计 5 条缩成 3 条,child 把 inherited prefix 再计一次。 下面一并附上完整 synthetic fixture。想确认三个边界:
补充边界:我的 2026-08-14 DeepSeek 官方语料没有 retry,也没有带 usage 的 compaction,所以这里的 patch 不改变那批对账数字;它验证的是通用折叠语义。
|
|
先说复核结果。我把 fixture 独立重折了一遍:parent 5 条、child 1 条、aggregate 6 条,五个 usage 字段共 15 个数字,和 expected.json 全部对上。turn 1 的 output 从 chunk 的 10 变成 message 的 12,正好把"替换"和"取大/相加"区分开,这是我自己语料里没有的样本。cacheWriteTokens 给了非零值也补上了我上面说过的那个空白,我那两条 provider 路线都没有 cache-write 流量。 第二个问题先回,因为你把我说错的地方指出来了。 我在上面说过"同意把 failure 字段当边界谓词作为后续 hardening"。按你这条论证,那句话在当前实现下是错的。agent loop 仍然只 allowlist 顺序上建议分两步。token-meter 和下游先严格跟随 第一个问题,值得补。你找到的那条保证现在靠三处间接支撑:agent.ts 的控制流、core/session/README.md 的一句话、transport-recovery tests 的观察。三处分属不同包,谁都可能在不知情的情况下改坏,改坏之后还不报错,只是数字慢慢不对。token-meter 里放一条名字就说清楚的测试,比注释和 README 都耐用。 第三个问题,一致。failure finish 结算 billed attempt,llm/retry-started 才计 retry,只有 llm/retry 没有 started 的 backoff cancellation 不计。这是两个量:一个是钱,一个是可靠性指标,混在一起两边都不准。#2426 我按这个口径理解。 最后,你说这批 patch 不改 2026-08-14 那组对账数字,我确认,而且那条线已经和这里分开了。FirmaSpring 在 #2554 把方向算清楚了:compaction 样本是 cache-read 重的,补上只会让 DSH 的 hit 列更大,而 DSH hit 本来就比控制台高 708k。#1886 修完是把残差拉宽,不是收窄。所以它是独立的 bug,不再是那边的候选解释。 你的 fixture 建议直接开 PR,关联 #1886。 |
|
把这条线上用的方法写成了一篇公开文章,中英双版。 它把过去五个月在 5 个仓库上做的审计归成五类成因。#1886 这两处占其中两类(compaction 漏计、retry 被替换),另外三类是:fork 子会话物理上包含父前缀(实测虚高 5.18× 和 23.05×)、估算值与测量值合并进同一字段(实测 8.09×)、resume/compact 之后历史静默漂移。每一处都带实测倍数和对应仓库,末尾有一份和日志格式无关的自查清单。 方法论那节写的就是验证 63688b0 时用的四步:手算真值的合成语料、探针先自检再碰真实数据、直接 import 被测方自己的入口点而不是照 README 重写、两个不共享代码的实现落到同一个数。这条线是那四步唯一一次跑完全程的地方,所以文章里它是主要案例。 中文:https://zhuanlan.zhihu.com/p/2073158752958791824 @yha9806 @hydraxman @le-soleil-se-couche 三位在这条线上的工作我在文里都写进去了,只是没逐个点名,因为文章面向的是通用折叠语义而不是 DSH 本身。如果你们觉得哪处表述不准,直接说,我改。 |
|
感谢独立重折。parent 5 条、child 1 条、aggregate 6 条以及 15 个分桶数字全部对上,说明这份 fixture 确实把普通替换、retry、compaction、fork seed 和 cache-write 这些边界分开了。也谢谢你重新核对 merge-extended failure 那条。 我这边按这个口径收口:
关于 #2554,我也同意把两条线彻底分开:补计 cache-read-heavy 的 compaction 会扩大 hit-side 残差,因此不能解释那里的 hit/miss redistribution。 有一个实际限制:当前 master 的 如果值得单独跟踪,我可以另开一个 Discussion,只讨论 AgentLoop 的 |
|
Where this stands, as of August 19. I re-checked master this morning. What changed is that the fix now has three independent verifications:
Scope, so this doesn't get reopened. The failure boundary stays narrow. token-meter closes an attempt on What's blocking. CONTRIBUTING.md still closes external PRs, so Li Zhuojun |
|
Another independent implementation of the compaction half of this thread, confirming the bug is still live on current master ( Our fork carries the fix as a single commit on top of master: https://github.com/a137460387/deepseek-harness/tree/upstream-pr/token-meter-compaction-usage Semantics match 63688b0 on the compaction dimension:
The commit also carries unit coverage for the fold: full accumulation alongside step usage, skip-without-change for usage-less summaries, last-sample replacement intact when a summary lands between turns, and the projection checkpoint recording This deliberately does not address the retry dimension (scope 1 of this thread) — same reasoning as 63688b0: retries need an attempt-boundary rule, which is the structural decision still open here. Happy to send a PR if/when external PRs are accepted. |
|
Status roll-up, since this thread now has four independent implementations and still no maintainer position. Upstream, as of today (Aug 23). master is at 0.1.1-rc.2. packages/llm/token-meter/src/usage-projection.ts is unchanged since 47f9438 (v0.1.0-rc.6): usageOf() still matches only assistant/chunk with a usage chunk and assistant/message, apply() still has no attempt boundary for error/aborted finish chunks, and stateVersion is still 1. All four defects reproduce on current master. What has been built in this thread. yha9806, 63688b0: folds compaction/summary.usage, treats error/aborted finish chunks as attempt boundaries, bumps stateVersion 1 → 2. 23 tests, 100% coverage on the affected file, no llm-retry dependency. Corpus baseline, for anyone who wants a number to hit. dsh-probe folds a four-session corpus four ways (naive, official, seed-aware, correct). Deltas against the official fold: dual-write 536,770, fork-seed 261,562, compaction 48,895, correct total 324,103. I imported 63688b0 directly and refolded the session behind the original report: same numbers, bucket for bucket, and stateVersion reads 2. a137460387's patch is the compaction subset of 63688b0, so the two have to agree exactly on that one bucket. Worth confirming on le-soleil-se-couche's synthetic fixture rather than on anyone's private corpus — that gives whichever implementation gets adopted a shared baseline, and it costs about ten minutes. One thing from next door that raises the stakes. In #2554, Sutera-Diffusus notes that after the Aug 16 price change DeepSeek cache hit and cache miss differ by 30× (¥0.15/M vs ¥4.5/M). Different bug, same blast radius: a misfiled token now costs thirty times a double-counted one, and the compaction tokens missing here are not priced at all. CONTRIBUTING.md still blocks external PRs, so none of this can be sent as a patch. A one-line maintainer answer would unblock four people: take one of these, or say the approach is wrong and why. |
|
Agreed - the shared fixture is the right baseline, and private corpora should stay out of it. Ran it against the compaction-only patch ( Method. The fixture is a minimal projection input (message payloads deliberately omitted), so it cannot pass through Numbers (input / output / cacheRead / cacheWrite):
Other behaviors, recorded as-is: turn1 replaces (100/10/20/3 -> 100/12/20/3), not max or add; turn3's Two disclosures: the fixture contains no usage-less Environment: Node v24.14.1, direct fold of the branch's |
|
@a137460387 — your numbers hold, and they are on a different fixture from mine, which is worth stating clearly before either set gets quoted. There are now two synthetic fixtures in play. Yours is @le-soleil-se-couche's, posted in this thread: aggregate 207 / 43 / 137 / 23 plus a reasoning column, turn1–turn3, seq14 compaction. Mine is a separate construction committed at Same three conclusions off both:
Two substrates, no shared code, same structural answer: the patch adds the compaction term and nothing else. That is a better result than either of us running the other's file. On the case you flagged as uncovered. You noted your fixture has no usage-less I have been wrong about
|
| fold | input | output | cacheRead | cacheWrite | total | stateVersion |
|---|---|---|---|---|---|---|
b150a551b8 unpatched |
850 | 85 | 8,500 | 25 | 9,460 | 1 |
64ee978 |
1,250 | 125 | 12,500 | 25 | 13,900 | 2 |
63688b0 |
1,650 | 165 | 16,500 | 25 | 18,340 | 2 |
The ablation is the comparison worth having. Removing the error/aborted finish branch from 63688b0 and leaving everything else gives 1,250 / 125 / 12,500 / 25 — identical to 64ee978 on every bucket, per session as well as in total. The two agree exactly on compaction and differ by exactly the retry term. Same statement your 7 / 2 / 5 / 1 makes from the other side.
Worth recording separately: unpatched b150a551b8 lands on my fixture's official fold bucket for bucket. That fold was hand-computed and then reproduced by reference.py; this is the first time it has been checked against the vendor's compiled code instead of a reading of it. It holds.
What this does not cover
The compaction dimension only. Two synthetic fixtures and two probes, no corpus, so none of it says how often the path runs — only what it computes when it does.
One gap I have been carrying since the opening post is now closed, and it is your run that closes it. I have said in every version of this that a summary reporting cache writes is untested — neither route in my corpus ever populated cacheWriteTokens, and every compaction/summary in my own fixture reports 0 on that bucket. Your compaction increment is +31 / +9 / +37 / +6. The +6 is a summary carrying cache-write traffic, folded correctly, for the first time anywhere in this thread. The bucket is still unobserved in the wild — a synthetic fixture cannot fix that — but it is no longer untested by construction, and I will stop writing that it is.
The API-drift finding is read from the interface on master against the branch's call shape. I did not run tsc, so "does not apply" is an inference from three specific mismatches rather than a compiler transcript.
D-2 and D-4 are untouched by this patch and unchanged upstream. Pointing dsh-conformance/check.py at 64ee978 still fails, correctly, with a residual of 200 / 20 / 2,000 / 12 — gap_inherited minus gap_superseded, the two open items and nothing else. Your 141/22/63/10-minus-owned decomposition is the same fork-seed term measured on your file.
Harness: dsh-1886-crosscheck/. Clones the three trees at their SHAs, builds the four folds, runs the ablation and the two probes. The ablation locates the branch to strip by verbatim string match and aborts if it is not found, so a refactor upstream fails the run rather than quietly comparing something else. Both probes are in there; take them for your spec if they are useful.
Status
Master b150a551b8, 0.1.1-rc.2, stateVersion 1, all four defects reproduce. CONTRIBUTING.md line 9 still reads "we cannot accept external pull requests at the moment", which I have now read off the file rather than quoting it from this thread.
Five independent measurements now, across two fixtures and four implementations, converging on the same answer, with the retry dimension left out of all of them because nobody has ruled on the attempt-boundary. A one-line answer — take it, or say it is not wanted — costs less than the sixth, which will be written against an API that has moved again.
Li Zhuojun
|
The checker for this already exists and I don't think I ever pointed at it directly in this thread, which is my fault. So, plainly:
The fixture root arrives as the final argv, and as When it fails it doesn't just say failed. It decomposes the residual against @yha9806 @hydraxman @le-soleil-se-couche @a137460387 — between us we wrote four folds and cross-checked them by hand across two fixtures and a dozen comments. That was worth doing, and it leaves nothing behind that a fifth person can run. If each of you runs the line above against your own fold and pastes the output here, four parallel implementations turn into four conformance records, and whoever shows up next starts from a check instead of from this thread. Two limits worth stating. D-4 is decomposed and reported but never graded, because nobody has ruled on where an attempt boundary sits and I'm not going to invent one and call it a standard. And nobody outside me has run this checker yet, so treat it as unexercised. If the contract is awkward in practice I'd rather find out from the four of you than from a stranger. Upstream unchanged as of today: master https://github.com/lizhuojunx86/token-accounting-conformance/tree/main/dsh-conformance |
|
@a137460387 — your fold script is already what the checker wants, so this is one flag rather than any work. git clone https://github.com/lizhuojunx86/token-accounting-conformance
cd token-accounting-conformance/dsh-conformance
python3 check.py --self-test
python3 check.py --cmd "<your fold>"Your command gets the fixture's sessions root as its last argv, and the same path in This is not a test of your patch, and I should say so before you run it: I already pointed it at 64ee978 myself. It fails, correctly, with a residual of 200 / 20 / 2,000 / 12 — You would be running it to check the checker. That is the part I need. Nobody outside me has run this thing. Every harness in it was written after I had already measured the defect by hand, so I have no evidence that the contract works for someone who did not write it. You are the only person in this thread who has published a bucket-by-bucket method with the environment pinned, so if the contract is awkward you are the one who will say where. One thing it does that our hand cross-check could not. Your 7 / 2 / 5 / 1 is the superseded-attempt term, and you had to read the trace to know that. My fixture carries the same hazard with the failed attempt reporting real tokens (2,220 of them, against a real corpus where every failed attempt reported zeros), and the checker names D-4 instead of printing four numbers that differ. "Compaction only, retry deliberately out of scope" stops being a sentence in a comment and becomes a line of output. Two things in that README were wrong until an hour ago, and both were in the path this comment points you down: the quick-start still cloned If wiring up a command is more trouble than it is worth, the fold script you offered would let me run it instead. I would rather the record were yours. Li Zhuojun |
|
Ran it against my current local
Self-test: Against the local fold: The local suite also passes: 7 test files / 47 tests, plus The command contract was straightforward. One small integration detail: the committed fixture directory names are This is a conformance record for the local fold semantics, not a claim that the temporary adapter is a shipped CLI, and it does not settle the upstream ownership decision for the attempt boundary. |
|
@le-soleil-se-couche — first run of this checker by anyone but me, and it found a bug in the fixture on the first try. That is the whole reason I asked. You are right about the mismatch, and I fixed it the other way round. Real DSH cannot produce it: the transcript lives at Fixed in e211154. The header ids are now Why the suite never caught this itself: Your scoping is right and I will not argue you up from it. What the record settles is D-1 through D-4 against a fold I did not write, on a substrate neither of us can tune after the fact. That was the missing piece. Li Zhuojun |
|
Ran it, per the invitation. Fresh clone at d1c44e5; self-test green on all seven folds plus the D-5 identity. Our command folds every Reading the result against the patch's declared scope (
One wiring note from the outside run: the fold command needs to execute with its cwd inside the branch checkout so the TS loader resolves workspace paths; from an unrelated cwd it falls back to unbuilt Environment: Node v24.16.0, Windows (Git Bash), stdlib Python 3.10. The branch remains one commit on rc.2, compaction dimension only. Thanks for building this and for the invitation — a named residual is a better artifact than four hand-compared tables. |
|
Confirmed from my side, and the part I needed was not your patch. Your residual reads exactly right. What I was testing was the contract, not the patch. Nobody outside me had run this, so I had no evidence it worked for anyone who hadn't written it. It did, in one flag, on a setup I have never used: Windows Git Bash, Node v24.16.0. That is worth more to me than the pass/fail line. On the cwd note, I'd call that mine rather than your driver's. Upstream is unchanged as of today: master D-4 stays decomposed and ungraded until somebody rules on where an attempt boundary sits. If that gets settled and you want the retry dimension graded as well, say so and I'll add it rather than invent the rule myself. |
|
I reproduced the token accounting bugs on current master (
The standalone Web fixture folds the same log a second time. It still replaced on I put a regression-tested fix on a fork branch. Branch: https://github.com/vpimshin/deepseek-harness/tree/fix/token-usage-compaction-and-retry
Tests I ran on that branch:
|
|
Upstream landed the retry half about three and a half hours after you posted. Your reproduction checks out from here. At The part worth flagging is that both of you bumped Which leaves the half that is actually still missing. That last one is new to me. My catalog has the successful summarize call and nothing about a failed summarizer dropping usage on If you want the decomposition run against your branch, |
|
@vpimshin — I ran your branch, and it passes. But the more useful half of this reply is that your baseline is stale, and so was mine until this morning. The retry half was already fixed upstream, two days before your post
if (event.type === 'llm/retry-started') {
return state.last?.turn === event.data.turn && state.last.step === event.data.step
? { ...state, last: null }
: state
}Released in Neither of us saw it because we both measured Upstream keyed the boundary on Your branch, foldedNot a transcription. I pulled
Two probes the fixture cannot carry, both of which you handle:
Those are per-bucket figures on the seed-aware scope, where the caller has already handled D-2. On the whole-log scope current master and a137460387's fold both read 1,250 / 125 / 12,500 / 25, which is arithmetic coincidence on this fixture, not agreement: My fixture had a bug that would have failed you unfairlyThe Nothing read those events, so it stayed invisible — until upstream keyed the boundary on exactly them. Against the old fixture, current master scored 850 / 85 / 8,500 / 25, byte for byte the unpatched rc.2 result. The checker would have reported an implementation that does fix D-4 as fixing none of it. Fixed in What your branch does that the other four don't
I can't corroborate that half. My corpus has no failed summarizer — all three I also didn't run your 480 tests or the Web fixture mirror; I read that diff but did not execute it. Worth noting the mirror is still unfixed upstream — Two things for whenever this rebases
The two boundaries only diverge on a log where an error finish is followed by another usage sample under the same One question, not a finding. In Harness, if you want to reproduce any of the above: https://github.com/lizhuojunx86/token-accounting-conformance/tree/main/dsh-1886-crosscheck Li Zhuojun |
|
Thanks for the pointer. One version correction, since the doc pins to rc.2 throughout. The retry half is no longer a gap. The compaction half is still open at One thing to watch if you key advice on checkpoint versions: The cheap check is |
|
Format v2 rewrote the file every patch in this thread touches, so this is a heads-up for the five implementations plus a re-measurement.
For @yha9806, @a137460387 and @vpimshin. The compaction fold itself carries over unchanged, since D-3 is still open, which is the part I re-checked before writing any of this. At What the format change did to the measurements. I converted the four sessions from the original report with upstream's own
The migration collapsed 8,350 The dual write moved inside the event. It used to be two events. Now One correction to my own advice. I have been telling people the only sound fork discriminator is The two forks migrate to cuts of 47 of 65 events and 83 of 104, and report the same inflation as before: 11,418 tokens against 2,204 of own work, and 263,790 against 11,442. Still 5.18× and 23.05×. Only the field you check changed. One thing to know before recomputing anything across versions. The frozen released-v0 reader in the current tree refuses logs written by
Probe, migration harness and the updated catalog are at If your corpus contradicts any of this I want the numbers, same as before. A v2 settlement whose |
|
Thanks, Li Zhuojun, for the v2-format warning and the precise note about the inherited cut. I have now implemented the corresponding accounting path in |
|
Thanks for the fix. I cloned dsh-token-cost at 35c06cf and ran the three test files on Node 22 / vitest 4.1.10: 32/32 pass, and the parser does what your comment says. One correction for anyone following the link: 35c06cf is As noted above, the retry half has been closed on master since b565df3 (dsh-v0.1.2-alpha.1 onward). I re-checked master at c291e79 (Sep 10) and dsh-v0.1.5-rc.2: One warning on the plugin. 0.1.5 writes session format v3 natively: I'll narrow the original post to the compaction item and re-run my corpus against 0.1.5-rc.2. I haven't done that yet, so the 48,895 figure above is still the 0.1.1-rc.2 number. |
|
Thanks for independently running the tests and for correcting the commit attribution. My previous I checked the v3 codec, migration, payload and inheritance rules at On Node 22.22.1 / vitest 4.1.10, the three focused files pass 39/39 and the full suite passes 82/82; typecheck and build also pass. The new synthetic accounting fixture covers system-message replacements, repeated inherited markers, a retry, duplicate settlement usage and independent compaction. Its hand-computed result is 3 records: input 43, output 16, cache-read 56, cache-write 9, reasoning 12. Tests also cover raw/zstd v3 selection over retained v0–v2 files, cached restart, and refusing a future v4 without falling back. These are downstream accounting tests with a minimal synthetic fixture, not full native Session validation or a complete |
|
Re-checked D-3 against At that tag, I restored the four sessions from the original report v0 → v4 through the shipped catalog and folded them with the shipped One note for anyone re-running on 0.2.x: the bare If the fix is in scope for 0.2.2, I'd expect it to follow the retry fix: a |
|
D-3 is still live on current master, and a tested one-commit fix is available for cherry-picking. Re-verified at master The fix — per CONTRIBUTING I am not opening a pull request; the branch exists so the change can be cherry-picked, and I will gladly open a PR if you prefer that instead: https://github.com/changjun-zheng/deepseek-harness/tree/fix/token-usage-compaction-usage (commit
Verification (local: Windows, Node 24.15.0, pnpm 11.28.5):
Prepared with an AI coding agent; the runs above are all local. |
|
@changjun-zheng I ran your commit against today's master, and it does what you say.
I built both files with esbuild against real zod 4, replaced the workspace imports with small stubs (
The mid-step row matters most to me. The settlement still replaces the attempt and the summary adds on top, because you pass One gap is out of scope for this patch. What I didn't do: run your vitest suite, a host build, or a re-fold of my four-session corpus. That corpus isn't on this machine any more, so 48,895 is still the Nov 14 measurement at rc.3. Zhuojun Li |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Update, September 12. This discussion is now about one item:
compaction/summary.usageis not folded (D-3). Item 2 below, the retry replacement, has been fixed on master since b565df3 (Aug 25, shipped in dsh-v0.1.2-alpha.1); see the Aug 28 comment for the commit and the merge-base check.Re-measured at dsh-v0.1.5-rc.2 (a305303, Sep 10) with the shipped code rather than a transcription. The four v0 sessions were restored through
sessionFormatCatalog.createRestore(@deepseek-ai/dsh-session-format-catalog,validation: 'transformed', the same callsession-persistence-jsonlmakes), which runs v0 → v1 → v2 → v3, and the restored events were folded withtokenUsageProjectionDefinition.applyimported frompackages/llm/token-meter/src/usage-projection.ts. The emitted v3 files re-read undervalidation: 'current'.The 8 extra events are two
system/messageper session, the V3 system head. Nothing else moved.usageOf()at 0.1.5-rc.2 still matchesassistant/messageandassistant/attemptand nothing else;compaction/summaryis read only bysurface-projection.ts, for the shadow price.Two corrections to my Sep 5 comment. First, a current DSH does read logs written by 0.1.0-rc.6: since 46196d6 (Sep 6, in dsh-v0.1.3-alpha.2 and later) the v0 stage skips payload validation for
assistant/chunk, so thereplayStateshape that used to be refused passes, and the strip step is no longer needed. Second, the corpus does contain one real retry (session e7c289bf, turn 4 step 1:assistant/attemptending inTRANSPORT, thenllm/retry,llm/retry-started). The shipped projection handles it. That attempt reported 0/0, so there is still no measured magnitude for D-4.For @le-soleil-se-couche: dsh-token-cost at 35c06cf throws
unsupported session format version v3on all four emitted logs. Widening the version gate to 3 (six lines inparser.ts, no other change) returns 324,103, per session 11,439 / 252,348 / 4,430 / 55,886, with one compaction record where a compaction happened. On this corpus the v2 accounting grammar carries over to v3 unchanged.The restore-and-fold script, the per-session JSON and the six-line patch are in token-accounting-conformance under
dsh-probe/v3-migration/(2b8acda).Two gaps in
token-meter'stokenUsageprojection, found while measuring session logs from a probe corpus. Both are in the projection itself, so plugins that do the recommended thing (readctx.sessionProjections.tokenUsageinstead of folding the log themselves) inherit them.Measured on 4 sessions, 8,650 events, 78 usage samples, two providers (MiniMax-M3 over
minimax-cn, andqwen2.5:14bover a local OpenAI-completions endpoint).1. Compaction cost is never counted
compaction/summary.usagecarries the provider-reported cost of the summarize call. It is typed inpackages/compaction/compaction/src/types.ts("Provider-reported token usage for the summarization request, when emitted") and written atpackages/compaction/compaction-basic/src/region.ts:447.usageOf()inpackages/llm/token-meter/src/usage-projection.tsmatches onlyassistant/chunk(usage) andassistant/message. The summarize call is not a loop step, so it produces neither. The event is never folded.Measured: 3 compaction events, 48,895 tokens, none counted. The largest was a single MiniMax-M3 summarize call reporting 536 input / 2,436 output / 41,472 cache-read = 44,444 tokens, against a
shadowedTokenCountof 19,962 for the range it replaced.Whether that trade is worth it depends on cache pricing, and I have no opinion on it. The issue is that a user reading any usage surface built on this projection cannot see that the call happened at all — and compaction fires more often precisely on the long sessions where budgets matter.
Suggested fix: extend
usageOf()to matchcompaction/summaryand returnevent.data.usage. The(turn, step)replacement logic does not apply (a summary is not a loop step), so it wants a plain add.usage?is optional, so an absent value stays absent rather than becoming zero.2. A retried step's earlier attempt is replaced, not added
apply()replaces on a repeated(turn, step)viaaddReplacing(lines 126-136). That is correct for the two-sample case D-1 documents: a usage chunk followed by the assembled message reporting the same numbers.It is not correct across a retry. Observed sequence in one session:
Three usage samples under one
(turn, step), and one more retry would make four. The two attempts are separate costs, not duplicate reports of one cost, but they share a key andapply()has no way to tell them apart —llm/retryis not in its match list.The failed attempt reported zeros here, so nothing was actually lost in this corpus and I am claiming no number for the undercount. The mechanism is what I am reporting. A provider that reports real usage before a transport failure would have that cost silently dropped.
The token-meter README says "Usage chunks are counted even when a request later fails", which holds when the failed step produces no message. It stops holding when a retry succeeds under the same key.
Two things this also affects: the group-size assumption (a
(turn, step)can carry k>2 samples) and keep-first implementations, which report such a step as costing zero — 10,368 cache reads in the case above.llm/retry/llm/retry-startedcarry aretryIdand sit between attempts, so the discriminator already exists in the log.What is already right
Worth stating, because it is why these two stood out. Append-only with dense contiguous
seqremoves the whole class of drift that comes from in-place transcript rewriting. Terminal-only usage (types.ts:291: "Adapters emit usage before the terminal finish and nothing afterward") removes partial-snapshot summing. Sibling child sessions withparentSession+seedLength, and telemetry that says to stitch on that pair, is the right shape.addReplacingfor the ordinary two-sample case is correct, and its existence is what told me the double-write hazard was real rather than theoretical.Reproducing
Stdlib-only Python, no dependencies, no vendor account:
It folds a corpus four ways (naive, a line-for-line transcription of
tokenUsageProjectionDefinition, seed-aware, and corrected) and prints the deltas plus the(turn, step)group-size distribution.--self-testasserts every fold against constructed ground truth before it touches real data.Corpus written with
compression: 'none'andpackChunks: falseso the log is line-readable.Probe, protocol, and the full invariant catalog: https://github.com/lizhuojunx86/traceguard/blob/main/usage-tracker-audit/dsh-probe/README.md
I understand external PRs aren't being accepted right now. Happy to supply a regression fixture in whatever form is useful, or just leave the measurements here.
中文摘要
两处都在
token-meter的tokenUsage投影里,所以按推荐做法读sessionProjections.tokenUsage的插件全都会继承。一、
compaction/summary.usage从不被折叠。usageOf()只匹配assistant/chunk和assistant/message,而摘要调用不是 loop step。实测 3 次 compaction、48,895 token 全部未计入,其中一次 MiniMax-M3 摘要调用报了 44,444 token(含 41,472 cacheRead),换掉的历史shadowedTokenCount是 19,962。建议usageOf()增加compaction/summary分支,按相加而非(turn, step)替换处理。二、同一
(turn, step)下的重试尝试被替换而非相加。流传输失败后 harness 在同一 key 下重试,两次尝试是两笔独立成本,但apply()看不到llm/retry,无从区分。本语料中失败尝试报的是全零,所以我没有漏计的数字,报告的是机制本身。附带两个影响:一个 step 的样本数可以大于 2;keep-first 实现会把这一步报成零成本(上例中丢掉 10,368 个 cacheRead)。复现脚本纯标准库、无依赖、无需任何厂商账号,
--self-test会先用手算真值校验四种折叠再碰真实数据。All reactions