Repository navigation
perf(sessions): move compaction reads off the main thread - #165406
Conversation
Prepare durable transcript statistics and compaction entry facts through the existing history and agent readers. Recheck caller authority after awaits, preserve internal writer facts, and retain the released synchronous statistics contract. Manual compaction phase MAIN SQL: 199 to 163; migrated read cohort: 37 to 0.
|
🦞👀 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: needs maintainer review before merge. Reviewed October 5, 2026, 5:38 AM ET / 09:38 UTC (Revision 5). ClawSweeper reviewWhat this changesMove compaction’s session metadata and transcript-statistics reads to existing database workers while preserving synchronous plugin contracts. Merge readiness✅ Ready for maintainer review No blocking introduced defect found. The previously requested build and integration checks are now recorded for the reviewed head, and current main still needs this scheduling improvement. Likely related people: @steipete and @ekinnee, as routing candidates from merged area history. Priority: P2 Review scores
Verification
How this fits togetherCompaction reduces an agent’s conversation history. Gateway requests and automatic agent work prepare session facts, execute compaction, and publish updated transcript and session accounting. flowchart TD
A[Manual or automatic compaction] --> B[Capture session and store]
B --> C[Existing database workers]
C --> D[Session facts and transcript statistics]
D --> E[Recheck current authority]
E --> F[Compaction and guarded commit]
F --> G[Updated history and accounting]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +84, Tests +54, Docs +9, Other 0. Total +147 across 18 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Serve compaction preparation through existing worker owners while retaining physical-store identity, final writer guards, and released synchronous SDK behavior. Do we have a high-confidence way to reproduce the issue? Yes, current-main source directly shows synchronous statistics and entry reads on the compaction path, corroborated by the recorded native statement measurement. This read-only review did not execute the workload. Is this the best way to solve the issue? Yes, reusing existing database executors and readers is a focused cutover that preserves storage semantics, final commit guards, and plugin callability. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 13c1d87f6df4. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (4 earlier review cycles)
|
Integrate the startup observer fixture and Doctor maintenance-authority fixes from main. Preserve the extracted foreground compaction owner and consolidated Gateway errors while retaining worker-backed reads and post-await authority checks.
|
Merged via squash.
|
…65406) * perf(sessions): move compaction reads off the main thread Prepare durable transcript statistics and compaction entry facts through the existing history and agent readers. Recheck caller authority after awaits, preserve internal writer facts, and retain the released synchronous statistics contract. Manual compaction phase MAIN SQL: 199 to 163; migrated read cohort: 37 to 0. * perf(sessions): keep compaction stats private to worker executor
What Problem This Solves
Manual and automatic compaction still read current session metadata and transcript statistics synchronously on the Gateway thread. The measured manual compaction issued 37 main-thread statements through those readers, despite already having worker owners for the underlying stores.
Solution
Use the existing entry readers for Gateway lookup, direct/queued preparation, and successor selection. Read exact hot/cold transcript statistics through a private command on the existing canonical database executor. Capture the physical store before yielding, retain FIFO/resource ownership, and recheck live authority after reads. Existing synchronous transaction predicates and accepted-work settlement stay with their owners.
The stats command does not expand the released history-reader interface or worker request/reply unions. Correct two internal reader declarations to describe the optional internal fields their codec already returns. Keep the released synchronous stats SDK and process-held incognito paths. No new worker service, schema, cache, retention, durability, configuration, or update behavior.
Impact
The migrated reads execute zero caller-thread SQL. This is a focused scheduling improvement, not a claim that the whole compaction phase is free of main-thread SQL or that total SQL/latency decreased. Production diff: +140 / −56 / net +84 (196 changed production lines); 18 files overall. No new
OPENCLAW_*names.Evidence
Before/after measurement
Unchanged synthetic sqlmeasure workload and observer, Node 24.21.0. Before: fresh-main
e76032fbab8d02b3d8c360db01440e732ee79a0d; measured candidate:13dd217b618469dc690167773f438c0d546463b2. Original review/gate base:a37950a0b4a05d15887f2b038479f6796f9e40bc, incorporating the intervening main import-cycle repair. Caller attribution uses bundle source-region markers and function stacks; bundle line numbers are not presented as source line numbers. Counts are successful native SQL statement executions, excluding prepare calls.The final run completed 139 existing background memory-reindex statements during compaction that the before run executed during shutdown. Across both intervals, Memory has the same 314 statements and identical SQL multiset. This timing effect is retained in the raw counts rather than excluded as an exemption.
Both runs: 13/13 turns succeeded, child turn succeeded, scheduled cron completed,
sessions.compact.compacted=true, shutdown[0,null], and zero SQL errors in the compaction interval. Persisted compaction summary, token accounting, and details match; fresh transcript IDs differ. All located disk databases stayed inside the synthetic fixture. No latency or RSS improvement is claimed.Adjacent real-entry probes needed no cutover: activity-summary
handleTranscriptand its compaction background refresh had 0 MAIN SQL (130 worker statements for the refresh; watermark advanced 4→5). Real durable transcript rewrite had 0 MAIN SQL, with 12 preparation and 78 commit worker statements, preserved prefix, and identical live/reopened views.Validation
pnpm test <files> --maxWorkers=1, 1,241.61s command wall on the loaded Mac. Covers Gateway compaction (20), read-error behavior (6), readers (19), delegate cancellation (9), runtime build graph/get-reply imports (11), wrapper import closure (17), and history imports (2).compact.auth-preparation.test.tsinto the host-owned project; run its six tests and indirect caller suites with one worker. Re-audit the private stats dispatch's callers; they are already host-owned. Runtime-process build-graph and import-closure gates passed.node scripts/check-changed.mjs --staged --base a37950a0b4a05d15887f2b038479f6796f9e40bc: passed, 4,144.21s command wall (including build/artifact-lock waits).qaRuntime) passed, 497.5s command wall, including all 14 postbuild phases. The original full-build attempts were incomplete because of local generation and remote infrastructure failures. Full package/declaration qualification for the integrated candidate is now complete, as recorded below; the earlier runtime build remains separate evidence.76e85c03: no entrypoint or direct exported-signature changes; 128 reachable hashes change only through the two reader imports changingSessionEntrytoInternalSessionEntry. Existing fields remain and the added internal fields are optional; no service changes sync/async behavior or requires new inputs.The first final-validation attempt hit a host Homebrew Node 26
simdjsonloader failure; Node 24 rerun passed the affected checks. An earlier WebSocket timeout in the unchanged Gateway ordering test passed on Linux; the full final Gateway file also passed above.Earlier individual Linux test command wall times
All commands used
pnpm test <file> --maxWorkers=1.server.sessions.compaction.test.tssession-transcript-readers.test.tscompact.auth-preparation.test.tscompact.queued-successor.test.tscompaction-successor.test.tscompaction-successor.lifetime.test.tscompact.hooks.test.tscompact.delegate.test.ts(fixture failure, corrected above)compact.foreground-resources.test.tscompact.queued-resources.test.tsrun.overflow-compaction.test.tssession-history-read.imports.test.tsRemaining debt and overlap
Memory's serving-path first-use initialization and reindex remain main-thread work; they are not blanket classified as boot-only. Placement and sandbox classification remain separate owners. The pre-existing native capability authority read at
src/agents/embedded-agent-runner/compact.queued-execution.ts:612stays synchronous to revalidate its live writer immediately before native use; it is outside the moved-reader boundary. Released compatibility is evidenced byv2026.9.8:src/plugin-sdk/session-store-runtime.ts:444. Activity-summary service signatures are indirectly released through Gateway context and remain unchanged.Overlap acknowledged: #165028, #165205, #165193, #165129, #162433; replysnap/readamp/sqlmeasure4, the incognito P7 lanes, and the other phase lanes. Activity-summary push delivery from #165024 is preserved. Hunks remain scoped; no other PR branch was changed.
Landing validation
Current candidate:
22a9e74a788320d34e152e6ed4f62af23b83c365, merging main689bda012dae1fd39862098df4e3393590be89c5without rebasing. The two conflicts preserve the foreground compaction owner and consolidated Gateway error handling from #165413 while retaining the worker reads and post-await authority checks. The SQL measurements above remain observations of the original measured candidate; they were not rerun for this integration commit.The original CI run had three failing jobs. The startup-observer fixture type error and Doctor requester-authority maintenance refusal were independently reproduced in scheduled main CI; the candidate incorporates their fixes,
e78e965a55e2and689bda012dae. The PR-context heading failure was corrected in the body and its replacement check passed. The new exact-head CI run passed, includingopenclaw/ci-gateandsecurity-fast; no inherited-failure admin exception is needed for that run.The health account-inspection suite failed before its cases with an
EnvironmentTeardownError. Its import graph reaches the accessor barrel, so attribution was investigated rather than assumed unrelated. Replaying the original 10-file shard order on the original PR head passed 137/137 tests, 1693.11s Vitest wall. Five individual runs on merge baseline689bda012daealso passed 2/2 tests each; command walls were 259.39, 143.56, 163.80, 138.14, and 169.25s. These Node 24.21.0 Mac runs did not reproduce the error and do not establish a fix; the loaded host differed substantially from Linux CI timing. All five merged-head comparisons finished: 4 passed, 1 failed, with command walls 290.76, 175.80, 116.66, 79.00, and 80.67s. None reproduced the original teardown error. The second run instead reported missingstateReasonin the unknown-configuration case. That case took 8.2s against the unchanged collector’s 7s deadline; its timeout record omitsstateReason, but the returned snapshot was not captured, so timeout attribution remains unproven. This separate local failure is retained, not relabeled as fixed by passing replays.Fresh isolated Codex autoreview through P2 is scoped-clean for the integrated candidate. Conflict-file formatting and
git diff --checkpassed. The routing/SDK audit found no additional host-owner registration gap or released signature change. The published-driver selector does not apply to this PR's own paths.Full package/declaration build and new-base focused tests passed on
22a9e74a788320d34e152e6ed4f62af23b83c365. A fresh Hetzner checkout with Node 24.21.0 and pnpm 12.5.1 ranCI=1 OPENCLAW_RUN_NODE_SKIP_DTS_BUILD=0 pnpm build: exit 0, 823s command wall, all 17 phases, full package/unified/SDK declarations, and 151 SDK subpath checks. The groupedpnpm test <10 files> --maxWorkers=1run passed 115/115 tests across 10 files, 439s command wall / 437.74s runner wall. It covers foreground resources, delegate cancellation, auth preparation, real successor handling, Gateway compaction/read errors, transcript readers, runtime build graph, get-reply imports, and eager wrapper closure. The local full build was stopped after 1258.33s while still generating package declarations; it is incomplete evidence. The initial remote wrapper was cancelled before allocation while preparing its source capsule; no source was uploaded or lease allocated. An AWS quota fallback supplied a runner below the build’s memory floor (206 MB derived heap versus 4,352 MB minimum); its guard refused before compilation and the lease was released. The Hetzner gates above completed successfully, and both cloud leases are verified released. The wrapper reported a post-run artifact-staging ENOENT after the successful remote command; complete gate output was retained and inspected, and the passing gates were not rerun. ClawSweeper completed its exact-head review with no actionable code or security findings; its outstanding full-build request is now satisfied.