Skip to content

[TASK] Spike: why the compaction trigger estimate exceeds the provider's prompt_tokens #1586

Closed

Description

@edenreich

Summary

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

Activity

  1. added
    refactor
    on Oct 20, 2026
  2. added theissue type on Oct 20, 2026
  3. moved this to Todo in 2026on Oct 20, 2026
  4. edenreich commented on Oct 20, 2026

    @edenreich
    ContributorAuthor

    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 raw ToolExecutionResult JSON (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 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:

    124 "╰── Result:                         …"
    124 "    Exit Code: 0                    …"
    124 "    short                           …"
    124 "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx…"
    

    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.

    Two consequences of that path:

    • The backoff from fix(compaction): emit a failure event and back off after a failed summary #1584 only guards !force (conversation_optimizer.go), so after a failed summary the rollover re-fires every turn. The run shows five compaction_started in six minutes before one compaction_completed.
    • 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.

    Proposed fixes

    Filed as follow-ups:

  5. edenreich commented on Oct 20, 2026

    @edenreich
    ContributorAuthor

    Findings are in the comment above. Fixes: #1590 → #1593, #1591 → #1594, #1592 → #1595.

  6. moved this from Todo to Done in 2026on Oct 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    refactor

    Type

    Projects

    • Status
      Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions