Skip to content

fix(agent-core-v2): use measured tokens before compaction - #4615

Open
wszqkzqk wants to merge 1 commit into
MoonshotAI:mainfrom
wszqkzqk:fix/compaction-measured-token-counts
Open

wszqkzqk wants to merge 1 commit into
MoonshotAI:mainfrom
wszqkzqk:fix/compaction-measured-token-counts

Conversation

@wszqkzqk

@wszqkzqk wszqkzqk commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Requirement or Bug

Resolve #4614

长会话自动压缩时,用户看到的压缩前 token 数可能明显低于实际触发值,从而误以为压缩过早发生。本 PR 让压缩任务和完成记录复用供应商实测前缀,只估算尚未实测的新增消息,使两处计数与自动压缩的触发口径一致。

Bug Reproduction Steps

See linked issue.

Root Cause

自动压缩的触发判断使用 token-counting 服务的“实测前缀 + 新增消息估算”,但压缩开始校验和最终记录都调用 requestTokens(),重新估算系统提示、工具定义和全部历史消息。两条路径对同一份上下文给出了不同结果。

这是根本修复:统一压缩前计数的口径,不调整触发阈值,也不隐藏或修正展示数字。

Code Changes

 preCompactionTokenCount
-  estimate(systemPrompt + tools + allMessages)
+  if measuredPrefixExists
+    return measuredPrefix + estimate(pendingMessages)
+  return estimate(systemPrompt + tools + allMessages)
  • validateCompactionStart:压缩任务和 PreCompact hook 使用上述计数。
  • compactionRound:完成事件、会话记录和遥测中的 tokensBefore 使用同一计数。
  • 没有实测锚点时保留原来的完整请求估算,避免漏掉系统提示和工具开销。
  • 压缩阈值、触发时机、tokensAfter 的估算与后续实测校正,以及 wire/API 字段结构均不变。

核心实现位于 fullCompactionService.ts;回归测试只增加在现有 fullCompaction.test.ts,分别覆盖有实测前缀的真实工具结果尾部和无实测锚点的回退路径。

Behavior Changes and Affected Users

行为 修改前 修改后 依赖原行为的人群 退路
有实测锚点时的压缩开始计数 全量本地估算 实测前缀 + 新增消息估算 PreCompact hook、显示压缩任务的 TUI/web/desktop 客户端 无;修正数值,字段结构不变
有实测锚点时的 tokensBefore 全量本地估算 与触发判断和开始计数一致 压缩块、会话回放/导出、遥测分析及读取该字段的外部脚本 无;修正数值,历史记录不变
无实测锚点时的压缩前计数 完整请求估算 不变 供应商不返回 usage、旧会话或首次实测前手动压缩的用户 不需要;旧行为有回归测试保护

压缩后的 tokensAfter 仍在下一次供应商响应前保持估算,随后按现有机制实测校正。没有修改默认配置、公开字段、旧会话格式或客户端请求。

受影响模块与覆盖:

  • agent-core-v2 压缩开始与完成路径:验证实测前缀、工具结果尾部估算,以及两个计数出口的一致性。
  • 无实测数据的回退路径:验证系统提示、工具定义和全部消息仍被计入。
  • 现有压缩行为:完整 full-compaction 测试套件继续通过。
验证记录
  • fullCompaction.test.ts:122/122 通过。
  • 新增的两条回归测试分别通过单点变异验证,能够独立发现开始计数和结果计数的回退。
  • @moonshot-ai/agent-core-v2 typecheck 和 build 通过。
  • pnpm lint:0 error;仓库已有 warning 未改动。
  • git diff --check 通过。
  • 本地全仓测试未完整运行,全量验证交由 PR CI。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

Copilot AI balanced review requested due to automatic review settings November 2, 2026 13:32
@changeset-bot

changeset-bot Bot commented Nov 2, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: f2575da

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@moonshot-ai/kimi-code Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-02T13:37:20.692850Z f2575da PR opened
ℹ️ 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.

@pkg-pr-new

pkg-pr-new Bot commented Nov 2, 2026

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@f2575da
npx https://pkg.pr.new/@moonshot-ai/kimi-code@f2575da

commit: f2575da

@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: f2575da6a7

ℹ️ 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".


private requestTokensWithMeasuredPrefix(messages: readonly Message[]): number {
const context = this.tokenCounting.get(agentContextOfScope(this.agent), 0, messages.length);
return context.measured > 0 ? context.size : this.requestTokens(messages);

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 Require a provider-measured anchor before skipping request overhead

When a provider omits usage under the default measured+estimated strategy, TurnEnded pins an estimated (measured: false) anchor, but TokenCountingAgentModel.get() still puts that anchor's token count in ContextSize.measured. This condition therefore treats a message-only estimate as a provider-measured prefix and skips requestTokens(), which is the only path adding the current system prompt and tools; compaction-start and tokensBefore counts are underreported for these sessions. Check actual anchor provenance before taking this fast path.

AGENTS.md reference: AGENTS.md:L111-L113

Useful? React with 👍 / 👎.

This branch has not been deployed

No deployments
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.

bug(compaction): pre-compaction token count disagrees with measured usage

2 participants