Skip to content

perf(sessions): move compaction reads off the main thread - #165406

Merged
steipete merged 3 commits into
mainfrom
dbasync/compactsql
Oct 5, 2026
Merged

steipete merged 3 commits into
mainfrom
dbasync/compactsql

Conversation

@steipete

@steipete steipete commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

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.

Compaction MAIN caller cohort, ranked by before count Before Final
Memory manager initialization/indexing 154 293
Gateway initial/current session reads 11 0
Transcript statistics 10 0
Successor current-row read 9 0
Direct/queued entry preparation 7 0
Placement 5 5
Sandbox classification 3 6
Raw compaction MAIN total 199 304
Moved reader cohort MAIN 37 0

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.

Raw phase accounting Before Final
Shutdown MAIN 403 267
Compaction + shutdown MAIN 602 571
Compaction worker-thread statements 580 766
Compaction helper-process statements 30 30
Compaction all-thread/process statements 809 1,100
Compaction + shutdown all-thread/process statements 3,154 3,217

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 handleTranscript and 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

  • Final focused run: 8 files / 84 tests passed, 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).
  • Native statement observer proves zero caller-thread SQL for stats/manual preflight and freshness after a later append. It demonstrably failed with the original synchronous preflight. Final regression: 8.538s; corrected hydration-abort boundary: 4.529s. The fixture now pauses the actual hydration request, preserving all no-publication assertions after the new earlier entry read.
  • Earlier Linux/Testbox scoped proof on the prior candidate: 206 passed / 1 fixture failure, 354.46s aggregate command wall/remote test seconds. The fixture failure is fixed and green above. Unchanged successor, hooks, resource-lifetime, auth-preparation, and overflow inputs retain that proof. The new reader case took 0.339s there. Testbox run.
  • Worker-cutover importer audit: route compact.auth-preparation.test.ts into 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).
  • Madge: 0 cycles, 77.38s. Database-worker ratchet passed against the pinned base; no T1 call-count growth. Environment-name ratchet passed, 473/473.
  • Runtime build (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.
  • SDK comparator passed, 1,491.07s. Digest 76e85c03: no entrypoint or direct exported-signature changes; 128 reachable hashes change only through the two reader imports changing SessionEntry to InternalSessionEntry. Existing fields remain and the added internal fields are optional; no service changes sync/async behavior or requires new inputs.
  • Fresh isolated Codex autoreview through P2, ultrafast, pinned base: scoped-clean, no accepted/actionable findings.

The first final-validation attempt hit a host Homebrew Node 26 simdjson loader 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.

File Wall seconds
server.sessions.compaction.test.ts 53.20
session-transcript-readers.test.ts 28.16
compact.auth-preparation.test.ts 29.45
compact.queued-successor.test.ts 33.30
compaction-successor.test.ts 35.77
compaction-successor.lifetime.test.ts 20.75
compact.hooks.test.ts 42.59
compact.delegate.test.ts (fixture failure, corrected above) 32.57
compact.foreground-resources.test.ts 27.90
compact.queued-resources.test.ts 21.95
run.overflow-compaction.test.ts 25.02
session-history-read.imports.test.ts 3.80

Remaining 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:612 stays synchronous to revalidate its live writer immediately before native use; it is outside the moved-reader boundary. Released compatibility is evidenced by v2026.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 main 689bda012dae1fd39862098df4e3393590be89c5 without 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, e78e965a55e2 and 689bda012dae. The PR-context heading failure was corrected in the body and its replacement check passed. The new exact-head CI run passed, including openclaw/ci-gate and security-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 baseline 689bda012dae also 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 missing stateReason in the unknown-configuration case. That case took 8.2s against the unchanged collector’s 7s deadline; its timeout record omits stateReason, 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 --check passed. 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 ran CI=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 grouped pnpm test <10 files> --maxWorkers=1 run 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.

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

clawsweeper Bot commented Oct 5, 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 docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: M labels Oct 5, 2026
@clawsweeper clawsweeper Bot added 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 5, 2026
@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 5, 2026, 5:38 AM ET / 09:38 UTC (Revision 5).

ClawSweeper review

What this changes

Move 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
Reviewed head: 22a9e74a788320d34e152e6ed4f62af23b83c365

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, well-supported worker cutover with the prior validation request satisfied and no blocking findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Recorded production Gateway compaction with real SQLite owners demonstrates zero caller-thread SQL for the migrated readers and matching persisted results on 13dd217. Exact-head integration coverage and the full package build qualify the subsequent merge resolution. No stored-data contract changes require migration proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Recorded production Gateway compaction with real SQLite owners demonstrates zero caller-thread SQL for the migrated readers and matching persisted results on 13dd217. Exact-head integration coverage and the full package build qualify the subsequent merge resolution. No stored-data contract changes require migration proof.
Evidence reviewed 11 items Pinned introduction reviewed: Reviewed the complete introduced delta from the pinned base to the actual PR head. The stale GitHub test merge was not used to infer what merging would remove.
Existing executor and statistics kernel: The new adapter retains the captured physical source, uses the canonical database executor, and rechecks currentness after execution. Its worker calls the existing hot/cold statistics kernel; no schema or serialized format changes are introduced.
Successor authority remains transaction guarded: Successor preparation rechecks caller authority after the worker read. The final patch still compares the exact writer claim inside its update callback and retains the live pre-commit assertion.
Findings None None.
Security None None.

How this fits together

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

Before merge

None.

Agent review details

Security

None.

PR surface

Source +84, Tests +54, Docs +9, Other 0. Total +147 across 18 files.

View PR surface stats
Area Files Added Removed Net
Source 10 140 56 +84
Tests 5 78 24 +54
Docs 1 9 0 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 2 1 1 0
Total 18 228 81 +147

Review metrics

Metric Value Why it matters
Measured read scheduling Migrated caller-thread SQL: 37 → 0 on the measured candidate The evidence establishes the intended scheduling change without claiming lower total SQL or latency.
Production and test growth Production +140/−56; tests +77/−24 Production growth is explained by private worker dispatch and currentness checks that preserve the released reader interface.

Technical review

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded runtime scheduling improvement with demonstrated compaction behavior and no urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Recorded production Gateway compaction with real SQLite owners demonstrates zero caller-thread SQL for the migrated readers and matching persisted results on 13dd217. Exact-head integration coverage and the full package build qualify the subsequent merge resolution. No stored-data contract changes require migration proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded production Gateway compaction with real SQLite owners demonstrates zero caller-thread SQL for the migrated readers and matching persisted results on 13dd217. Exact-head integration coverage and the full package build qualify the subsequent merge resolution. No stored-data contract changes require migration proof.

Evidence

What I checked:

  • Pinned introduction reviewed: Reviewed the complete introduced delta from the pinned base to the actual PR head. The stale GitHub test merge was not used to infer what merging would remove. (22a9e74a7883)
  • Existing executor and statistics kernel: The new adapter retains the captured physical source, uses the canonical database executor, and rechecks currentness after execution. Its worker calls the existing hot/cold statistics kernel; no schema or serialized format changes are introduced. (src/config/sessions/session-transcript-stats.ts:13, 22a9e74a7883)
  • Successor authority remains transaction guarded: Successor preparation rechecks caller authority after the worker read. The final patch still compares the exact writer claim inside its update callback and retains the live pre-commit assertion. (src/agents/embedded-agent-runner/compaction-successor.ts:224, 22a9e74a7883)
  • Current main still has the synchronous path: Fetched main still imports and calls synchronous transcript statistics and performs synchronous current-entry lookup. The merged compaction refactor at refactor(compaction): deslop compaction #165413 is incorporated but does not implement this worker-read cutover. (src/gateway/server-methods/sessions-compact.ts:162, 13c1d87f6df4)
  • Released synchronous SDK preserved: GitHub’s v2026.9.8 source exposes synchronous readTranscriptStatsSync; the reviewed checkout retains that contract. The new command stays private, and the two reader declaration corrections add only already-returned optional internal fields. (src/plugin-sdk/session-store-runtime.ts:444, fc23bc864e45)
  • Complete captured body recovered: Read the full GitHub body, including the omitted validation tail, and verified its SHA-256 matches the captured source: f16f999359d695992657d678117dbee17cdb1b4aaf69bf9c993d057c61604c6c, 12,802 UTF-16 units. It records a full package/declaration build passing in 823 seconds and 115/115 focused tests passing in 439 seconds on the exact reviewed head, satisfying the prior rank-up request. (22a9e74a7883)

Likely related people:

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

Rating scale

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

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

Workflow

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

History

Review history (4 earlier review cycles)
  • reviewed 2026-10-05T07:10:06.991Z sha 13dd217 :: needs changes before merge. :: none
  • reviewed 2026-10-05T07:18:39.672Z sha 13dd217 :: needs changes before merge. :: none
  • reviewed 2026-10-05T08:34:31.721Z sha 22a9e74 :: needs changes before merge. :: none
  • reviewed 2026-10-05T09:03:24.389Z sha 22a9e74 :: needs changes before merge. :: none

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.
@steipete
steipete merged commit 4f05baa into main Oct 5, 2026
193 checks passed
@steipete
steipete deleted the dbasync/compactsql branch October 5, 2026 10:00
@steipete

steipete commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 6, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation 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: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant