Repository navigation
Description
What version of Kimi Code is running?
2.4.0. The same code path is also present in upstream/main at a2afdbc; I have not rerun this live session on the latest release.
Which open platform/subscription were you using?
Managed Kimi provider.
Which model were you using?
An OpenAI-compatible coding model with a declared 1,048,576-token context window.
What platform is your computer?
Linux x64 (remote environment; exact kernel details were not captured).
What issue are you seeing?
Automatic compaction triggered at the correct threshold, but its completion record reported a much smaller pre-compaction token count. This makes compaction look premature.
Observed values:
- Last provider usage:
890624 inputCacheRead + 535 inputOther + 153 output = 891312 tokens. - Default trigger:
1048576 × 85% = 891289.6 tokens, so this response had just crossed the threshold. context.apply_compaction:tokensBefore: 798833,tokensAfter: 31223(shown as780.1k → 30.5k).
The reported tokensBefore is a fresh local estimate, not the measured-plus-estimated count that triggered compaction.
What steps can reproduce the bug?
- Use a model with a 1,048,576-token window and the default compaction settings.
- Grow a tool-using session until the provider-reported input plus output crosses 85% of the window.
- Add a tool result after that measured response, then let automatic compaction run before the next step.
- Compare the last
usage.record/token_counting.measuredevent withcontext.apply_compaction.tokensBefore.
In the observed session, the measured anchor covered 1,368 messages and one final tool result was added before compaction.
What is the expected behavior?
Both the in-flight compaction tokenCount and the final tokensBefore should use the same measured-plus-estimated context size as the trigger: in this case, 891312 plus the estimated final tool result.
When no measured anchor exists, the full local request estimate should remain the fallback. tokensAfter can remain an estimate until the next provider response supplies measured usage.
Additional information
In packages/agent-core-v2/src/agent/fullCompaction/fullCompactionService.ts, validateCompactionStart and compactionRound use requestTokens(), which re-estimates the system prompt, tools, and all messages. The automatic trigger instead uses the token-counting service's measured prefix plus estimated tail.
Reusing that existing hybrid count for both pre-compaction fields would fix the mismatch without changing the wire schema. I have a small patch with regression coverage ready.
Contribution
- I am willing to submit a PR for this bug fix myself (please wait for maintainer approval in this issue first)
Activity