Skip to content

fix(compaction): long sessions lose their own decisions when recent tool output overflows the summary - #195028

Merged
obviyus merged 5 commits into
mainfrom
fix/compaction-summary-priority
Nov 8, 2026
Merged

obviyus merged 5 commits into
mainfrom
fix/compaction-summary-priority

Conversation

@obviyus

@obviyus obviyus commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #194408

What Problem This Solves

Fixes: after compaction the agent forgets decisions, TODOs and IDs from the summarized span when the most recent turns before the cut carried a lot of tool output.

User Impact

User impact: compacted summaries keep almost all of the model's own decisions and TODOs at the same 16,000-character size, with no extra replay cost and no new setting.

Why This Change Was Made

The persisted summary holds the model-written summary plus verbatim "recent turns preserved" context. Before this change the body only got half the budget once that suffix was large, so verbatim tool output (each result up to 600 chars, dozens per turn) displaced the generated summary. In 16 replayed production compactions the model's summary was always 6.9k–12.7k chars and would have fit on its own.

  • The generated body now reserves room only for the suffix's required sections (tool failures, file ops, workspace context, generated split-turn summary). Verbatim preserved turns take what is left, newest first, and a cut keeps their heading.
  • The suffix is assembled chronologically (preserved turns, split turn, then tool failures, file operations and workspace rules). The tail cap trims from the head, so older verbatim turns yield first and required sections stay; the split-turn reservation is no longer needed.
  • Preserved tool results keep a 160-char head excerpt plus [N more chars omitted at compaction], similar to how Hermes Agent demotes stale tail tool output to stubs.
  • Suffix budgeting moves to compaction-safeguard-budget.ts (line-cap ratchet).

