Fix token-based compaction retaining too little recent history

Merged
AN
2mo ago
+803-96

Problem

Automatic compaction can reduce a large conversation to far less original recent history than keep_tokens specifies.

For example, a conversation grows to 190k estimated history tokens and crosses max_tokens=170_000:


Older history             139k

Recent large message       48k

Newest messages             3k

With keep_tokens=50_000, the existing cutoff excludes the 48k message and keeps only the newest 3k. Summarizing compaction summarizes the other 187k, potentially leaving the resulting context well below 50k. Sliding-window compaction discards that prefix. The problem is what survives high-context automatic compaction, not manually compacting just above 50k.

This fixes the existing retention behavior by including the boundary-crossing message, retaining 51k of original history in that example. No min_keep_tokens option is added.

[!WARNING]

Compatibility impact: Positive keep_tokens now retains a minimum whole-message suffix rather than selecting a tail below an upper-budget target. Existing configurations can retain more context, and copied older user turns no longer displace that suffix.

Release policy: This change is in the 0.x harness package, whose version policy permits behavior changes between minor releases. Previous upper-budget semantics were documented and tested; this PR does not describe them as an undocumented assumption.

Migration: Review context headroom and compaction trigger thresholds. Lower the retention target if needed, accounting for whole-message/tool-pair overshoot and summary/request overhead. This is not a strict context-window limit. keep_tokens=None, keep_tokens=0, and message-count mode retain their existing behavior.

Closes #9768. Replaces the closed opt-in proposal #9769 following the author's discussion with the repository owner and the request to fix current compaction behavior instead.

Fix

  • Select the shortest original message suffix reaching positive keep_tokens, including the boundary message.

  • Count message-part text with the configured tokenizer/default heuristic; attached request instructions do not satisfy the retention target.

  • Resolve tool returns and tool-specific retries to their nearest preceding call occurrence, including reused IDs and transitive/long-gap dependencies. Dependency expansion uses a forward index and a single reverse pass.

  • Keep the protected suffix contiguous and unchanged. Summary, receipt, pin, and older-user-copy processing cannot displace or edit it.

  • Leave histories below the retention target unchanged without a summary call.

  • Update existing upper-budget assertions and document current retention behavior in both documentation surfaces.

Validation

  • Automatic Agent before/after comparison using upstream versus corrected cutoff: 3,000 -> 51,000 retained original tokens for both strategies, from 190k history with a 170k trigger and 50k retention target.

  • Python 3.13 compaction suite and docs parity, including DBOS tests: 1,018 passed, 3 skipped.

  • New regression module on Python 3.10: 110 passed.

  • New regression module with Trio: 110 passed.

  • Compaction documentation examples/snippets: 30 passed, 2 skipped.

  • Repository-wide Ruff check/format: passed.

  • Pyright for the complete compaction implementation and test directories: zero errors or warnings.

  • git diff --check: passed.

  • After CI identified legacy-edge coverage gaps, added 13 zero-token/message-count regressions. Focused coverage of both flagged implementation modules now reports 100% statements and branches (628 statements, 322 branches).

  • Separate Code Puppy checkout using matching editable slim, graph, and harness from this exact monorepo fix: 614 passed, 12 skipped across agents, capabilities, and launcher tests. The source-verifying focused launcher also passes 52 tests; uv pip check passes.

  • Code Puppy's actual HistoryCompaction capability is exercised through Agent.run, covering automatic summarization, truncation, summary-failure fallback, and below-threshold non-compaction. Complete preserved fixture tool results and their matching calls are compared byte-for-byte; archive removal, durable history, and dropped-message hashes are checked.

The automated Code Puppy integration suite uses deterministic in-process models, not a live-provider/TUI session. A separate live headless CLI execution also passed, as detailed below. Neither token estimator is mocked: approximately 190k CP-estimated tokens triggers at 170k and retains approximately 51k harness-estimated tokens with keep_tokens=50_000. CP estimates characters/2.5; harness retention estimates characters/4. These are not provider-token measurements. Normal Code Puppy configuration and credentials were not modified.

The isolated validation is recorded locally at Code Puppy commits ee53862f and 321f085a, against Pydantic implementation commit c0f285a3b and final test commit 87096dda4. Its machine-local dependency overrides are not proposed for upstream. Rerun from the isolated checkout with .venv\Scripts\python.exe scripts\run_min_retention.py.

Independent review reproduced and verified the reused-tool-ID edge case and the transitive dependency fix. The tests also cover large/changing instructions, custom tokenizers, receipts, pins, additional user turns, unchanged message-count/zero-token modes, and retained message identity/serialization.

Live Code Puppy headless validation

Executed the actual Code Puppy CLI with --resume and --prompt, using gpt-5.5 through the existing ChatGPT OAuth plugin. A seeded conversation contained real fixture text; the prompt requested hidden records from the retained tool results and prohibited tools, file reads, and delegation. No compaction routines, token estimators, or model transports were mocked.

| Measurement | Estimated tokens |

|---|---:|

| Seed history, Code Puppy estimator | 190,201 |

| Automatic trigger measurement including prompt/overhead | 193,090 |

| Trigger threshold | 170,000 |

| Configured keep_tokens | 50,000 |

| Unchanged paired tool suffix alone, harness estimator | 51,015 |

| Compacted request history, Code Puppy estimator | 82,250 |

| Compacted request history, harness estimator | 51,793 |

  • One automatic summarization event, two provider requests (summary and answer), zero live tool calls.

  • Both complete tool results (192,000 and 12,000 characters) and their matching calls survived unchanged. Strict serialized-part audits passed for the post-compaction snapshot and CLI-saved session.

  • An additional independent check confirmed the four complete original message JSON objects remained contiguous and exactly equal in both artifacts, with no field normalization.

  • The old archive was removed; the model returned all four expected fixture values exactly. The new prompt did not contain those values, and disabled tools prevented rereading files to mask lost history.

  • The retention floor is met by original tool history alone, excluding the generated summary. CP and harness use different estimators; these figures are not provider token counts.

  • All XDG directories and CWD were isolated. OAuth credentials were read into memory only, with refresh/saving disabled. Normal credential/config/catalog/MCP files were unchanged; an artifact scan found no credential/account values.

The successful run's provider usage was 76,187 input tokens and 250 output tokens. There were two successful live executions during development (the first exposed an observer-order issue), plus three setup attempts that failed before generation. Combined reported cost estimate: $0.778065. The final strict audit was rerun without further provider calls.

Local artifacts and reproducible commands are documented in docs/LIVE_KEEP_TOKENS_VALIDATION.md in the isolated Code Puppy checkout. The capture is an application history snapshot, not a raw HTTP request capture.

CI follow-up

The initial run found the legacy-edge coverage gaps now addressed by 87096dda4. Its unrelated duplicate-import lint failure was fixed upstream in #9787. The updated full CI run completed successfully: 70 jobs passed, zero failed, including the combined coverage gate. Local development and live headless validation are complete.

Release note

Fix token-based harness compaction discarding the message that crosses keep_tokens and retaining much less original history than configured. Positive targets now retain at least that amount when available, with whole-message/tool-dependency overshoot. Applications should review context headroom; zero-token and message-count modes are unchanged.

Checklist

  • Bug fix uses existing configuration; no new retention option.

  • Compatibility impact and migration are documented in this PR.

  • PR title and release note describe the user-visible fix.

  • Focused Pydantic and Code Puppy integration tests pass.

  • Upstream CI and combined coverage gates.

  • Actual headless Code Puppy run and independent saved-history audit.