Skip to content

fix(usage): 按原始日期和模型记录会话补账 - #3571

Merged
deepcoldy merged 3 commits into
deepcoldy:masterfrom
Disaster-Terminator:fix/usage-recovery-attribution
Nov 19, 2026
Merged

deepcoldy merged 3 commits into
deepcoldy:masterfrom
Disaster-Terminator:fix/usage-recovery-attribution

Conversation

@Disaster-Terminator

@Disaster-Terminator Disaster-Terminator commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

会话恢复时,BotMux 用两次读取的累计 token 算差值,可能把多日、多个模型的用量合成一条。比如周一用模型 A,周二切到模型 B,周三重启后才补账,两天的用量可能都记到周三,模型也可能归错。

  • Codex 格式的会话按原生日志的时间、模型和 token 增量补账。跨日志分段时校验会话归属,确认补账区间后才写入。
  • 将最后一条已记账的原生用量记录标记写入账本。重启后从该位置继续,区分累计计数重置前后相同的值。
  • 月预算按账本记录去重恢复。上月用量归上月,写账后、更新预算前中断时可从账本恢复。
    验证覆盖跨日切模型、跨分段续接、计数重置、写账后中断和同名外部会话日志。构建、Workflow Core 冒烟、Vitest 回归和 Bun 全量通过。

补账恢复边界修复

  • 续接分段按原生 checkpoint 跨 reset epoch 去重,避免旧前缀被误判为时间回退。
  • 分段候选以索引选定的活跃 generation 为右边界,保留其历史祖先,排除更新的非活跃分段。
  • 退役分段的半行尾不再否决完整恢复链;活跃文件中尚未 durable 的 preview 仍保持 pending。
  • 单次 recovery 的所有分段共用 64 MiB 扫描预算,超限 fail-closed。
  • reset 时先推进内存基线再持久化,并追加零增量 kind="reset" 账本控制行;写 state 失败后即使立即重启,也能按 totals/epoch/checkpoint 重建。控制行不进入用量分析或预算。
  • 无模型元数据时按 model="" 记录 token,不猜价,不再丢弃整个有效区间。

补充验证

  • bun run typecheck、bun run build 通过。
  • 相关 Vitest:19 文件、343 用例通过;测试卫生检查 28 用例通过。
  • Bun 腿:budget-tracker + usage-ledger 共 85 用例通过。
  • 原六项及 reset 持久化/分析过滤的守卫移除变异均按预期咬红;源码随后恢复并复跑通过。
  • 独立对抗复核曾复现“reset 的 state 写入失败后立即重启仍少记”的窗口,已改为上述持久控制行修复。定点复验中,reset 到 20 后连续增长到 40/60/80 均各记 20 且 epoch=1;重复 reset 行 recordId 相同,分析仅统计唯一正 delta,预算重建金额与正 delta 成本总和一致。多代际重放、暖游标追加、无换行 preview、反复半写入等攻击场景未再复现问题。
  • 另在追加 reset 控制行前尝试全量 unit:55,281 通过、128 失败、111 跳过;失败输出包含长路径 tmux socket、bwrap 与路径别名等本机环境形态,故不记为全绿。最终提交以本节的定向、构建、变异和独立探针结果为准。

🤖 Generated with Claude Code

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-18T14:35:43.996379Z babbfca Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: babbfcaa26

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1628 to +1629
if (ms !== null && priorSegmentEnd !== null && ms <= priorSegmentEnd
&& fields.every(k => usage[k] <= last[k])) return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Deduplicate replayed prefixes across counter resets

When a resumed generation replays history spanning a counter reset, old snapshots can exceed the post-reset last, so they fail this duplicate test and are subsequently rejected as timestamp regressions. A fenced, fixed-clock probe using the real reader and ledger with an accounted 100, old history 100 → 150 → 20 → 40, and a continuation replaying that history before 120 records no new usage on reconciliation or subsequent retries. Removing only the retired generation recovers the missing deltas. Deduplicate replayed native checkpoints across epochs rather than comparing historical snapshots only with the latest totals.

AGENTS.md reference: AGENTS.md:L172-L172

Useful? React with 👍 / 👎.

Comment thread src/services/transcript-resolver.ts Outdated
}
};
try { walk(root, 0); } catch { return [current.path]; }
return [...found].sort();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Respect the indexed active generation during recovery

When SQLite's threads.rollout_path selects an older-named active Codex generation, this sorted list also appends later-named inactive generations, although findCodexRolloutBySessionId deliberately treats the index as authoritative (src/services/codex-transcript.ts:1154-1155). In a fenced, fixed-clock probe of the real resolver and ledger, an accounted 100 and active 150 were followed by an inactive 200; recovery consumed that file, failed its final comparison with the active snapshot, and omitted the valid 50 delta. Prefer proving the interval in the selected current path and include only necessary predecessor segments instead of unconditionally replaying every filename match.

AGENTS.md reference: AGENTS.md:L172-L172

Useful? React with 👍 / 👎.

Comment thread src/core/cost-calculator.ts Outdated
last = usage;
previousAt = ms;
} });
if (!scan || scan.pendingTail.trim() || invalid) return null;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Skip incomplete retired tails before locating the baseline

If a retired generation ends with a partial line, this check rejects it even while anchored is false, before reaching the healthy generation containing the persisted checkpoint. A fenced, fixed-clock probe using the real reader and ledger with retired usage 50 plus a partial tail, a current baseline of 100, and new current usage of 150 leaves the ledger at 100; removing only the retired file immediately records the expected 50. Since the retired file no longer grows, retries cannot repair this condition. Scope completeness validation to the recovered interval rather than allowing incomplete history before the baseline to disable accounting.

AGENTS.md reference: AGENTS.md:L172-L172

Useful? React with 👍 / 👎.

@deepcoldy

Copy link
Copy Markdown
Owner

你好,这个 PR 的自动评审群已建,麻烦点击链接加入群聊、查看评审意见并跟进后续修改:
https://applink.larkoffice.com/client/chat/chatter/add_by_link?link_token=d7bo8a00-5fb2-45a7-99af-549d97d7036b

另外你暂时不在自动拉群名单里,也可以把 GitHub 账号和飞书信息补进名单文档,补好后后续评审会自动拉你进群:https://bytedance.larkoffice.com/wiki/WJ1nwWbtxi89erkNGNbcgkt9nUe

(本条为自动流程发出的提示消息)

@deepcoldy deepcoldy left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

复审结论:暂不可合

三个账务 P2 均用真实 resolver / reader / ledger 独立复现,定级维持;它们都是特定文件形态下反复返回 null、基线不前进的持久少计,不是下一轮会自然恢复的瞬时失败。另同意将 recovery 的无上限同步扫描列为性能 P2。

P2-1|跨 reset 的分段前缀重放

src/core/cost-calculator.ts:1628-1637 的问题确认。独立探针中,已入账 100,历史为 100 → 150 → 20 → 40,续接分段重放该历史后增长到 120;getSessionUsageRecovery 返回 null,连续两次 reconcile 均不记账,基线保持 100。

定级 P2 合适。 触发需要续接重放与计数重置叠加,但命中后不会自愈,且直接丢失真实用量。

**修法方向:**应按 nativeCheckpoint 的事件身份识别跨 epoch 重放,而不是只拿历史累计值与最新 last 比较。一种符合现有数据结构的方案是:在一次 recovery 内记录已经扫描过的原生 checkpoint(包括锚点之前的历史),续接分段中先跳过已见 checkpoint,再对真正未见的事件执行时间单调、reset 与末值校验。也可以做严格的段间 checkpoint 接续,但若接续点不存在必须 fail closed。不要仅靠放宽时间戳回退、或扩大 usage <= last 的数值豁免,那会混淆旧 epoch 重放与真正 reset。

回归用例应覆盖上述完整序列,并验证各 epoch 的增量、原始日期/模型及重跑不重复;摘掉跨 epoch 去重后必须咬红。

P2-2|分段扫描越过 SQLite 选定的活跃 generation

src/services/transcript-resolver.ts:77-92 的问题确认。独立探针让 threads.rollout_path 指向较旧文件名的活跃分段(100→150),同时放置较新文件名的非活跃分段(累计到 200);walker 实际返回两段,recovery 消耗非活跃末值后与活跃 current=150 不一致,真实 50 增量连续两次均未入账。

定级 P2 合适。 单文件解析器已经把索引当作活跃路径的权威来源,恢复扫描不能使用另一套“所有同名文件都算活跃历史”的口径。

**修法方向:**候选链必须以 resolveSessionTranscriptPath 选中的 current path 为右边界,至少排除排序位于 current 之后的分段;current 之前只保留恢复基线所需、且能与后续 checkpoint 链衔接的祖先,无法证明时继续 pending。不能按最高累计值或最新 mtime 改选 active。

同时,不建议把“只读 current 文件能恢复成功就直接接受”作为通用修复:若 current 只有基线和终点,而旧分段含有中间日期/模型点,这会把增量重新合并到终点,损害本 PR 的归因目标。只有不存在更早历史、或已证明 current 含完整重放时,才适合这种快路径。Codex 与 TraeX 共用此处,应分别补活跃索引早于非活跃文件的回归用例。

P2-3|退役分段的半行尾否决健康恢复链

src/core/cost-calculator.ts:1649 的问题确认。独立探针在退役分段放置完整历史记录及半行尾,在后续活跃分段放置已入账锚点 100 和新增 150;recovery 返回 null,连续两次 reconcile 均停在 100。

定级 P2 合适。 退役文件不再增长,半行尾永久存在,因而重试无法修复。

修法方向:pendingTail 不应作为跨越所有分段的独立全局否决条件。恢复只能提交到最后一个换行终止、durable 且与 current.nativeCheckpoint 严格对齐的 checkpoint;退役尾部不能再否决后续已证明的区间。活跃文件若尾部 preview 含有尚未 durable 的新用量,仍应保持 pending,不能为修此问题而提前入账。

测试至少覆盖两种形态:锚点位于后续健康文件(半行尾退役文件整体处于锚点之前),以及锚点本身就位于半行尾退役文件之内;另补活跃文件半行含新用量时不得提前记账的反向用例。仅把条件改成 pendingTail && anchored 会漏掉第二种形态。

性能 P2|recovery 冷扫描没有工作量上限

src/core/cost-calculator.ts:1611 从 offset 0 同步扫描所有候选分段,确实绕过了主读取路径的 64 MiB 护栏。daemon 重启集中 reconcile 时会放大为事件循环阻塞,P2 合理。

短期至少应有单次调用的字节/条目预算,超限 fail-closed;但要承认固定 64 MiB 上限会让超大会话长期 pending。更完整的方向是把原生定位信息(文件身份 + offset + 行哈希)持久化,或做可恢复的分片扫描,避免每次冷启动都从 0 找锚点。

实际验证

  • 三组临时真实组件探针均复现 recovery=null,且连续两次 reconcile 基线不变;探针用后已删除,未修改 PR 代码。
  • fenced 定向回归:usage-recovery.integration、transcript-resolver-config-profile、cost-calculator、budget-tracker、usage-ledger 共 5 文件、152 用例全绿。这也说明上述三个边缘形态目前均不在有效回归覆盖内。

@deepcoldy deepcoldy left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

补充复审:另有 2 个已复现 P2

P2|reset 落盘失败后,内存基线停留在 reset 前

src/services/usage-ledger.ts:391-399 将 reset 分支的 sessionBaselineMemory.set 移到了 saveState 之后;PR 之前顺序相反,且正 delta 分支仍明确保证“append 后即使 saveState 失败也先推进内存”。

独立故障注入探针:非 Codex 会话先记录 100,随后在 100→20 的 reset 中让 saveState 仅失败一次;磁盘恢复后读取 40,仍与内存中的旧基线 100 比较而再次被视为 shrink,20→40 的 20 token 没有入账,ledger 仍只有最初那条 100。继续增长时也只能从后来被误重置的基线起算。

这是写状态异常与 reset 交叠时的持久少计回归,定级 P2。建议恢复 reset 分支原有的“先推进内存、再尝试持久化”顺序,并补一次性写失败后的行为回归;该问题影响非 Codex 路径,不限于新 recovery。

P2|没有模型元数据的有效 rollout 全部停账

src/core/cost-calculator.ts:1635 把 !usage.model 与时间戳无效、时间回退一起作为整个 recovery 失败条件。

独立真实组件探针使用只有 session_meta 和带有效时间戳的累计 token_count、但没有任何模型字段的 Codex rollout:主读取器正常返回 inputTokens=100/150, model="",已入账基线为 100;增长到 150 后 recovery 返回 null,连续两次 reconcile 均不记账。

旧路径可以记录 token 增量并写 model:"",定价不可知时省略 costCny;新路径却把 token 也永久丢弃,定级 P2。建议将“模型未知”与“区间无法证明”分开:时间戳与 checkpoint 链有效时可按 unknown model 记 token、不猜价,不能为了修此问题放宽时间单调要求。应补无模型旧 rollout、以及后续仍无模型时持续增长的回归。

以上两组均为临时探针实际执行结果,探针用后已删除,工作树未修改。

按原生检查点跨重置去重,限定活跃分段与扫描预算,处理退役半行和无模型记录,并保持重置后的内存基线。

Co-Authored-By: Claude Code <[email protected]>
@deepcoldy

Copy link
Copy Markdown
Owner

已在作者分支 fast-forward 推送修复提交 29e6fa65b(原 head babbfcaa 的直接子提交),未强推。

本次覆盖:

  • 原生 checkpoint 跨 reset 重放去重;
  • 以索引 active generation 为分段右边界;
  • 退役半行尾与活跃 preview 的 durable 边界;
  • recovery 合计 64 MiB 扫描预算;
  • reset 内存顺序及可重启重建的零增量 kind="reset" 控制行;
  • 无模型 rollout 按 unknown model 记 token、不猜价。

验证:typecheck、build 通过;相关 Vitest 19 文件 343 用例、Bun 85 用例、测试卫生 28 用例通过;原六项及 reset 持久化/分析过滤变异均咬红。独立对抗复核发现的 reset 落盘失败后立即重启窗口已修复,定点复验通过,指定范围内未发现新问题。详细探针证据及全量 unit 的本机环境失败说明已追加到 PR 描述。

@deepcoldy deepcoldy left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tree-hash 简化复审:通过

本次仅核 hash 与文件清单,未重复展开功能审查或重跑测试。

  • API 核验 PR head 为 de359c2a5e76d40037c0ab49dcc523b587edec19,mergeable=MERGEABLE。
  • 该 merge 的双亲依次为 29e6fa65bddd58fbecdccaeb3e8b3178da8815d2 与 3565b8f1ad27ed480f323e3616af51cba5dfc9c1。
  • de359c2a5e^{tree} 为 c8c53b29fab634e4e803482ad152002f5e9ca8fa,与此前完成验证的树哈希逐字一致。
  • git diff --name-status 678251d3e..3565b8f1a 仅有 M test/dispatch-user-route.test.ts;该范围只有提交 3565b8f1ad(#3590 的夹具补桩)。
  • 对照 PR 全量 14 个文件,master 侧这一净新增文件与 PR 文件交集为空。

结论:满足约定的 tree-hash 豁免条件,可沿用此前 6 个 P2 已关闭、功能复核可合的结论。无新增阻断项,后续只以新 head 的 CI 首跑结果作为合并门禁。

@deepcoldy deepcoldy left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

G7 合并树复核:可合

  • API 核验 PR head 保持 de359c2a5e76d40037c0ab49dcc523b587edec19;其 15 个 check-run 全部 completed/success,非 success 列表为空。
  • 远端 master API 返回 7700b211858eb70fc9f45c40fb596e65d13949e7。
  • 独立执行 git merge-tree --write-tree 7700b21185 de359c2a5e,得到 4d227b5ed982461c8e008b907a7711ac7c9525dc,无冲突。
  • 本地实 merge 3a6f83f2eb1f55867d872c357d357f65f96d370a 的双亲为 de359c2a5e + 7700b21185,其 tree 与上述预测树逐字相同;也与已完成 typecheck、build 和 2410 条 Vitest 验证的树一致。
  • master 漂移与 PR 全量文件的交集只有 src/daemon.ts。PR hunk 为 @@ -33370,7 +33370,7,master 最后一个 hunk 从 @@ -32106,7 +32136,7 起,分属不同区域且其后无 hunk,不存在相邻编辑。

结论:合并树满足 G7 豁免条件,可沿用 de359c2 的 G4 全绿与同树验证结果,无需再推同步提交,可直接 squash。

@deepcoldy
deepcoldy merged commit f5e3b04 into deepcoldy:master Nov 19, 2026
15 checks passed
@deepcoldy

Copy link
Copy Markdown
Owner

感谢 @Disaster-Terminator 的贡献,这个补账归因改进已经合入 master。

这次解决的问题:Codex/TraeX 会话在跨天、切换模型、daemon 重启后补账时,旧逻辑会把多日多模型用量合成一条记到重启当天。现在按原生日志的真实时间戳和模型逐条归属,并通过原生检查点(nativeCheckpoint)保证计数重置和分段重放下不重不漏;月预算也改为按账本记录去重恢复,迟到的上月记录只进上月预算。

合入过程中补齐了几个边界:跨 reset 的分段前缀重放去重、以索引活跃分段为右边界、退役分段半行尾不再拖垮恢复链、64 MiB 扫描上限、reset 落盘失败后的内存基线与可重启重建、无模型元数据时按未知模型记 token 不猜价。

后续非阻断的改进点(不影响本次合入):

  1. cost-calculator.ts 恢复路径里 entry.payload.context?.model 目前在仓库内没有真实产线字段依据,实际总回退到聚合模型,建议后续确认来源或移除。
  2. 恢复游标恢复时的行身份校验(resume offset 处行内容比对)目前没有直接单测,靠锚点哈希、末值相等、时间单调三层兜底,建议补一个针对性用例。
  3. resolveSessionTranscriptPaths 的日期目录遍历没有条目上限(单文件查找器在不可信根下有 5 万条封顶),建议对齐一个保护性上限。
  4. budget-tracker.ts 重建时对 ledger 文件名用的是 startsWith 宽松匹配,建议与 ledger 侧的锚定正则 ^usage-\d{4}-\d{2}-\d{2}\.jsonl$ 对齐。

以上为自动评审流程的记录,最终以维护者审阅为准。欢迎继续贡献。

@github-actions

Copy link
Copy Markdown

🚀 Released in v3.59.22

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants