Skip to content

fix: compact long-lived sessions without holding their whole history in Gateway memory - #201304

Merged
jalehman merged 9 commits into
mainfrom
fix/compaction-view
Nov 18, 2026
Merged

jalehman merged 9 commits into
mainfrom
fix/compaction-view

Conversation

@jalehman

Copy link
Copy Markdown
Contributor

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 SessionManager for 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 base e25ad96f; 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-thread heapUsed, MiB, median (range):

session base: before → peak this PR: before → peak peak RSS base → PR
575 MB, 22,273 events, all active 213 → 912 (912–921) 213 → 290 (289–319) 2794 → 2308
50 MB, 1,943 events 212 → 366 (359–387) 213 → 336 (335–336) 2238 → 2158
570 MB archive + 5 MB active 212 → 315 213 → 308 2155 → 2154
  • A heap snapshot taken mid-summary on the 575 MB session: on base, one SessionManager whose byId reaches 581 MB (the whole window); with this PR, no SessionManager and a 251 MB heap whose large strings are all source code.
  • Correctness: across all 20 base/PR request pairs (memory rounds, snapshots and performance rounds), every summary request is byte-identical. The follow-up turn requests are identical after normalizing install paths and the wall-clock line in the system prompt.
  • All 40 runs compacted with 4 summary calls and finished status: ok.
  • Trade-off: the largest single worker heap is about 290 MiB (was 112), because the one extraction pass now runs in a worker. That's under the unchanged 512 MiB worker limit.

Cold-session performance (the #199561 concern). Isolated real Gateway, cold worker per sample, compaction wall/CPU, interleaved pairs:

size wall Δ median / p95 CPU Δ median / p95
8 MiB (5 pairs) +7.7% / +8.7% +4.5% / −34.1%
40 MiB (5 pairs) +5.9% / +6.6% −23.5% / −10.1%
575 MiB (2 pairs) −48.4% / −48.0% −63.3% / −63.3%

After the rebase, a 2-pair spot check per size against e25ad96f gave 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

  • A new real-Gateway residency regression (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.
  • Differential checks against the original array implementation: over 100k comparisons over cut points, rendered summary text at several budgets, safeguard facts, replay metrics and gating, plus 6/6 end-to-end request-body parity.
  • 577 tests across 37 files pass after the rebase. Core typecheck, typed lint, format and the worker import budgets pass.
  • Two independent reviews: the first found two P2s (native preparation used the wrong summary policy, which changed the cut; native completion skipped the tokensAfter sanity check). Both are fixed with regressions that fail on base. A fresh review of d2aef106 found no P0–P2 issues.

Gaps

  • Synthetic sessions and a local mock model only; no real-model summary-quality run.
  • Small sessions still pay about 70–85 ms on the first compaction after a reader worker starts.
  • CLI-backend pressure estimation (cli-compaction.ts) still opens a full manager to estimate context. It's out of scope here and a follow-up.
  • Side finding, not fixed here: on both main and this branch, openclaw doctor --session-sqlite import of one deterministic 575 MB seed reliably reports sqlite_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 use SLOW_MS=250. Base e25ad96fb3d62c9934f4be4797b1a5e4cbcb4fc3, candidate d2aef106aa68b927658c29534e741bbd90b5e6ce, container image sha256:f1e034976f948cf212ef1f659c12e5dd58ac7eab947831813e81a62401ca38be.

🦞 Made with OpenClaw

…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.
@clawsweeper

clawsweeper Bot commented Nov 18, 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 gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: XL labels Nov 18, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 18, 2026
@clawsweeper

clawsweeper Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This 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.

  • Before: Reported median Gateway main-thread heap rises from 213 MiB to 912 MiB.
  • After: Reported median heap rises from 213 MiB to 290 MiB, with byte-identical summary requests.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Strong Gateway residency evidence and both earlier findings repaired; current CI failures remain unattributed and uncleared.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied isolated-Gateway campaign exercises actual compaction with a slow local HTTP model, records reduced main-thread residency and completed follow-up turns, and compares summary requests against the base; subsequent repairs address replay scans and accounting without replacing that measured path.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Compacting a long-lived active session holds hundreds of megabytes of transcript payloads in Gateway memory while the summary model runs.
Reason: The demonstrated memory reduction has clear value, and the maintainer-authored proposal explicitly measures and acknowledges its small cold-session cost.

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
Reviewed head: 20fc57203f7d267e0c6a1de5af0b4a568fa2ddf0

Before merge

  • Resolve review confidence - ClawSweeper must reach high confidence before merge readiness is known.

Findings

None.

Agent review details

How this fits together

Compaction 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]
Loading

Technical review

Best 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

  • Worker preparation and complete-history fallback changes intended behavior with a stated reason (472cd0a: Move eligible preparation off the Gateway thread while preserving full input for unsupported or oversized windows.)
  • Cold-session compaction execution changes intended behavior with a stated reason (a4cc2ad: Restore in-process compaction after the earlier worker implementation regressed cold-session CPU and latency.)
  • Signed-turn attachment scanning keeps the original intent (6f266b9: Scan attachment presence once per signed turn while preserving bytes, identities, and complete sibling-result requirements.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

PR surface statistics unavailable: the file list is incomplete.

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.

Root-cause cluster

Relationship: same_root_cause
Canonical: #195361
Summary: This PR repairs the large-active-window Gateway residency tracked by the linked issue; earlier worker preparation and worker-OOM work did not eliminate that retainer.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status no longer selects a status label.

Label justifications:

  • P2: Large active sessions incur substantial transient Gateway memory pressure, while the reported reproduction completes its turns.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 (1 earlier review cycle)
  • reviewed 2026-11-18T15:48:17.420Z sha d2aef10 :: needs changes before merge. :: [P2] Preserve once-per-turn attachment fact collection | [P2] Remove the unused replay pass from finalization

Reviewed November 18, 2026, 3:01 PM ET / 20:01 UTC (Revision 2).

@jalehman

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed 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 Nov 18, 2026
@jalehman
jalehman enabled auto-merge (squash) November 18, 2026 21:20
@jalehman
jalehman merged commit 777fc99 into main Nov 18, 2026
282 of 289 checks passed
@jalehman
jalehman deleted the fix/compaction-view branch November 18, 2026 22:25
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 19, 2026
…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
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 19, 2026
…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
RomneyDa pushed a commit that referenced this pull request Nov 19, 2026
…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)
RomneyDa added a commit that referenced this pull request Nov 19, 2026
* 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)
github-actions Bot pushed a commit to clawhaven/openclaw that referenced this pull request Nov 23, 2026
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)
obviyus added a commit that referenced this pull request Nov 23, 2026
## 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):

![Before: two Context compacted dividers](https://github.com/user-attachments/assets/bf6e542f-ec29-4d3d-af8a-512151ccfa20)

After (head):

![After: one Context compacted divider with metric](https://github.com/user-attachments/assets/63bb297e-f190-41ed-8cce-cf30b1768c63)

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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 24, 2026
…#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):

![Before: two Context compacted dividers](https://github.com/user-attachments/assets/bf6e542f-ec29-4d3d-af8a-512151ccfa20)

After (head):

![After: one Context compacted divider with metric](https://github.com/user-attachments/assets/63bb297e-f190-41ed-8cce-cf30b1768c63)

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]>
obviyus added a commit that referenced this pull request Nov 26, 2026
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]>
tideclaw-bot pushed a commit that referenced this pull request Nov 26, 2026
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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 27, 2026
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]>
tideclaw-bot pushed a commit that referenced this pull request Nov 28, 2026
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Compaction parses a session's entire transcript onto the main thread, so a long-lived session lifts the gateway heap by about 1 GB on every compaction

1 participant