Add `min_keep_tokens` to harness compaction strategies

Draft
AN
2mo ago
+700-17

Problem

When a large conversation is automatically compacted, its original recent history can shrink to a few thousand tokens even when the application configures keep_tokens=50_000. That setting is a retention budget, not a minimum, so it cannot guarantee that the agent keeps at least 50k tokens of unchanged working context after compaction.

For example, configure SummarizingCompaction(max_tokens=170_000, keep_tokens=50_000). Before the next model request, the estimated history has grown to 190,000 tokens, crossing the automatic compaction threshold:

Before automatic compaction:                 190k
  Older history                             139k
  A recent large message                     48k
  Newest messages                             3k

Keeping the newest 3k plus the preceding 48k message would exceed the 50k budget. With no tool dependency forcing the boundary backward, the budget-based cutoff can therefore keep only 3k of original recent history, summarizing the other 187k. With a short summary, the resulting history is well below 50k. Sliding-window compaction can discard that older prefix instead and leave just the 3k tail, aside from separately preserved messages.

The issue is the retention decision after the high-context auto-compaction trigger, not an application compacting as soon as its history exceeds 50k. A caller needing a 50k minimum should retain the boundary-crossing message: 51k of original recent history, plus any summary and other overhead.

This is a missing capability, not a change to the existing budget semantics. The example uses estimated history tokens; request overhead and whole-message/tool dependencies can change the final total.

Proposed solution

Add an opt-in, keyword-only min_keep_tokens to SlidingWindowCompaction and SummarizingCompaction. It includes the whole message that crosses the minimum and extends backward for tool-call dependencies, while leaving existing defaults and keep_tokens behavior unchanged.

Related proposal: #9768. This draft requests maintainer agreement on the API and scope; approval and assignment have not been obtained. The implementation was tested in a personal harness fork and ported to this repository following the harness migration.

Behavior

  • Retain the shortest whole-message suffix reaching the minimum, including the boundary-crossing message.
  • Extend backward for matching tool calls, including tool-specific retry responses and dependencies beyond the existing nearby-message search window.
  • Preserve the suffix unchanged, including existing receipts and pinned parts. Summaries, reinserted pins, and optional older-user copies remain outside it.
  • Count message-part text with the configured tokenizer/default heuristic. Attached ModelRequest.instructions cannot satisfy the floor; system-prompt message parts still count.
  • Leave short histories unchanged without a summary call. Validate a positive minimum and reject combining it with keep_tokens.

Whole messages and dependencies can overshoot the floor. This is not a context-window-fit guarantee; callers must handle insufficient remaining request budget. Fallback chains must configure the floor on every strategy that must preserve it. Both documentation surfaces describe these limits.

Validation

Windows, current upstream checkout:

  • Python 3.13: 1,014 passed, 4 skipped across tests/harness/compaction and tests/harness/test_docs_parity.py.
  • Python 3.10: 109 passed in the new minimum-retention module.
  • Harness compaction documentation examples/snippets: 32 passed, 2 skipped.
  • Core documentation examples selected by compaction: 2 passed, 4 skipped, with the optional TypeSafe SDK installed for its unrelated example.
  • Repository-wide Ruff check and format check: passed.
  • Pyright on all changed Python files: zero errors or warnings.
  • git diff --check: passed.

Tests cover both strategies, automatic Agent compaction, whole-message boundary crossing, exact/short/empty histories, custom tokenizers, large/changing instructions, pin placement, receipts, extra user copies, tool returns/retries, fallback, invalid configuration, and unchanged legacy behavior. Assertions check retained message identity and serialization through the explicit compaction API.

An earlier revision was also exercised in a separate Code Puppy checkout: manual compaction reduced its displayed history estimate from 175,905 to 87,146, retaining all original file-read results for fixtures 26–50 and their tool calls. All 25 retained results matched the fixture files exactly; retained message text exceeded the 50k floor. The display and harness use different estimators, so those UI values are not provider token counts.

The repository-wide provider/integration matrix and coverage gate are left to upstream CI. No external model credentials are needed by the new tests.

Checklist

  • No breaking changes: the new option is keyword-only and disabled by default.
  • No compatibility-impact waiver is needed; existing retention modes are unchanged.
  • PR title is written for the release changelog.
  • Maintainer agreement on the proposal in #9768.
  • Upstream CI and coverage gates.