Skip to content

fix: avoid compaction from superseded history - #150623

Merged
obviyus merged 15 commits into
openclaw:mainfrom
goutamadwant:fix/active-window-token-estimate
Oct 1, 2026
Merged

obviyus merged 15 commits into
openclaw:mainfrom
goutamadwant:fix/active-window-token-estimate

Conversation

@goutamadwant

@goutamadwant goutamadwant commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Closes #150579

What Problem This Solves

Fixes: stale-usage preflight triggers unnecessary compaction after a session has already compacted but retains a large display history.

User Impact

User impact: healthy compacted sessions proceed without another budget compaction. Genuinely oversized active contexts still trigger compaction.

Why This Change Was Made

Use the existing asynchronous canonical model-context reader for the no-usage estimate, preserving the summary, retained tail, tool pairs, and newer messages while excluding superseded history. Headerless legacy projections retain their existing fallback.

The contributor's implementation and commits are preserved. Removed an unused re-export left by an earlier revision. Strengthened the real-Gateway regression to assert that no second compaction entry is persisted: one model request alone was not sufficient, because the baseline performed an unnecessary compaction without an extra provider request.

The new reader also recognizes an explicitly selected incognito database, not only an incognito-shaped session key. Such databases stay with their existing process-local owner instead of being reopened as empty worker-local databases.

No overlap with Pash/Sarah changes. Thanks to @goutamadwant for the fix and @BillBOT33 for the report.

Evidence

Secretless Docker, built runtimes, synthetic persisted sessions, explicit isolated profiles, loopback mock Anthropic transport, and real authenticated Gateway agent turns. Baseline: current main 3f263ba918c56e5c227261cb67be910e64bef74d.

Each healthy fixture retained 650,000 characters of superseded history behind a compaction boundary, with a short summary/tail and stale usage. The model window was 100,000 tokens; the blocking threshold was 80,000.

Scenario Transcript estimate Estimate including new prompt Observed behavior
Main, healthy compacted context 162,505 162,512 Budget compaction triggered and persisted a second compaction entry
Candidate, identical context 11 18 No compaction triggered; one original boundary remained; reply completed and persisted
Candidate, genuinely large active context 93,758 93,765 Budget compaction triggered and completed; reply completed

The healthy candidate's single provider request included the summary, active tail, and new prompt, but not the superseded marker. Memory flushing was disabled in this proof; it exercises the compaction path, not the reporter's complete hook/draining sequence.

  • SQLite-backed regression: failed on main because compaction was called; candidate file passed all 9 tests (45.80 s command wall time, 43.88 s Vitest duration). The first hosted run also passed all 9 tests in 24.97 s Vitest time (26.90 s command wall time).
  • Strengthened real-Gateway regression: failed on main with two persisted compaction entries instead of one; passed on the candidate (61.85 s command wall time, 34.92 s test time). The isolated driver used the committed scenario/assertions with explicit profiles and retained diagnostics. Gateway startup and a real provider round trip account for the runtime; the cheaper SQLite tests separately cover the estimate boundary.
  • Large-active-context Gateway control passed (47.42 s command wall time).
  • The first hosted run exposed a related incognito admission regression (failing case). A new physical-incognito row in the existing context-reader matrix failed with the same read-fence error before the owner correction. Afterward, all 38 context-reader tests and all 222 reply-agent tests passed, including that admission case (406.24 s combined command wall time; 72.85 s and 257.60 s Vitest durations). The added row itself took 76 ms.
  • Rebuilt after the incognito correction. Two real Gateway turns in the supported incognito session namespace completed with zero provider-usage anchors; the second request retained the first turn, and no incognito SQLite file was created (22.26 s command wall time). An initial smoke setup pointing the global session store directly at the incognito sentinel was rejected before execution; the successful smoke uses the normal incognito route.
  • Both isolated runtime builds passed. Initial E2E wrapper attempts redundantly rebuilt the runtime; those setup attempts were stopped, then the documented prebuilt-runtime mode was used.
  • git diff --check passed.

Compatibility

Read-only selection change: no SQLite schema, serialized row, writer, migration, or retention changes. The persisted-session fixtures use the existing format. This does not require a data-model migration. The legacy read fallback remains intact.

Disclosure: AI assisted with implementation review and validation.

@clawsweeper

clawsweeper Bot commented Sep 17, 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.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 17, 2026
@clawsweeper

clawsweeper Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 1, 2026, 7:04 AM ET / 11:04 UTC (Revision 15).

ClawSweeper review

What this changes

The PR estimates compaction pressure from the active conversation context, preserves legacy transcript reads, and keeps incognito reads with their process-local database owner.

Merge readiness

⛔ Blocked before merge - 1 item remains

This remains a useful fix that current main and the latest release lack. The incognito correction resolves the reported reader regression, and source inspection removes the previous migration-proof blocker; no actionable patch defects remain.

Priority: P1
Reviewed head: 3c8c8d08728dd232ed4ec87a91ad734e84c575ac

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with meaningful baseline/candidate Gateway evidence and no remaining correctness finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Recorded built-runtime Gateway turns exercise the changed preflight owner against persisted compacted sessions: the healthy candidate avoids a second boundary, the oversized control still compacts, and corrected incognito turns retain context without creating a file. Tests supplement those runtime observations. No stored-data contract changes occur, so the previous migration-proof requirement is withdrawn.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Recorded built-runtime Gateway turns exercise the changed preflight owner against persisted compacted sessions: the healthy candidate avoids a second boundary, the oversized control still compacts, and corrected incognito turns retain context without creating a file. Tests supplement those runtime observations. No stored-data contract changes occur, so the previous migration-proof requirement is withdrawn.
Evidence reviewed 9 items Pinned introduced change: Reviewed the merge-base-to-head delta across all seven supplied paths, separately from the final incognito correction. The checkout matches the pinned original head; the stale test merge was not used to infer merge effects.
Canonical context selection: Preflight now consumes the existing asynchronous model-context reader. Headerless legacy projections retain their fallback, excluded display messages are filtered there, and repeated read-fence failures propagate rather than silently becoming an unknown estimate.
Incognito ownership correction: The final commit recognizes the canonical incognito sentinel path as well as incognito session keys. Both use the process-held reader, while cancellation, admission, context-version, and anchor validation remain intact. The existing Gateway history reader already uses this same two-part classification.
Findings None None.
Security None None.

How this fits together

Before an agent replies, OpenClaw estimates conversation size to decide whether compaction is required. The estimate should include the current summary and retained messages rather than conversation history already superseded by compaction.

flowchart TD
  A[Incoming agent turn] --> B[Preflight budget check]
  C[Stored transcript and usage] --> B
  B --> D[Active conversation context]
  D --> E[Token estimate]
  E --> F{Over budget}
  F -->|Yes| G[Compact conversation]
  F -->|No| H[Continue reply]
  G --> H
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +59, Tests +335, Other 0. Total +394 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 3 71 12 +59
Tests 3 338 3 +335
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 7 410 16 +394

Review metrics

None.

Stored data model

Persistent data-model change detected: serialized state: src/auto-reply/reply/agent-runner-memory-transcript-context.ts, unknown-data-model-change: src/auto-reply/reply/agent-runner-memory-transcript-context.ts. Confirm migration or upgrade compatibility proof before merge.

Technical review

Best possible solution:

Use the canonical active-context reader for budget estimates while preserving legacy reads and process-local incognito ownership.

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

Yes: current source exposes the full-history estimate after compaction when usage is stale, and the captured baseline Gateway run records an extra persisted compaction. This read-only review did not execute tests.

Is this the best way to solve the issue?

Yes: reusing the existing active-context owner fixes the estimate without duplicating compaction selection or changing stored data.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P1: The reported false budget compactions interrupt active agent sessions and can delay or refuse inbound messages.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Recorded built-runtime Gateway turns exercise the changed preflight owner against persisted compacted sessions: the healthy candidate avoids a second boundary, the oversized control still compacts, and corrected incognito turns retain context without creating a file. Tests supplement those runtime observations. No stored-data contract changes occur, so the previous migration-proof requirement is withdrawn.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded built-runtime Gateway turns exercise the changed preflight owner against persisted compacted sessions: the healthy candidate avoids a second boundary, the oversized control still compacts, and corrected incognito turns retain context without creating a file. Tests supplement those runtime observations. No stored-data contract changes occur, so the previous migration-proof requirement is withdrawn.

Evidence

