Project-scope sessions miss the prompt cache on nearly every turn: boundRecent sliding window shifts the history prefix each turn
Summary
In project (managed group) scopes, once a session's history is larger than the history budget, almost every new turn misses the prompt cache past the system prompt. The first model call of each turn re-writes about 180-200k tokens of cache.
Evidence (one instance, captured usage from /v1/admin/sessions/:id/llm)
- Project-scope session, 84 turns: on step 0 of a new turn, 72 of 84 calls had a cache hit rate under 50%.
cacheReadwas about 17k (system + tools only) andcacheWritewas about 185k. This happened even when the previous turn had ended seconds earlier (48 of 54 turns with a gap under 4.5 min missed), so the cache TTL isn't the cause. - Within a turn, steps 1..n hit about 99%.
- Cost share: in two project sessions, 73% and 58% of all model spend was these step-0 cache writes (about $1.50 per turn on Opus).
- Personal DM sessions, where compaction summaries are allowed, miss much less often.
- The proxy's account affinity (CLIProxyAPI, LCP session affinity) kept the same upstream account across these turns, so the misses aren't caused by switching accounts.
Cause (from source)
src/core/orchestrator/compaction.ts:
summarizeForCompactionreturnsnullforisManagedGroupScope(...).- So
compactContextIfNeededfalls back toboundRecent(visibleHistory, maxContextTokens)each turn. boundRecenttrims the oldest items so the history fits exactlymaxContextTokens. Each new turn adds items, so the start of the window moves forward every turn. That changes the message prefix and invalidates the cached conversation.
Suggested fix
Add hysteresis to the sliding-window path. When history goes over the hard fraction, trim down to keepPercent of the budget (as compactRecent already does), not to exactly 100%. Also keep a stable window start (anchor seq) until the next trim. The prefix then stays the same for many turns, and turns stay cached. Another option is to allow compactRecent-style marker trimming in managed groups.
Spot-on diagnosis on boundRecent shifting every surviving history index once the sliding window fills.
We modeled this exact pattern in kvbytepack (Apache-2.0): kvbytepack audit flags MUTATED_HISTORY_PREFIX at the shifted message boundary and reports observed vs achievable hit rates offline, which can help compare chunked eviction/compaction boundaries against saved JSONL traces.