fix(agent): bill recovery retries separately so the context gauge sees clean usage / 重试尝试单独计费,上下文窗口与压缩判定不再被翻倍 usage 污染
Summary
Problem. Reasonix can intermittently double-report the context window fill, and — worse — auto-compaction can fire at roughly half the real usage. Issue #7620 reports the context window value jumping from ~200K to 700K+ and sessions being compacted unexpectedly. Both symptoms trace back to one root cause: when the silent missing-reasoning recovery (introduced in v1.19.4 via #7259) replays the byte-identical request, mergeStreamUsage summed the two attempts' PromptTokens/CompletionTokens/TotalTokens into a single per-turn usage record. That record was then written into lastUsage, which feeds both:
ContextSnapshot— the status bar / desktop gauge renders the doubled fill;maybeCompact— compaction triggers atPromptTokens >= compact_ratio × window, so a session at ~40% reports 80% and gets compacted (users in #7620 observed the exact "jump → prune ~10k tokens → compact → drop back to ~20%" sequence).
The sum was intentional for billing (both HTTP calls are billed by the provider; the original test asserted 12+13=25), but it was applied to the same per-turn record the window gauge and the compaction decision read.
Fix. Separate the billing view from the window view:
- The discarded attempt's usage is now emitted as its own
Usageevent (emitRecoveryAttemptUsage, with a request-onlyRequestCount=1record when the attempt produced no terminal usage), so session cost and request totals are preserved exactly — consumers (stats recorder, desktop telemetry, run metrics, pricing, cache deltas) accumulate the two events to the same totals as before (12+13=25, 2 requests, cache hit/miss preserved via thecacheTokenDeltafallback path). - The adopted attempt's clean usage is the only thing that reaches
lastUsageandmaybeCompact. Both attempts send the byte-identical prompt, so the adopted attempt's prompt tokens are the real context fill. mergeStreamUsageand its sum-assertion test are deleted; new tests assert per-attempt billing and thatlastUsagestays clean.
Known, unfixed display-layer issue. The same report shows a 3.5× value jump and an "other" breakdown bucket far above the prompt share (screenshot in #7620: used=546.9K with prompt=237.7K). Those numbers cannot come from a single usage record — the "other" bucket is used − known, which is always 0 for one record — so the desktop display is mixing records from different moments or tabs (async context fetch racing usage events, or cross-tab contamination while three sessions run concurrently). This display-layer mechanism is not yet localized and is intentionally out of scope here; it needs runtime logs to pin down. This PR fixes only the confirmed agent-side doubling.
Issues
Refs #7620
This PR fixes the confirmed agent-side root cause of #7620: the recovery-retry usage doubling that doubles the reported context fill and can trigger auto-compaction at half the real usage. The display-layer issue described in #7620 (3.5× jumps, inflated "other" breakdown) is not localized yet and stays open for follow-up — see the Summary above. The issue should remain open until the reporter verifies both symptoms are gone.
Verification
go test ./internal/agent/— full package, including the updated recovery e2e tests and the newTestEmitRecoveryAttemptUsageAccountsBillingOnlygo test ./internal/provider/ ./internal/stats/ ./internal/eventwire/ ./internal/control/ ./internal/cli/go test ./...— one pre-existing environment flake ininternal/boot(TestBuildFoldsProjectMemoryIntoSystemPromptfails identically without this change; tool-trust detection reports nothing in this sandbox)gofmt -l .clean;go vet ./...clean
Documentation-impact: none - internal usage accounting only; no user-visible CLI/desktop/config behavior changes and no docs describe the merged-sum record
Cache impact
Cache-impact: none - no provider-visible request, tool schema, or prompt construction changes; the recovery retry already sent the byte-identical request
Cache-guard: existing e2e tests keep the retry request byte-identical (loop_e2e_test.go asserts reflect.DeepEqual on the provider-visible requests)
System-prompt-review: N/A
Summary
问题。 Reasonix 会偶发地把上下文窗口占用显示为真实值的两倍,更严重的是——自动压缩可能在真实用量只有一半时就触发。Issue #7620 报告上下文窗口数值从约 20 万突变为 70 万+,会话被意外压缩。两个症状同源:v1.19.4 经 #7259 引入的 missing-reasoning 静默恢复会原样重放请求,而 mergeStreamUsage 把两次尝试的 PromptTokens/CompletionTokens/TotalTokens 相加成一条单次 usage 记录,再写入 lastUsage,而后者同时驱动:
ContextSnapshot——状态栏/桌面仪表盘渲染出翻倍的占用;maybeCompact——压缩判定为PromptTokens >= compact_ratio × window,于是真实占用约 40% 的会话上报 80% 并被压缩(#7620 用户观察到的正是"跳高 → 裁剪约 10k → 压缩 → 回落到约 20%"的完整序列)。
求和是计费的刻意设计(两次 HTTP 调用都会被计费,原测试断言 12+13=25),但它被错误地作用在了窗口占用与压缩判定所读取的同一条单次记录上。
修复。 将计费口径与窗口口径分离:
- 被丢弃尝试的 usage 以独立的
Usage事件发出(emitRecoveryAttemptUsage,无终态 usage 时发出RequestCount=1的 request-only 记录),会话费用与请求总数被精确保留——消费端(stats 记录器、桌面遥测、运行指标、定价、缓存增量)把两个事件累加后与原合并值完全等价(12+13=25、2 次请求、缓存命中/未命中经cacheTokenDelta回退路径保留)。 - 被采用尝试的干净 usage 是唯一进入
lastUsage与maybeCompact的值——两次尝试发送的是完全相同的 prompt,被采用尝试的 prompt tokens 就是真实的窗口占用。 - 删除
mergeStreamUsage及其求和断言测试;新增测试断言按尝试计费且lastUsage保持干净。
已知但未修复的显示层问题。 同一报告中还有 3.5× 数值跳变与远高于提示词占比的"其他"分项(#7620 截图:used=546.9K 而 prompt=237.7K)。这些数值不可能来自同一条 usage 记录——"其他"分项是 used − known,对任何单条记录恒为 0——说明桌面端显示在混合不同时刻或不同标签页的记录(异步 context 抓取与 usage 事件竞态,或三个会话并发时的跨标签页污染)。该显示层机制尚未定位,刻意不在本次范围内;需要运行时日志才能锁定。本 PR 只修复已确认的 agent 侧翻倍。
Issues
Refs #7620
本 PR 修复了 #7620 中已确认的 agent 侧根因:恢复重试的 usage 翻倍导致上下文占用显示翻倍、并可能在真实用量一半时触发自动压缩。#7620 中描述的显示层问题(3.5× 跳变、"其他"分项异常)尚未定位,保持打开以跟踪后续修复——详见上文 Summary。请保持 issue 打开,直至报告者确认两个症状都已消失。
Verification
go test ./internal/agent/—— 全量,含更新后的恢复 e2e 测试与新增TestEmitRecoveryAttemptUsageAccountsBillingOnlygo test ./internal/provider/ ./internal/stats/ ./internal/eventwire/ ./internal/control/ ./internal/cli/go test ./...—— 仅一个既有环境 flake(internal/boot的TestBuildFoldsProjectMemoryIntoSystemPrompt,无本改动时同样失败;沙箱中工具信任检测为空)gofmt -l .干净;go vet ./...干净
Documentation-impact: none - 仅内部 usage 记账;无用户可见的 CLI/桌面/配置行为变化,也无文档描述合并求和记录
Cache impact
Cache-impact: none - 无 provider 可见请求、工具 schema 或 prompt 构造变化;恢复重试本就发送字节一致的请求
Cache-guard: 既有 e2e 测试保持重试请求字节一致(loop_e2e_test.go 对 provider 可见请求断言 reflect.DeepEqual)
System-prompt-review: N/A