What I checked:

  • Pinned introduced change: Reviewed the merge-base-to-head delta across all seven supplied paths, separately from the final incognito correction. The checkout matches the pinned original head; the stale test merge was not used to infer merge effects. (3c8c8d08728d)
  • Canonical context selection: Preflight now consumes the existing asynchronous model-context reader. Headerless legacy projections retain their fallback, excluded display messages are filtered there, and repeated read-fence failures propagate rather than silently becoming an unknown estimate. (src/auto-reply/reply/agent-runner-memory-transcript-context.ts:35, 3c8c8d08728d)
  • Incognito ownership correction: The final commit recognizes the canonical incognito sentinel path as well as incognito session keys. Both use the process-held reader, while cancellation, admission, context-version, and anchor validation remain intact. The existing Gateway history reader already uses this same two-part classification. (src/agents/sessions/session-manager.ts:397, 3c8c8d08728d)
  • Still necessary on current main: Fetched main still reads messages with mode full for the no-provider-usage estimate. The changed path is OpenClaw's own context reader; native Codex token preflight is skipped before this estimate, so no Codex dependency contract is introduced. (src/auto-reply/reply/agent-runner-memory.ts:554, e34e76640d45)
  • Latest release check: REST inspection of v2026.9.7 also finds the full-history preflight estimate. Local release-blob inspection encountered an unavailable-object fetch failure; the GitHub contents read supplied the release source successfully. (src/auto-reply/reply/agent-runner-memory.ts:565, c074824a27c9)
  • Recorded production-boundary proof: The captured body, sourceRevision f2c73a37350e23f28b4656213aa5bd51c1fb7f77678460c8da510c09ec67ce73, records secretless Docker runs through built, authenticated Gateway agent turns and a loopback Anthropic transport. The baseline persisted a second compaction; the healthy candidate retained one boundary and completed its reply; the oversized active-context control still compacted. The latest discussion reports repeating both controls after the incognito correction and completing two incognito turns without a database file. Memory flushing and the reporter's complete draining sequence were explicitly outside this proof. (test/pr150623-active-context-preflight.e2e.test.ts:99, 3c8c8d08728d)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • fuller-stack-dev: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (14 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-27T14:32:17.482Z sha 7db7d9d :: blocked before merge. :: none
  • reviewed 2026-09-27T16:22:08.092Z sha 8b7c49c :: blocked before merge. :: none
  • reviewed 2026-09-27T19:02:45.435Z sha 8beba7c :: blocked before merge. :: none
  • reviewed 2026-09-27T22:01:09.584Z sha 90f7e3b :: blocked before merge. :: none
  • reviewed 2026-09-27T23:04:48.176Z sha 90f7e3b :: blocked before merge. :: none
  • reviewed 2026-09-30T07:25:30.085Z sha 3640c79 :: blocked before merge. :: none
  • reviewed 2026-09-30T07:37:48.735Z sha 3640c79 :: blocked before merge. :: none
  • reviewed 2026-10-01T10:16:45.797Z sha 0fe2675 :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. 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. labels Sep 17, 2026
@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review — exact head 0fe2675. The PR body now includes current-main versus candidate real-Gateway evidence and a large-active-context control. The Gateway regression now catches the actual extra persisted compaction, not merely provider request count. No stored-data contract changes.

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review — exact head 3c8c8d0. Corrected the first CI run’s incognito read-fence regression at the model-context reader owner. The added native-store case fails before and passes after; 38 reader tests and 222 reply-agent tests pass. Rebuilt and repeated both healthy/oversized Gateway scenarios; both pass. Two supported incognito Gateway turns also pass without creating a database file. No stored-data contract changes.

@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Oct 1, 2026
@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator

Maintainer override on head 3c8c8d08728dd232ed4ec87a91ad734e84c575ac. The exact-head review (revision 15) has no findings and only the path-triggered data-model checkbox open. Its own prose says no migration applies: the change only alters how the preflight estimates tokens, with no stored shape change.

Red CI (run 36852448961) is unrelated to this diff:

Proof: a real isolated Gateway, in the PR thread.

  • main: estimated 162,512 tokens and wrote an unnecessary second compaction.
  • This head: estimated 18 tokens and kept a single compaction boundary.
  • Large active context: still estimates high and compacts.
  • Incognito: turns create no database. The physical-incognito reader regression that the first CI run exposed was fixed in this head, with a regression test.

@obviyus
obviyus merged commit 5129c0a into openclaw:main Oct 1, 2026
127 of 134 checks passed
@obviyus

obviyus commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator

Landed as 5129c0a. Thanks @goutamadwant!

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
* fix: estimate compaction pressure from active context

* fix: satisfy memory helper line cap

* test: prove active-context preflight end to end

* fix: document transcript projection assertion

* test: use isolated workspace for preflight proof

* fix: move preflight context reads off gateway thread

* test: use typed excluded activity fixture

* test: detect redundant compaction after a real turn

* fix: retain native incognito ownership during context reads

---------

Co-authored-by: Ayaan Zaidi <[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 P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

2 participants