This is an alternative to raising the cap (#194719): the replay showed the cap was binding because of how it was split, not because summaries needed more room.

Evidence

Replay of 16 truncated production compactions from one long-running agent (tokensBefore 144k–1.05M). Each span was rebuilt from stored entries with prepareCompaction and run through the real safeguard with the qualityGuard on, using the same cached Opus 5.5 summary responses for every variant:

variant mean length decision bullets kept TODO bullets kept model-chosen IDs kept
main, 16k 15,715 73.9% 65.5% 74.1%
this PR, 16k 15,852 95.5% 92.3% 80.7%
main, cap raised to 32k 26,311 100% 100% 83.1%
main, cap raised to 64k 33,365 100% 100% 83.1%

32k gets the last few points at roughly +2–3% cached-context cost per compaction window (a summary is replayed on a mean of 336 requests); 64k adds nothing over 32k.

End-to-end (real Gateway child, qa-channel, mock-openai provider): new scenario qa/scenarios/runtime/compaction-summary-priority.yaml seeds a session with three tool-heavy recent turns, overflows once, recovers through one safeguard compaction and delivers the final answer.

  • This head: pass. The persisted summary keeps the generated body through its last decision, has no truncation marker, and preserved tool results show [N more chars omitted at compaction].
  • Same scenario with main's safeguard: fail — the persisted 15,996-char summary loses the body end and ends in raw tool output.
  • Sibling compaction scenarios: compaction-retry-mutating-tool passes. compaction-empty-response-recovery, compaction-reasoning-only-recovery, goal-context-survives-compaction, cjk-tool-result-budget and gateway-compaction-abort fail identically on unmodified main (44a5a65).

Tests:

  • New: keeps a generated summary whole when verbatim preserved turns overflow the cap and keeps only a head excerpt of preserved tool output. Both fail on main.
  • finally trims a raw tool interaction only at its atomic boundary: fixture raised from 12 to 80 tool results so the interaction still overflows with excerpted output.
  • New: keeps required file operations when a large split-turn summary meets a large body (fails with the first revision's split-turn reservation).
  • compaction-safeguard*.test.ts (5 files, 57 tests) and packages/agent-core/src/harness/compaction (132 tests) pass.
  • pnpm check:changed: all steps pass except changelog attributions, which fails on main on untouched CHANGELOG/*.md files.
  • src/agents/sessions/agent-session-compaction.test.ts has 5 local failures that reproduce identically on main without this change.

Gaps: the replay did not measure compounding across successive compactions (each case started from the stored 16k summary), and identifiers lost before the summarizer (its input is sampled to 160k chars) are unaffected by this change.

…urns

The safeguard reserved room for the whole suffix before sizing the generated
summary body, so verbatim preserved-turn context (mostly tool output) cut the
model's own decisions, TODOs and identifiers. The body now reserves only the
suffix's required sections; preserved turns take what remains, a cut keeps
their heading, and the generated split-turn summary is reserved ahead of
older preserved turns. Preserved tool results keep a 160-char head excerpt.

Suffix budgeting moves to compaction-safeguard-budget.ts.

Refs #194408

Co-authored-by: obviyus <[email protected]>
@clawsweeper

clawsweeper Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Nov 8, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 8, 2026
@clawsweeper

clawsweeper Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR prioritizes generated compaction summaries over verbatim recent turns and shortens preserved tool-result excerpts.

Example: A 10,018-character generated summary and twelve bulky recent messages exceed the 16,000-character artifact limit.

  • Before: Reserving the entire recent-turn suffix cuts the generated summary before BODY-END.
  • After: The generated body retains BODY-END while older preserved messages yield space.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused repair has distinct regression coverage and no identified defect; proof is limited to reported replay and mock-provider runtime behavior, and the broader linked request remains partially addressed.
Proof confidence 🦐 gold shrimp (3/6) This collaborator-authored PR is outside the ordinary contributor proof gate; its body reports cached-response replay and a real Gateway/qa-channel run with mock inference, but supplies no real-model continuation or successive-compaction result.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: After tool-heavy compaction, the agent loses decisions and pending work that its generated summary contained.
Reason: This collaborator-authored repair addresses a source-backed retention failure with focused changes; its Related link appropriately leaves the broader configurable-cap request separate.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR addresses a current-main compaction retention bug, and the introduced changes contain no actionable correctness or security finding.

Priority: P2
Reviewed head: 2a6fc92584d2fbd9c17822598706d2369fb2cc51

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The reported Gateway run uses a mock model provider; real-model continuation and successive-compaction behavior are not demonstrated.
Agent review details

How this fits together

The safeguard receives prepared conversation history and generated summaries, combines them with recent context and diagnostic sections, and returns a bounded summary for session persistence and subsequent model requests.

flowchart TD
  A[Prepared conversation history] --> B[Summary provider]
  B --> C[Generated summary body]
  A --> D[Recent context and diagnostics]
  C --> E[Safeguard budget owner]
  D --> E
  E --> F[Persisted compaction summary]
  F --> G[Next model request]
Loading

Technical review

Best possible solution:

Keep the existing safeguard as the single budget owner and let verbatim context yield to generated facts within the current cap.

Do we have a high-confidence way to reproduce the issue?

Current-main allocation demonstrably lets a bulky suffix cut an otherwise affordable generated body, and the new boundary regressions encode that case; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The repair changes allocation at the existing finalization owner, removes the superseded reservation path, and preserves token fitting and atomic context boundaries without introducing a competing policy.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 31af70774f99.

Provenance checked

  • Generated-body and suffix allocation changes intended behavior with a stated reason (2ce443d: Common finalization guaranteed useful generated content while retaining bounded suffix context and explicit loss markers.)
  • Preserved tool-result excerpt size changes intended behavior with a stated reason (c8b45a4: Recent turns were retained to preserve fresh phrasing and immediate follow-up context, with a 600-character per-message excerpt.)
  • Degraded split-turn reservation changes intended behavior with a stated reason (83b5f54: Lossy recovery prioritized active split-turn context; this PR explains how chronological suffix ordering protects it without crowding out later file-operation sections.)
  • QA summary fixtures and transcript seeding keeps the original intent (6d88ec5: QA fixtures exercise compaction-output recovery; extraction preserves existing fault modes while adding the summary-priority scenario through canonical transcript APIs.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Josh Avant: Raw commit 2ce443d adds src/agents/agent-hooks/compaction-safeguard.ts:1409 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 2ce443d9a46b; files: src/agents/agent-hooks/compaction-safeguard.ts)

PR surface

Source +83, Tests +46, Other +129. Total +258 across 9 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 5 280 197 +83
Tests 2 48 2 +46
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 129 0 +129
Total 9 457 199 +258

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This improves decision and task retention after tool-heavy compaction without changing configuration or the artifact limit.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (3 earlier review cycles)
  • reviewed 2026-11-08T04:59:22.486Z sha 70f2d5b :: needs changes before merge. :: [P3] Preserve the separator before the restored context heading
  • reviewed 2026-11-08T05:34:44.544Z sha 4afee45 :: needs changes before merge. :: none
  • reviewed 2026-11-08T05:43:06.334Z sha 38facd8 :: needs maintainer review before merge. :: none

Reviewed November 8, 2026, 12:52 AM ET / 05:52 UTC (Revision 4).

…y QA proof

Always reserving the generated split-turn summary could crowd out required
tail sections (tool failures, file operations, workspace rules) when both the
body and the split summary were large. The suffix is now assembled in
chronological order (preserved turns, split turn, required sections), so the
head-first tail cap trims older verbatim turns first and the reservation is
removed. A restored context heading keeps its leading separator.

Adds a qa-lab scenario that overflows a tool-heavy seeded session through the
real Gateway and asserts the persisted summary keeps the generated body whole
and excerpts preserved tool output; transcript seeding gains tool calls and
results, and mock compaction summaries move to their own module.

Refs #194408

Co-authored-by: obviyus <[email protected]>
@clawsweeper

clawsweeper Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 8, 2026
@clawsweeper

clawsweeper Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 8, 2026
@clawsweeper

clawsweeper Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 8, 2026
@obviyus
obviyus merged commit 2d4ec7b into main Nov 8, 2026
147 checks passed
@obviyus
obviyus deleted the fix/compaction-summary-priority branch November 8, 2026 06:08
@obviyus

obviyus commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 9, 2026
…ool output overflows the summary (openclaw#195028)

* fix(compaction): keep generated summary ahead of verbatim preserved turns

The safeguard reserved room for the whole suffix before sizing the generated
summary body, so verbatim preserved-turn context (mostly tool output) cut the
model's own decisions, TODOs and identifiers. The body now reserves only the
suffix's required sections; preserved turns take what remains, a cut keeps
their heading, and the generated split-turn summary is reserved ahead of
older preserved turns. Preserved tool results keep a 160-char head excerpt.

Suffix budgeting moves to compaction-safeguard-budget.ts.

Refs openclaw#194408

Co-authored-by: obviyus <[email protected]>

* fix(compaction): order suffix chronologically and add summary-priority QA proof

Always reserving the generated split-turn summary could crowd out required
tail sections (tool failures, file operations, workspace rules) when both the
body and the split summary were large. The suffix is now assembled in
chronological order (preserved turns, split turn, required sections), so the
head-first tail cap trims older verbatim turns first and the reservation is
removed. A restored context heading keeps its leading separator.

Adds a qa-lab scenario that overflows a tool-heavy seeded session through the
real Gateway and asserts the persisted summary keeps the generated body whole
and excerpts preserved tool output; transcript seeding gains tool calls and
results, and mock compaction summaries move to their own module.

Refs openclaw#194408

Co-authored-by: obviyus <[email protected]>

* test(compaction): tighten split-turn file-ops regression

Co-authored-by: obviyus <[email protected]>

* test: allocate test lines for compaction summary priority regressions

Co-authored-by: obviyus <[email protected]>

* test: size compaction test-line allocation to measured growth

Co-authored-by: obviyus <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 10, 2026
…ool output overflows the summary (#195028)

* fix(compaction): keep generated summary ahead of verbatim preserved turns

The safeguard reserved room for the whole suffix before sizing the generated
summary body, so verbatim preserved-turn context (mostly tool output) cut the
model's own decisions, TODOs and identifiers. The body now reserves only the
suffix's required sections; preserved turns take what remains, a cut keeps
their heading, and the generated split-turn summary is reserved ahead of
older preserved turns. Preserved tool results keep a 160-char head excerpt.

Suffix budgeting moves to compaction-safeguard-budget.ts.

Refs #194408

Co-authored-by: obviyus <[email protected]>

* fix(compaction): order suffix chronologically and add summary-priority QA proof

Always reserving the generated split-turn summary could crowd out required
tail sections (tool failures, file operations, workspace rules) when both the
body and the split summary were large. The suffix is now assembled in
chronological order (preserved turns, split turn, required sections), so the
head-first tail cap trims older verbatim turns first and the reservation is
removed. A restored context heading keeps its leading separator.

Adds a qa-lab scenario that overflows a tool-heavy seeded session through the
real Gateway and asserts the persisted summary keeps the generated body whole
and excerpts preserved tool output; transcript seeding gains tool calls and
results, and mock compaction summaries move to their own module.

Refs #194408

Co-authored-by: obviyus <[email protected]>

* test(compaction): tighten split-turn file-ops regression

Co-authored-by: obviyus <[email protected]>

* test: allocate test lines for compaction summary priority regressions

Co-authored-by: obviyus <[email protected]>

* test: size compaction test-line allocation to measured growth

Co-authored-by: obviyus <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>

(cherry picked from commit 2d4ec7b)

Release adaptation: retain the 2026.11.3 branch's assembleSuffix and splitPreservedRecentTurns owners, current request recovery and session-store seeding contracts, and existing 16000-character/runtime decisions. Adapt the three regressions to current fixtures; preserve the upstream atomic-boundary fixture expansion and extract the two priority regressions into a coherent sibling to avoid growing the grandfathered oversized test file, and record 103 net test lines. Rename the QA final-answer marker to avoid the mock continuation-keyword heuristic while preserving all real-boundary assertions. No configuration or public-contract change.

Closure: canonical probe found only the three expected owner/test conflicts. Companion audit through 742ed31 found no later same-path fix or PR-number companion; current fitter/quality/QA contracts are present-equivalent. Independent read-only review found no P0-P2 issues.

Proof: two new owning-hook regressions failed before the fix; 55 focused core tests and 138 QA adapter tests pass. The real isolated Gateway/mock scenario passes including overflow recovery, intact generated summary and excerpted tool output. Focused native types, type-aware lint, format, line-cap and exact test allocation checks pass. Final independent read-only review found no P0-P2 issues.

Co-authored-by: RomneyDa <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 10, 2026
Release adaptation: Keep the release SQLite planner helper private and omit
agent-port-projections.ts, which does not exist on this release line. Preserve
all baseline assertions by materializing four small test fixtures, and exercise
lazy payload reads through the actual SQLite planner rather than a fake source.
Allocate the exact 64 net test lines. No schema, config, or authority changes.

Later same-path followups through 568d89f: 8633af9 (#194591) is the
non-applicable PostgreSQL surrogate repair; b6ed907 (#193682) is the
non-applicable schema41 hydration migration. Neither is a streaming prerequisite.
Existing #195028 and #196277 repair contracts remain intact.

Verified: baseline lazy-read regression fails; 32 focused tests pass across
five suites, including compiled-worker publication and authority boundaries.
Targeted types, lint, format, and whitespace checks pass. Fresh independent
read-only review found no P0-P2 issues.

(cherry picked from commit 7bc0ae7)

Co-authored-by: vincentkoc <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling extensions: qa-lab P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant