You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[TASK] Spike: why the compaction trigger estimate exceeds the provider's prompt_tokens #1586
Spike: find out why the compaction trigger estimate runs far above the provider's prompt_tokens.
On https://github.com/edenreich/das-ist-berlin/actions/runs/39459666409 (CLI v0.233.0, ollama_cloud/glm-5.3-flash, 1M context window, compact-auto-at: 50) the compaction_started events reported current_tokens of 497k to 633k while the gateway's usage.prompt_tokens on the same turns was 178k median and 266k at most. The estimate is estimateTriggerTokens in internal/conversation/conversation_optimizer.go: the max of the repo's LastInputTokens and TokenizerService.EstimateMessagesTokens (chars/4 over content, tool call arguments, tool call ids, reasoning). Which part diverges from what the provider counts is not established. Split out of #1581, whose re-fire after a failed summary is fixed by #1584.
The same run shows force: true on auto-fired compactions although the agent loop passes force=false. Session rollover (session_rollover.go) gates on the same estimate and compacts with force, so it is the likely caller. Confirm it from the logger output.
Acceptance Criteria
A reasoning-heavy run (glm-5.3-flash or deepseek) logs, per turn, the estimate's parts (content, tool arguments, reasoning) next to the provider's prompt_tokens, and the comparison says which part the provider does not count
The force: true caller on auto compaction is identified from the logger output
Findings and the proposed fix are written on this issue, as follow-up issues if code changes are needed
1. Trailing-space padding in tool results (the bulk of the gap). Tool results reach the LLM through FormatToolResultForLLM, which renders a lipgloss tree (internal/tools/formatter.go, renderExpandedTree). The tree uses lipgloss.JoinHorizontal, and JoinHorizontal right-pads every line of a block to the block's widest line (charm.land/lipgloss/v2/join.go, "Also make lines the same length"). Rendering a Bash result with one 120-char line through BaseFormatter{}.FormatExpanded pads every line of the Result: block to 124 runes:
Through the first compaction_started of the run there were 58 tool results with a raw body of 296k chars. Padded to the widest line of each result they are 1.33M chars. At chars/4 that is ~332k estimated tokens for ~74k of content. The provider receives the padding too, but its tokenizer collapses runs of spaces into few tokens, so prompt_tokens stays near the content. chars/4 cannot. The padding is also real waste on every request.
2. Reasoning is counted twice.buildAssistantMessage stores the same string in both Reasoning and ReasoningContent (internal/agent/loop/agent_streaming.go), BuildAgentMessagesFromEntries does the same on replay (internal/conversation/domain/agent_messages.go), and EstimateMessageTokens adds both fields (internal/conversation/tokenizer.go). Reasoning through the first compaction was 240k chars, so this is ~60k phantom tokens, and ~120k if the provider ignores prior-turn reasoning altogether (typical for OpenAI-compatible endpoints).
Reconciliation at the first compaction (17:04:57, current_tokens: 497420, provider prompt_tokens: 230960 on the turn before):
Part
Estimate (chars/4)
Provider
Tool results, padded to widest line
~332k
~74k of content
Reasoning, counted twice
~120k
0 to ~60k
Tool arguments, text, per-message overhead
~15k
~15k
System prompt, tool definitions, volatile tail
not in the rollover's entries
the remainder of 231k
Total
~467k (reported 497k)
230,960
The rest of the gap is the tree prefixes (│ per line) and the Read/Bash headers.
The force: true caller
Session rollover. maybeRolloverSession runs at the top of every headless turn (internal/agent/loop/utils.go), before the auto path in optimizeConversation (agent.go, force=false), so the auto path never gets to fire first. MaybeRollover → PerformRollover → OptimizeMessages(messages, model, true) (session_rollover.go).
Proof from the log: all nine compaction_started events carry force: true, and the first reports current_tokens: 497420 under threshold: 500000. Only a forced call can log a value below the threshold. The gate (ShouldRollover → tokenTriggerFires) estimates over every entry including the 38 hidden system reminders, while PerformRollover drops hidden entries before calling the optimizer, so the gate crossed 500k and the compaction it triggered did not.
PerformRollover does not check whether the optimizer reduced anything. On a failed summary it logs "optimizer returned no reduction, copying messages as-is", still starts a new conversation and copies the full history into it. Each failed attempt in the run also rolled the session over with no summary.
Activity
fix(compaction): emit a failure event and back off after a failed sum…
edenreich commentedon Oct 20, 2026
Findings
Source: the job log of https://github.com/edenreich/das-ist-berlin/actions/runs/39459666409 (job 118755523003) plus the code on
main(26580c0). The headless renderer prints each tool result as the rawToolExecutionResultJSON (internal/platform/render/render.go,toolContent), not the message the LLM receives, so the log gives the raw sizes and the code gives what is added on top.Which parts the provider does not count
1. Trailing-space padding in tool results (the bulk of the gap). Tool results reach the LLM through
FormatToolResultForLLM, which renders a lipgloss tree (internal/tools/formatter.go,renderExpandedTree). The tree useslipgloss.JoinHorizontal, and JoinHorizontal right-pads every line of a block to the block's widest line (charm.land/lipgloss/v2/join.go, "Also make lines the same length"). Rendering a Bash result with one 120-char line throughBaseFormatter{}.FormatExpandedpads every line of theResult:block to 124 runes:Through the first
compaction_startedof the run there were 58 tool results with a raw body of 296k chars. Padded to the widest line of each result they are 1.33M chars. At chars/4 that is ~332k estimated tokens for ~74k of content. The provider receives the padding too, but its tokenizer collapses runs of spaces into few tokens, soprompt_tokensstays near the content. chars/4 cannot. The padding is also real waste on every request.2. Reasoning is counted twice.
buildAssistantMessagestores the same string in bothReasoningandReasoningContent(internal/agent/loop/agent_streaming.go),BuildAgentMessagesFromEntriesdoes the same on replay (internal/conversation/domain/agent_messages.go), andEstimateMessageTokensadds both fields (internal/conversation/tokenizer.go). Reasoning through the first compaction was 240k chars, so this is ~60k phantom tokens, and ~120k if the provider ignores prior-turn reasoning altogether (typical for OpenAI-compatible endpoints).Reconciliation at the first compaction (17:04:57,
current_tokens: 497420, providerprompt_tokens: 230960on the turn before):The rest of the gap is the tree prefixes (
│per line) and the Read/Bash headers.The
force: truecallerSession rollover.
maybeRolloverSessionruns at the top of every headless turn (internal/agent/loop/utils.go), before the auto path inoptimizeConversation(agent.go,force=false), so the auto path never gets to fire first.MaybeRollover→PerformRollover→OptimizeMessages(messages, model, true)(session_rollover.go).Proof from the log: all nine
compaction_startedevents carryforce: true, and the first reportscurrent_tokens: 497420underthreshold: 500000. Only a forced call can log a value below the threshold. The gate (ShouldRollover→tokenTriggerFires) estimates over every entry including the 38 hidden system reminders, whilePerformRolloverdrops hidden entries before calling the optimizer, so the gate crossed 500k and the compaction it triggered did not.Two consequences of that path:
!force(conversation_optimizer.go), so after a failed summary the rollover re-fires every turn. The run shows fivecompaction_startedin six minutes before onecompaction_completed.PerformRolloverdoes not check whether the optimizer reduced anything. On a failed summary it logs "optimizer returned no reduction, copying messages as-is", still starts a new conversation and copies the full history into it. Each failed attempt in the run also rolled the session over with no summary.Proposed fixes
Filed as follow-ups:
edenreich commentedon Oct 20, 2026
Findings are in the comment above. Fixes: #1590 → #1593, #1591 → #1594, #1592 → #1595.
fix(tools): stop right-padding tool result lines sent to the model (#…
fix(conversation): count a message's reasoning once in the token esti…
fix(conversation): gate a token-triggered rollover through the optimi…