kimi-code icon indicating copy to clipboard operation
kimi-code copied to clipboard

Compaction request itself loses the prompt cache when any MCP server is deferred

Open UniBody opened this issue 1 month ago • 0 comments

Environment

  • Kimi Code CLI 2.1.1 (macOS 26.6.2, arm64)
  • Model: kimi-code/k3.1-pro — capabilities include dynamically_loaded_tools, so the progressive-disclosure gate is open (toolSelect: true)
  • One MCP server configured with "deferred": true (170 tools), never loaded during the session

Summary

A compaction request re-sends the full history, so it should be prefix-friendly. In practice it cannot reuse the prompt cache at all once the session has a deferred MCP server: stripDynamicToolContext() drops the loadable-tools announcement, while normal loop requests keep it via shapeActiveHistory(). The two shapes diverge at the announcement (message #6 in the session), so only system + tools is cacheable and everything after it is billed as fresh input.

Evidence

One wire.jsonl, two consecutive requests, no config change in between:

llm.request  kind=loop        messageCount=178  systemPromptHash=a62f106e…  toolsHash=8eaa7e47…
usage.record                                     inputCacheRead=336,640  inputOther=1,576     → 99.5% hit

llm.request  kind=compaction  messageCount=179  droppedCount=0  systemPromptHash=a62f106e…  toolsHash=8eaa7e47…
usage.record                                     inputCacheRead=77,568   inputOther=260,915   → 22.9% hit

context.apply_compaction  tokensBefore=329,099  tokensAfter=85,235  summaryOutputTokens=4,843
  • systemPromptHash and toolsHash are identical to the preceding loop request — the system prompt and the tools[] block are byte-identical.
  • messageCount grew by exactly 1 (the appended compaction instruction).
  • droppedCount = 0 — preShrinkHistoryToWindowBudget() trimmed nothing, so head truncation is not the cause in this case.
  • 77,568 ≈ system prompt (17.6k) + tool schemas (63.5k): the cache matches up to the end of tools[] and breaks at the first conversation message.

Across 151 compactions in local session logs: with no deferred tools configured, compaction hits 92–99.8%; with deferred tools present it settles around 23%, independent of context size, trigger ratio, or model window.

Root cause

packages/agent-core-v2/src/agent/toolSelect/toolSelectService.ts

shapeHistory(messages) {
  if (this.enabled()) return this.shapeActiveHistory(messages);
  return stripDynamicToolContext(messages);
}
  • Normal loop request → shapeActiveHistory(). shapeActiveMessage() only filters entries of messages that carry a tools[] array; messages without it are returned unchanged, so the announcement survives.
  • Compaction request → stripDynamicToolContext():
function stripDynamicToolContext(history) {
  if (!history.some((m) => isDynamicToolSchemaMessage(m) || isLoadableToolsAnnouncement(m))) return history;
  const out = [];
  for (const message of history) {
    if (isLoadableToolsAnnouncement(message)) continue;   // ← announcement dropped
    // ... messages carrying tools[] lose the field; empty shells are dropped
  }
  return out;
}

loadableToolsAnnouncement() returns undefined only when added.length === 0 && removed.length === 0, so any deferred-but-unloaded tool guarantees the announcement exists. The divergence is therefore unconditional whenever toolSelect is on and at least one server is deferred — it does not require the user to have loaded anything.

The announcement in this trace is 5,727 chars (~1.4k tokens) sitting at message #6, so deleting it invalidates ~260k cached tokens of conversation.

Expected behavior

The compaction request should be as prefix-friendly as a normal loop request. Possible directions:

  1. Route both paths through the same shaping function (shapeHistory() / shapeActiveHistory()) instead of applying a stricter strip only to compaction.
  2. Keep the announcement in the compaction request and drop it only from the rebuilt post-compaction context.
  3. If stripping is required for size reasons, apply it consistently to loop requests too, so both shapes agree.

Reproduction

  1. mcp.json: one server with "deferred": true exposing many tools.
  2. Start a session with a model declaring dynamically_loaded_tools; chat a few turns (the announcement is injected on turn 1).
  3. Run /compact.
  4. In agents/main/wire.jsonl, compare the llm.request(kind="compaction") + usage.record pair with the preceding loop pair: droppedCount=0, identical systemPromptHash/toolsHash, and inputCacheRead ≈ system+tools only.

Workaround

  • Remove every "deferred": true server — the announcement disappears and compaction hits 99%+ again, or
  • Avoid /compact in such sessions and start a fresh session with a written handoff file instead.

Related

  • #3357 — cache miss on the first call after compaction. This issue is about the compaction request itself; the two effects stack.

UniBody avatar Oct 25 '26 09:10 UniBody