Repository navigation
fix: compact long-lived sessions without holding their whole history in Gateway memory - #201304
Conversation
…ive window on the main thread Refs #195361
…arity Checkpoint the verified throughput and policy repairs plus narrow cold imports. Retain deterministic request-body comparison and workload evidence. The cold 8/40 MiB performance acceptance gate remains unmet; this is not the completed cold-cost repair.
Move borrowed projection and pure replay decisions out of host/bootstrap imports, preserving public adapters and identity owners. Load the existing image backend only for admitted image work. Extend the existing worker census with prepared/render import inventories and owner-boundary guards. The prescribed cold campaign passes every <20% median/p95 wall/CPU gate: five interleaved pairs at 8/40 MiB, two at 575 MiB. Small cold wall medians remain +7.7%/+5.9%; 575 MiB improves 48.4% wall and 63.3% CPU. Six-request native parity and 341 affected tests pass. Independent source review found no P0-P2 findings.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: blocked before merge. What this changesThis PR plans compaction from payload-free transcript facts and reads selected rows in workers instead of retaining the complete active history in Gateway memory. Example: Compacting a 575 MB active session while its summary model responds slowly.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 1 item remains Keep open: this PR addresses a demonstrated Gateway memory problem, and both previous findings are fixed; exact-head CI still has unresolved failures. Priority: P2 Before merge
FindingsNone. Agent review detailsHow this fits togetherCompaction sits between persisted session transcripts and model inference, producing bounded summary requests and committing a summary boundary with retained conversation context. flowchart LR
A[Session transcript] --> B[Reader worker]
B --> C[Payload-free compaction plan]
C --> D[Selected-row renderer]
D --> E[Gateway summary request]
E --> F[Model response]
F --> G[Worker finalization]
G --> H[Existing transcript writer]
Technical reviewBest possible solution: Keep the existing compaction policies and writer authority shared while holding only transcript facts and selected payloads across summary inference. Do we have a high-confidence way to reproduce the issue? The reproduction in #195361 matches current main's complete-history fallback, and the PR supplies corresponding Gateway measurements; this read-only review ran no reproduction. Is this the best way to solve the issue? The selected-row design addresses the retainer directly, shares decision kernels with array callers, and preserves full-history adapters for existing callback contracts. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against b413b8e19667. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
PR surfacePR surface statistics unavailable: the file list is incomplete. Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed November 18, 2026, 3:01 PM ET / 20:01 UTC (Revision 2). |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
…in Gateway memory (openclaw#201304) * refactor(compaction): share payload-free planning kernels * refactor: collect range-local compaction facts during transcript reads * refactor: share reset retention over compaction pairing facts * refactor(compaction): share preparation and render selected rows lazily * fix(compaction): compact large sessions without materializing the active window on the main thread Refs openclaw#195361 * fix(compaction): reduce preparation work and preserve native policy parity Checkpoint the verified throughput and policy repairs plus narrow cold imports. Retain deterministic request-body comparison and workload evidence. The cold 8/40 MiB performance acceptance gate remains unmet; this is not the completed cold-cost repair. * perf(compaction): isolate read-only projection and replay owners Move borrowed projection and pure replay decisions out of host/bootstrap imports, preserving public adapters and identity owners. Load the existing image backend only for admitted image work. Extend the existing worker census with prepared/render import inventories and owner-boundary guards. The prescribed cold campaign passes every <20% median/p95 wall/CPU gate: five interleaved pairs at 8/40 MiB, two at 575 MiB. Small cold wall medians remain +7.7%/+5.9%; 575 MiB improves 48.4% wall and 63.3% CPU. Six-request native parity and 341 affected tests pass. Independent source review found no P0-P2 findings. * fix(compaction): repair replay scans and committed accounting * fix(compaction): restore replay checks and wrapper closure
…stage 2) Catches the pure continuation candidate bc7e568 up to openclaw/openclaw main 41bdde2 (fetched 2026-11-19T14:32:59Z), 2,996 upstream commits past the old merge base 401a1de. Merge commit only; rerere disabled, so every resolution was made here. 80 conflicted paths (77 content, 3 modify/delete), each recorded with base, ours and theirs blobs and its reason in the lane's stage2-conflicts.md: - 8 take upstream whole: the openclaw#197153 pg16-smoke cherry-pick (6909b64) now ships upstream (ci.yml, ci-build-manifest, ci-workflow-planning test), the Control UI settings child moved onto runDistArtifactChild, the canary worker target and two active-facts migration tests. - 3 deleted with upstream: session-fork and update-candidate-canary suites whose production paths upstream removed; cwd-split folded away (openclaw#198916), its one continuation case rehomed to attempt.continuation-tools.test.ts. - One-owner cutovers where upstream now owns a fork extraction: the requester-origin projection and replacement-text helpers (openclaw#200533) replace the fork's byte-identical copies in user-turn-transcript.metadata.ts. - Ports into fork-extracted owners: removalReason in the queued-start plan and collector-group sweep (openclaw#199868), the async prepared-pricing usage diagnostic, the announce flow types, and the session-delivery codec, which gains upstream's mediaCandidate kind, reviewedTaskId and their schemas (openclaw#198227), importing its retention type from the leaf types module. - Transcript repair (openclaw#201304, post-b894): upstream's payload-free adapter kernel carries the fork's continue_delegate attachment redaction through a payload-adapter-only fact and a withBlock update. - Reset cleanup: upstream's process and retained-send stops (openclaw#199079, openclaw#200326) with the fork's continuation-aware reason as the single input; the chat reset's retention adapter wraps upstream's stopSessionResetWork, the Gateway preemption keeps stopSessionResetSubagents as upstream does. - Schema: upstream owns agent 42 (tool usage) and 43 (pending-input endings) and is at 43; 44 is unused upstream. Continuation's recipient authority moves 42 -> 44: version constants, step order, historical schemas, witness additive table and version set, backup scope, PostgreSQL ladder (V43 = current minus the authority table) and port descriptor. package.json schemaVersions state 40, agent 44. - Generated outputs regenerated, never hand-merged: config baseline, gateway validators, postgres schema catalogs, worker-access inventory. - Compile follow-through for upstream's delivery-union narrowing and its readSessionDelivery callers. Refs openclaw#129388
…in Gateway memory (#201304) * refactor(compaction): share payload-free planning kernels * refactor: collect range-local compaction facts during transcript reads * refactor: share reset retention over compaction pairing facts * refactor(compaction): share preparation and render selected rows lazily * fix(compaction): compact large sessions without materializing the active window on the main thread Refs #195361 * fix(compaction): reduce preparation work and preserve native policy parity Checkpoint the verified throughput and policy repairs plus narrow cold imports. Retain deterministic request-body comparison and workload evidence. The cold 8/40 MiB performance acceptance gate remains unmet; this is not the completed cold-cost repair. * perf(compaction): isolate read-only projection and replay owners Move borrowed projection and pure replay decisions out of host/bootstrap imports, preserving public adapters and identity owners. Load the existing image backend only for admitted image work. Extend the existing worker census with prepared/render import inventories and owner-boundary guards. The prescribed cold campaign passes every <20% median/p95 wall/CPU gate: five interleaved pairs at 8/40 MiB, two at 575 MiB. Small cold wall medians remain +7.7%/+5.9%; 575 MiB improves 48.4% wall and 63.3% CPU. Six-request native parity and 341 affected tests pass. Independent source review found no P0-P2 findings. * fix(compaction): repair replay scans and committed accounting * fix(compaction): restore replay checks and wrapper closure (cherry picked from commit 777fc99) Release adaptation: keep retired session-identity allowlist deleted; omit unused source-context hook imports absent from this baseline while retaining new diagnostic stream and transport owners. Companion review: no later PR-number references at pinned main. Full companion audit and targeted compaction proof recorded in lane evidence. Co-authored-by: RomneyDa <[email protected]> (cherry picked from commit e6d8e935d6570a933596920898b1ba8e46c75c41)
* fix(ci): retire unused compaction export surfaces * fix(ci): complete compaction fixture export cleanup (cherry picked from commit bf7681d) Release adaptation: omit unrelated new-session UI test-helper cleanup. Retain source compaction stream test, absent on the release baseline, at its canonical owner boundary. Follow-up disposition: paired with #201304; no additional runtime policy changes. Co-authored-by: RomneyDa <[email protected]> (cherry picked from commit a115b897eb7bcba23496edc40b73d5b8b9a8640a)
Prepare persisted compaction from bounded worker facts before opening a SessionManager, preserving native safeguards, replay metadata, lifecycle streams, concurrent appends, and accounting. Keep actor-backed incognito sessions on their canonical adapter, including unprepared callers. Prove native compaction and a resumed real-model turn with durable results. Extract fixture accounting and context-engine mocks into their existing owners without dropping coverage or increasing grandfathered line debt. Source: 777fc99 (openclaw#201304) Co-authored-by: RomneyDa <[email protected]> (cherry picked from commit f78a701a6e226f844106dab05349a47598e7a4dd)
## What Problem This Solves
After a compaction, the Control UI chat shows two "Context compacted" dividers: one with the saved-token metric, and a second bare one below it. This happens for every compaction that runs through the prepared compaction path: `/compact` from the Control UI (`sessions.compact`) and recovery compactions (overflow, budget, timeout).
## User Impact
New compactions render one divider, with its "saved … tokens" metric. Sessions that already have an affected compaction keep the extra bare divider only until the live compaction status clears (reload, session switch, or the status timeout); stored transcript rows are not rewritten.
## Why This Change Was Made
The UI hides its live compaction divider when the persisted compaction entry carries the same `{runId, itemId}` that its progress events announced. Since #201304, the prepared compaction path persisted only `itemId` and dropped `runId`, so the UI never matched the two and rendered both. The prepared path now persists `{ runId, itemId }` from the same run id and diag id that its callers use for progress events (recovery: the run id and `diagId`; `sessions.compact`: the operation id). The UI matcher is unchanged.
## Evidence
- Regression test through the real queued compaction, native session, and SQLite transcript (`compact.summary-fallback.test.ts`, recovery and `sessions.compact` preflight cases): the persisted entry's `__openclaw` equals the caller's `{runId, itemId}`. Red on base (`[{ itemId: "cmp-…" }]`, no `runId`), green on head.
- UI contract test (`chat-thread-live-final.test.ts`): a persisted marker plus a matching complete compaction status renders exactly one divider with the metric.
- Control UI E2E against a real built Gateway, real agent, and a local OpenAI-compatible fixture provider: three turns, then `/compact` typed in the composer.
- Base: two dividers; `chat.history` marker has `itemId` only.
- Head: one divider with "saved 3.9k tokens (67.5%)"; marker has `runId` and `itemId`.
Before (base):

After (head):

Merge danger: two-way door. A revert restores the old entry shape; no schema, protocol, or stored-row change. Blast radius: new compaction entries written by the prepared path gain a `runId` field already defined on `CompactionEntry["__openclaw"]` and already projected by `chat.history`.
Co-authored-by: Ayaan Zaidi <[email protected]>
…#204029) ## What Problem This Solves After a compaction, the Control UI chat shows two "Context compacted" dividers: one with the saved-token metric, and a second bare one below it. This happens for every compaction that runs through the prepared compaction path: `/compact` from the Control UI (`sessions.compact`) and recovery compactions (overflow, budget, timeout). ## User Impact New compactions render one divider, with its "saved … tokens" metric. Sessions that already have an affected compaction keep the extra bare divider only until the live compaction status clears (reload, session switch, or the status timeout); stored transcript rows are not rewritten. ## Why This Change Was Made The UI hides its live compaction divider when the persisted compaction entry carries the same `{runId, itemId}` that its progress events announced. Since openclaw#201304, the prepared compaction path persisted only `itemId` and dropped `runId`, so the UI never matched the two and rendered both. The prepared path now persists `{ runId, itemId }` from the same run id and diag id that its callers use for progress events (recovery: the run id and `diagId`; `sessions.compact`: the operation id). The UI matcher is unchanged. ## Evidence - Regression test through the real queued compaction, native session, and SQLite transcript (`compact.summary-fallback.test.ts`, recovery and `sessions.compact` preflight cases): the persisted entry's `__openclaw` equals the caller's `{runId, itemId}`. Red on base (`[{ itemId: "cmp-…" }]`, no `runId`), green on head. - UI contract test (`chat-thread-live-final.test.ts`): a persisted marker plus a matching complete compaction status renders exactly one divider with the metric. - Control UI E2E against a real built Gateway, real agent, and a local OpenAI-compatible fixture provider: three turns, then `/compact` typed in the composer. - Base: two dividers; `chat.history` marker has `itemId` only. - Head: one divider with "saved 3.9k tokens (67.5%)"; marker has `runId` and `itemId`. Before (base):  After (head):  Merge danger: two-way door. A revert restores the old entry shape; no schema, protocol, or stored-row change. Blast radius: new compaction entries written by the prepared path gain a `runId` field already defined on `CompactionEntry["__openclaw"]` and already projected by `chat.history`. Co-authored-by: Ayaan Zaidi <[email protected]>
Root cause: `src/config/sessions/session-transcript-worker-readers.ts:366-372` (on main) charged compaction-preparation requests as `JSON.stringify(input).length * 2` and passed no request options, so a manual plan carrying Gateway preflight facts was refused by the history pool's 256 MiB pending-bytes cap (`packages/worker-runtime/src/worker-task-capacity.ts:2`), and every preparation read fell back to the 60 s default in `session-transcript-worker-runtime.ts:183`. Fixes #205752 Thanks @jredbeard for the report, the root-cause trace and this fix. ## What Problem This Solves Since 2026.11.10 (#201304), long-running sessions with a lot of history (the report: a Slack channel session at ~835k tokens, ~415 MB since the last compaction, ~1,460 images) can't be compacted. Manual `openclaw sessions compact` fails with `worker task capacity reached [... pool pending bytes ... inputBytes=445943294]`, and budget compaction can fail with `worker task timed out` after 60 s on every turn on slower hosts. ## Why This Change Was Made 1. **Manual path, refused for size.** The Gateway preflight returns per-entry compaction facts for the whole active window and the plan request sends them back to the history worker (so planning does not extract the window twice). The reader charged that request as UTF-16 JSON: about 4.7x the structured clone that actually crosses the thread boundary, and it built a string as large as the window on the Gateway thread. `readPreparedCompaction` now charges the request by its `v8.serialize` byte length, the serializer the worker transport uses. The facts still travel and are still charged; the 256 MiB cap is unchanged and still refuses genuinely oversized requests. 2. **Preparation deadline.** Preflight, plan, render and finalize reads used the 60 s default worker read deadline regardless of `agents.defaults.compaction.timeoutSeconds`. The Gateway runner and the embedded compaction owner now pass the existing `resolveCompactionTimeoutMs(config)` (default 180 s) to those reads, the way `readTrajectoryRetention` already takes a caller-owned `timeoutMs`. Caller abort signals still apply. No config, schema or stored-data changes. ## Evidence Built Gateway, merge base vs this head, seeded session the size of the report (37,801 events, 413.7 MB transcript, 1,500 distinct base64 PNG tool results): #205783 (comment) - Manual: main refused twice (`worker task capacity reached ... inputBytes=828669298`, 7 s); this head compacted twice in 15 s (21,870,587 -> 20,708 tokens). - Preflight facts measured 174 MB as a structured clone vs 828 MB charged before. A plan with twice those facts (349 MB) is still refused with the same capacity error on this head; on main the JSON estimate throws `RangeError: Invalid string length` first. - Budget path: at the report's size preparation took ~8 s on this host on both main and this head, so the 60 s timeout did not reproduce here. The timeout change is covered by the integration regression in `compact.summary-fallback.test.ts` (red on main, green here). - Small session: unchanged on both (10,926 -> 1,140 tokens). - Regressions: `session-transcript-worker-readers.test.ts` (plan facts charged at least their clone and under the old estimate) and `compact.summary-fallback.test.ts` (`timeoutSeconds: 600` reaches every preparation read), both red on main. Production +18/-2, tests +103 against the merge base. ## Merge danger Two-way door: a revert restores the old charge and the 60 s deadline; nothing is written or migrated. Blast radius: compaction-preparation reads only (Gateway manual compaction and embedded compaction). Co-authored-by: Ayaan Zaidi <[email protected]>
Root cause: `src/config/sessions/session-transcript-worker-readers.ts:366-372` (on main) charged compaction-preparation requests as `JSON.stringify(input).length * 2` and passed no request options, so a manual plan carrying Gateway preflight facts was refused by the history pool's 256 MiB pending-bytes cap (`packages/worker-runtime/src/worker-task-capacity.ts:2`), and every preparation read fell back to the 60 s default in `session-transcript-worker-runtime.ts:183`. Fixes #205752 Thanks @jredbeard for the report, the root-cause trace and this fix. ## What Problem This Solves Since 2026.11.10 (#201304), long-running sessions with a lot of history (the report: a Slack channel session at ~835k tokens, ~415 MB since the last compaction, ~1,460 images) can't be compacted. Manual `openclaw sessions compact` fails with `worker task capacity reached [... pool pending bytes ... inputBytes=445943294]`, and budget compaction can fail with `worker task timed out` after 60 s on every turn on slower hosts. ## Why This Change Was Made 1. **Manual path, refused for size.** The Gateway preflight returns per-entry compaction facts for the whole active window and the plan request sends them back to the history worker (so planning does not extract the window twice). The reader charged that request as UTF-16 JSON: about 4.7x the structured clone that actually crosses the thread boundary, and it built a string as large as the window on the Gateway thread. `readPreparedCompaction` now charges the request by its `v8.serialize` byte length, the serializer the worker transport uses. The facts still travel and are still charged; the 256 MiB cap is unchanged and still refuses genuinely oversized requests. 2. **Preparation deadline.** Preflight, plan, render and finalize reads used the 60 s default worker read deadline regardless of `agents.defaults.compaction.timeoutSeconds`. The Gateway runner and the embedded compaction owner now pass the existing `resolveCompactionTimeoutMs(config)` (default 180 s) to those reads, the way `readTrajectoryRetention` already takes a caller-owned `timeoutMs`. Caller abort signals still apply. No config, schema or stored-data changes. ## Evidence Built Gateway, merge base vs this head, seeded session the size of the report (37,801 events, 413.7 MB transcript, 1,500 distinct base64 PNG tool results): #205783 (comment) - Manual: main refused twice (`worker task capacity reached ... inputBytes=828669298`, 7 s); this head compacted twice in 15 s (21,870,587 -> 20,708 tokens). - Preflight facts measured 174 MB as a structured clone vs 828 MB charged before. A plan with twice those facts (349 MB) is still refused with the same capacity error on this head; on main the JSON estimate throws `RangeError: Invalid string length` first. - Budget path: at the report's size preparation took ~8 s on this host on both main and this head, so the 60 s timeout did not reproduce here. The timeout change is covered by the integration regression in `compact.summary-fallback.test.ts` (red on main, green here). - Small session: unchanged on both (10,926 -> 1,140 tokens). - Regressions: `session-transcript-worker-readers.test.ts` (plan facts charged at least their clone and under the old estimate) and `compact.summary-fallback.test.ts` (`timeoutSeconds: 600` reaches every preparation read), both red on main. Production +18/-2, tests +103 against the merge base. ## Merge danger Two-way door: a revert restores the old charge and the 60 s deadline; nothing is written or migrated. Blast radius: compaction-preparation reads only (Gateway manual compaction and embedded compaction). Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit ec31b90) Release adaptation: Git merged the Gateway import hunk into the release layout cleanly; no production or test behavior was adapted. Co-authored-by: vincentkoc <[email protected]> Co-authored-by: RomneyDa <[email protected]>
Root cause: `src/config/sessions/session-transcript-worker-readers.ts:366-372` (on main) charged compaction-preparation requests as `JSON.stringify(input).length * 2` and passed no request options, so a manual plan carrying Gateway preflight facts was refused by the history pool's 256 MiB pending-bytes cap (`packages/worker-runtime/src/worker-task-capacity.ts:2`), and every preparation read fell back to the 60 s default in `session-transcript-worker-runtime.ts:183`. Fixes openclaw#205752 Thanks @jredbeard for the report, the root-cause trace and this fix. ## What Problem This Solves Since 2026.11.10 (openclaw#201304), long-running sessions with a lot of history (the report: a Slack channel session at ~835k tokens, ~415 MB since the last compaction, ~1,460 images) can't be compacted. Manual `openclaw sessions compact` fails with `worker task capacity reached [... pool pending bytes ... inputBytes=445943294]`, and budget compaction can fail with `worker task timed out` after 60 s on every turn on slower hosts. ## Why This Change Was Made 1. **Manual path, refused for size.** The Gateway preflight returns per-entry compaction facts for the whole active window and the plan request sends them back to the history worker (so planning does not extract the window twice). The reader charged that request as UTF-16 JSON: about 4.7x the structured clone that actually crosses the thread boundary, and it built a string as large as the window on the Gateway thread. `readPreparedCompaction` now charges the request by its `v8.serialize` byte length, the serializer the worker transport uses. The facts still travel and are still charged; the 256 MiB cap is unchanged and still refuses genuinely oversized requests. 2. **Preparation deadline.** Preflight, plan, render and finalize reads used the 60 s default worker read deadline regardless of `agents.defaults.compaction.timeoutSeconds`. The Gateway runner and the embedded compaction owner now pass the existing `resolveCompactionTimeoutMs(config)` (default 180 s) to those reads, the way `readTrajectoryRetention` already takes a caller-owned `timeoutMs`. Caller abort signals still apply. No config, schema or stored-data changes. ## Evidence Built Gateway, merge base vs this head, seeded session the size of the report (37,801 events, 413.7 MB transcript, 1,500 distinct base64 PNG tool results): openclaw#205783 (comment) - Manual: main refused twice (`worker task capacity reached ... inputBytes=828669298`, 7 s); this head compacted twice in 15 s (21,870,587 -> 20,708 tokens). - Preflight facts measured 174 MB as a structured clone vs 828 MB charged before. A plan with twice those facts (349 MB) is still refused with the same capacity error on this head; on main the JSON estimate throws `RangeError: Invalid string length` first. - Budget path: at the report's size preparation took ~8 s on this host on both main and this head, so the 60 s timeout did not reproduce here. The timeout change is covered by the integration regression in `compact.summary-fallback.test.ts` (red on main, green here). - Small session: unchanged on both (10,926 -> 1,140 tokens). - Regressions: `session-transcript-worker-readers.test.ts` (plan facts charged at least their clone and under the old estimate) and `compact.summary-fallback.test.ts` (`timeoutSeconds: 600` reaches every preparation read), both red on main. Production +18/-2, tests +103 against the merge base. ## Merge danger Two-way door: a revert restores the old charge and the 60 s deadline; nothing is written or migrated. Blast radius: compaction-preparation reads only (Gateway manual compaction and embedded compaction). Co-authored-by: Ayaan Zaidi <[email protected]>
Root cause: `src/config/sessions/session-transcript-worker-readers.ts:366-372` (on main) charged compaction-preparation requests as `JSON.stringify(input).length * 2` and passed no request options, so a manual plan carrying Gateway preflight facts was refused by the history pool's 256 MiB pending-bytes cap (`packages/worker-runtime/src/worker-task-capacity.ts:2`), and every preparation read fell back to the 60 s default in `session-transcript-worker-runtime.ts:183`. Fixes #205752 Thanks @jredbeard for the report, the root-cause trace and this fix. ## What Problem This Solves Since 2026.11.10 (#201304), long-running sessions with a lot of history (the report: a Slack channel session at ~835k tokens, ~415 MB since the last compaction, ~1,460 images) can't be compacted. Manual `openclaw sessions compact` fails with `worker task capacity reached [... pool pending bytes ... inputBytes=445943294]`, and budget compaction can fail with `worker task timed out` after 60 s on every turn on slower hosts. ## Why This Change Was Made 1. **Manual path, refused for size.** The Gateway preflight returns per-entry compaction facts for the whole active window and the plan request sends them back to the history worker (so planning does not extract the window twice). The reader charged that request as UTF-16 JSON: about 4.7x the structured clone that actually crosses the thread boundary, and it built a string as large as the window on the Gateway thread. `readPreparedCompaction` now charges the request by its `v8.serialize` byte length, the serializer the worker transport uses. The facts still travel and are still charged; the 256 MiB cap is unchanged and still refuses genuinely oversized requests. 2. **Preparation deadline.** Preflight, plan, render and finalize reads used the 60 s default worker read deadline regardless of `agents.defaults.compaction.timeoutSeconds`. The Gateway runner and the embedded compaction owner now pass the existing `resolveCompactionTimeoutMs(config)` (default 180 s) to those reads, the way `readTrajectoryRetention` already takes a caller-owned `timeoutMs`. Caller abort signals still apply. No config, schema or stored-data changes. ## Evidence Built Gateway, merge base vs this head, seeded session the size of the report (37,801 events, 413.7 MB transcript, 1,500 distinct base64 PNG tool results): #205783 (comment) - Manual: main refused twice (`worker task capacity reached ... inputBytes=828669298`, 7 s); this head compacted twice in 15 s (21,870,587 -> 20,708 tokens). - Preflight facts measured 174 MB as a structured clone vs 828 MB charged before. A plan with twice those facts (349 MB) is still refused with the same capacity error on this head; on main the JSON estimate throws `RangeError: Invalid string length` first. - Budget path: at the report's size preparation took ~8 s on this host on both main and this head, so the 60 s timeout did not reproduce here. The timeout change is covered by the integration regression in `compact.summary-fallback.test.ts` (red on main, green here). - Small session: unchanged on both (10,926 -> 1,140 tokens). - Regressions: `session-transcript-worker-readers.test.ts` (plan facts charged at least their clone and under the old estimate) and `compact.summary-fallback.test.ts` (`timeoutSeconds: 600` reaches every preparation read), both red on main. Production +18/-2, tests +103 against the merge base. ## Merge danger Two-way door: a revert restores the old charge and the 60 s deadline; nothing is written or migrated. Blast radius: compaction-preparation reads only (Gateway manual compaction and embedded compaction). Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit ec31b90)
Closes #195361
What Problem This Solves
When OpenClaw compacts a long-lived session, the Gateway loads the session's whole active history onto its main thread and holds it there while the summary model runs, which can take minutes. A 575 MB session raised the Gateway's main-thread heap by about 700 MiB for every compaction (about 1 GB in the original production report). The cost grew with the session's lifetime, not with what was being summarized.
User Impact
Large-session compaction now uses about one tenth of the extra main-thread memory and finishes about twice as fast. Summaries, the kept context and what gets persisted are unchanged; on the reproduction, every summary request is byte-identical to
main. Small sessions compact about 6–9% (70–85 ms) slower on their first compaction after a worker starts. No configuration, schema or migration changes.Why This Change Was Made
Compaction only needs a few facts about each entry (id, parent, role, token estimate, tool-call pairing, file and safeguard facts) to choose the cut point, plus the actual text of the roughly 160 KB it sends to the summary model and of the context it keeps. Before, it built a full
SessionManagerfor the whole window to get those. Now a worker reads the window once, keeps only those facts, and rereads just the selected rows to render the summary input and to finalize. The main thread never holds the window, and no worker slot or read snapshot stays open while the model runs.To keep behavior exact, cut selection, serialization sampling, safeguard facts, sanitized-replay metrics and gating (including the bundled Google replay callbacks), tool pairing and reported metrics each still have a single implementation. The existing array APIs now call the same shared kernels the new view uses. Public callbacks that genuinely receive the full mutable history (session SDK extensions, custom compaction providers, custom provider replay callbacks) still get it, through an explicit full-materialization adapter that's chosen before they're invoked. The last commit splits the read-only projection and pure replay code out of their host owners, so the worker loads 93 modules instead of 495; that's what keeps small-session cold compaction within about 8% of
main.This is a large diff (roughly +5.6k production and +3.1k test lines net). The growth is the shared fact kernels plus their array adapters, the selected-row renderer and finalizer, and the owner split; the old private prepared-session adopter, the 16 MiB preparation cap and the full-array planner are removed. An earlier approach to this problem (#196550) was reverted by #199561 for cold-session regressions; this change was measured against that concern specifically (see below).
Evidence
Live Gateway reproduction from #195361 on a Mac Studio, in a Linux container (
node:24.22.1-trixie, 8 CPUs, 24 GB), using the issue's own scripts: safeguard compaction with a slow summary model,maxActiveTranscriptBytes: 2mb, triggered by an ordinary agent turn. Base is the merge basee25ad96f; the candidate is this branch,d2aef106. Both versions got the same deterministic seed, ran in the same paths, and ran in 3 interleaved rounds. Main-threadheapUsed, MiB, median (range):SessionManagerwhosebyIdreaches 581 MB (the whole window); with this PR, noSessionManagerand a 251 MB heap whose large strings are all source code.status: ok.Cold-session performance (the #199561 concern). Isolated real Gateway, cold worker per sample, compaction wall/CPU, interleaved pairs:
After the rebase, a 2-pair spot check per size against
e25ad96fgave 8 MiB +8.6% wall and 40 MiB +8.3% wall, both under the 20% gate. On the Studio, full turns with a fast summary model (5 pairs each) were within ±7% on wall time and process CPU, and main-thread CPU was 4–8% lower.Tests
test/gateway-compaction-residency.e2e.test.ts, release-only inventory) fails on base (held-heap slope 0.97 bytes per source byte) and passes on this branch (0.006), with zero removed-payload hydration on the main thread.tokensAftersanity check). Both are fixed with regressions that fail on base. A fresh review ofd2aef106found no P0–P2 issues.Gaps
cli-compaction.ts) still opens a full manager to estimate context. It's out of scope here and a follow-up.mainand this branch,openclaw doctor --session-sqlite importof one deterministic 575 MB seed reliably reportssqlite_transcript_count_mismatch(22,272 vs 22,273 events). That's a separate import bug, and it now has a reproducible input.Reproduction
The issue's scripts, with small adaptations: a deterministic seed so both versions get identical transcripts, an archive case, per-worker heap sampling, CPU sampling, request-body capture, and a shared run directory. Five interleaved rounds were run for the cold-performance numbers. Memory rounds use
SLOW_MS=60000; performance rounds useSLOW_MS=250. Basee25ad96fb3d62c9934f4be4797b1a5e4cbcb4fc3, candidated2aef106aa68b927658c29534e741bbd90b5e6ce, container imagesha256:f1e034976f948cf212ef1f659c12e5dd58ac7eab947831813e81a62401ca38be.🦞 Made with OpenClaw