Repository navigation
perf(state): move session RPC SQL off the Gateway main thread - #155740
Conversation
|
🦞👀 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. Reviewed September 22, 2026, 6:16 PM ET / 22:16 UTC (Revision 13). ClawSweeper reviewWhat this changesMoves durable session history, metadata, and preview reads into existing database workers, with bounded row preparation and coordinated cleanup. Merge readiness⛔ Blocked before merge - 1 item remains Keep open: the SQL offload remains useful and is not superseded by current main. No actionable patch defect was found. The prior migration-proof blocker does not apply because the changed backfill enriches in-memory rows without changing persistent storage contracts. Priority: P2 Review scores
Verification
How this fits togetherThe Gateway serves session history and session-list requests from clients and agent tools. Its session projection combines stored metadata, transcript facts, and current access rules before returning results. flowchart TD
A[Client and agent requests] --> B[Session row projection]
B --> C[Selected row preparation]
C --> D[Existing database workers]
D --> E[SQLite metadata and transcripts]
E --> D
D --> F[Current identity and access checks]
F --> G[Session response]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +682, Tests +526, Docs +17. Total +1225 across 74 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Technical reviewBest possible solution: Use the existing worker and projection owners for durable reads while preserving current access checks, physical-store identity, and host-side presentation policy. Do we have a high-confidence way to reproduce the issue? Not applicable as a functional bug report; source confirms the host-side SQL path, and the PR supplies a focused SQL-counter regression that this read-only review did not execute. Is this the best way to solve the issue? Yes. Reusing the existing read workers and projection invalidation is a coherent solution, without a competing store owner or new persistent contract. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 54655675d54a. 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 (12 earlier review cycles; latest 8 shown)
|
60e9d1a to
25b8284
Compare
a8ae250 to
e1d5492
Compare
Move durable session RPC and row-projection SQL through the existing history and shared-state workers. Preserve raw messages, current authorization, archive ownership, worker custody, and host presentation policy. No schema, stored-data, retention, configuration, or update changes. Integrate main's coalesced placement reads and per-ID freshness. Admit placement work before selected-row preparation; batch exact-row reads by physical store with bounded input, FIFO retries, and two concurrent scopes for independently retained archive pages. Reject queued work on disposal and settle accepted native work before closing SQLite. Join Gateway shutdown and projection disposal in affected test fixtures. The original 41-file CI group reproduced active borrowers before the repair and passed all 575 tests afterward; seven focused suites passed 129 tests. Main's memory repair and advisory-export CI fixes are incorporated unchanged. Testbox: final concurrency/archive/RPC proof passed 30 tests, core typing and focused type-aware lint passed. Earlier full check-changed passed all 25 test graphs, dead-code scans, lint, storage guards, and import cycles. Full-candidate independent autoreview has no actionable P0-P2 findings. No local test suites, typechecks, or builds ran. The previous large-18 sessions.list timeout did not reproduce in the original 25-file group on main or the old PR head (454 tests each); Testbox CPU capacity differs from CI. No timeout or assertion was weakened. Exact-head CI remains the landing gate.
e1d5492 to
2eadae9
Compare
|
Merged via squash.
|
* commit '7d7f977ccfc1ac177526232e4f4960febd010015': (91 commits) test: avoid unused target setup in package profile fixtures (#155972) fix(worktrees): batch snapshot metadata reads test(plugin-state): distinguish borrowed and foreign lifecycle owners refactor(agents): share external harness session and attempt machinery (#152181) chore(i18n): refresh native locales (#156006) chore(test): retain Doctor fixture settlement diagnostics (#155944) perf(codex): reuse unchanged inference request bytes (#155987) perf(test): prepare snapshot ownership subprocess imports (#155973) perf(test): consolidate channel registry coverage (#155014) fix(runtime): preserve Node worker dependencies and cleanup diagnostics (#155292) perf(test): prepare worktree GC child runtime (#155928) fix(ui): open browser cards after delayed panel renders (#153253) fix(update): retain the running updater by hard link instead of copying the package (#155977) feat(decisions): add explicit evaluation and Labs opt-in foundation (#155134) fix(state): preserve lifecycle custody across worker dispatch improve: reuse shared tooling fixtures and defer legacy updater proof (#155731) improve(ui): reduce real-Gateway test preparation (#155979) perf(state): move session RPC SQL off the Gateway main thread (#155740) docs(freebsd): explain native Codex runtime limits (#155980) fix(qa): count Code Mode nested tool activity as transcript tool evidence (#155976) ...
…aw#155740) Move durable session RPC and row-projection SQL through the existing history and shared-state workers. Preserve raw messages, current authorization, archive ownership, worker custody, and host presentation policy. No schema, stored-data, retention, configuration, or update changes. Integrate main's coalesced placement reads and per-ID freshness. Admit placement work before selected-row preparation; batch exact-row reads by physical store with bounded input, FIFO retries, and two concurrent scopes for independently retained archive pages. Reject queued work on disposal and settle accepted native work before closing SQLite. Join Gateway shutdown and projection disposal in affected test fixtures. The original 41-file CI group reproduced active borrowers before the repair and passed all 575 tests afterward; seven focused suites passed 129 tests. Main's memory repair and advisory-export CI fixes are incorporated unchanged. Testbox: final concurrency/archive/RPC proof passed 30 tests, core typing and focused type-aware lint passed. Earlier full check-changed passed all 25 test graphs, dead-code scans, lint, storage guards, and import cycles. Full-candidate independent autoreview has no actionable P0-P2 findings. No local test suites, typechecks, or builds ran. The previous large-18 sessions.list timeout did not reproduce in the original 25-file group on main or the old PR head (454 tests each); Testbox CPU capacity differs from CI. No timeout or assertion was weakened. Exact-head CI remains the landing gate.
Retain ACP metadata and board membership on cold resident rows through the existing worker batch and revision lifecycle. Preserve cold display-row retention, catalog demotion, and lifecycle replacement semantics. A 5,000-session Testbox fixture reduced filterSetup from 811 ms to 371 ms and main-thread read statements from 56,700 to zero with identical results. RPC regression, worker/archival coverage, typechecks, scoped lint, and repository guards validated. Full core lint has two documented, unmodified baseline line-cap violations. Related: #151574, #155740. PR #156665 contains historical measurements, Testbox evidence, and remaining production-attribution limits.
Retain ACP metadata and board membership on cold resident rows through the existing worker batch and revision lifecycle. Preserve cold display-row retention, catalog demotion, and lifecycle replacement semantics. A 5,000-session Testbox fixture reduced filterSetup from 811 ms to 371 ms and main-thread read statements from 56,700 to zero with identical results. RPC regression, worker/archival coverage, typechecks, scoped lint, and repository guards validated. Full core lint has two documented, unmodified baseline line-cap violations. Related: openclaw#151574, openclaw#155740. PR openclaw#156665 contains historical measurements, Testbox evidence, and remaining production-attribution limits.
What Problem This Solves
Session history RPCs and row refreshes still execute SQLite queries on the Gateway event loop after the worker migrations. A synthetic probe counted 1,700 host statement executions for 100 warm
sessions.getcalls and 1,000 for 100 publication-plus-sessions.listcycles.User Impact
Durable session reads and background preview preparation keep database work off the Gateway event loop. Raw history messages, visibility, lifecycle checks, archive behavior, and response formats are preserved. There are no configuration, schema, durability, retention, or update changes.
Why This Change Was Made
Use the existing row projection for session selection and final authorization, and the retained history worker for raw recent messages, selected dirty/archived rows, previews, and terminal fallback facts. Prepare ACP metadata in the existing shared-state reader, carrying explicit absence through materialization. The projection's existing publications and revisions invalidate those facts. Hot reads rely on their atomic cold-storage check and restore only after a cold rejection.
Selected preparation rechecks row and membership readiness after placement waits; it does not wait for unrelated full-row materialization. The archive owner pins selected row identities only for each prepared-read lifetime, so concurrent disjoint pages cannot evict one another; release restores normal bounded eviction. Fixture cleanup joins accepted projection reads before its synchronous database-close assertions. Terminal transcript facts cross the worker boundary; fallback-notice and runtime-alias policy stays with the host owner, without transferring configuration.
Evidence
Baseline
41f119f66004c2944a79e1aaede0bc77dd35c4d2; the latest quantitative counter rerun below was measured atc0533e73e96b1d486123be096863b1ca33e50255. The current integration separately passes the permanent zero-host-SQL regression; the historical dirty-list counts have not been remeasured after the latest main update. One warmed durable-session fixture with an empty transcript; 100 serialized calls/cycles (before → after). Hooks countStatementSync.get/all/run/iterateexecutions on the host, excludingDatabaseSync.exec; these are not individualsqlite3_stepcounts. Dirty-list cycles include the row publication and background work during the cycle.sessions.getsessions.listacp_sessionssession_key_contractconfig_machine_statecontent versionPRAGMA user_versionPRAGMA schema_versionPRAGMA data_versionStatementSyncexecutionsWarm list/describe remain at zero in this fixture. A stronger permanent regression observes host data-database prepares, exec calls, and statement executions across 100 warm gets, 100 dirty gets, 100 dirty describes, and archived get/describe while preserving raw commentary/tool messages. It excludes the captured lifecycle coordinator database and clears publication activity before measuring dirty RPC reads. Participant/member owners are unchanged.
The remaining 300 dirty-list executions occur during publication: 100
PRAGMA user_version, 100 schema-version reads, and 100 exact session-row reads. The earlier pre-integration candidate measured 100; the table reports the final integrated rerun. Savedchat.metadataacquisition, incognito stores, and other legacy synchronous consumers remain separate migration work; this change covers get/describe/list and background row preparation. The unidentified 773-statement sample from the motivating profile was not reproduced or identified, and is excluded from the claimed reduction. CPU samples varied; this PR claims the measured SQL relocation, not a stable end-to-end latency improvement.Validation used Blacksmith Testbox (
openclaw-check); no local test suites, typechecks, or builds ran.Integration and CI repairs
The final candidate incorporates main through
9eec298184e08a6a3612016bca9932e30cbc2459, including #155471's placement batching and per-ID freshness. Placement reads are admitted before asynchronous selected-row preparation. The existing row refresh owner coalesces exact-row work by physical store, deduplicates keys, bounds retained input, and runs two read scopes so independently retained archive pages can both progress. Each batch makes one read attempt; the existing readiness loop requeues stale work at the FIFO tail. Disposal rejects queued work and preserves active native custody until settlement. A later fixture conflict takes main'sobserveGatewayRunExecutionhelper and agent test unchanged, removing this PR's superseded observer. Main's owned-worker cleanup remains intact.The compact-small-15 failure was task-fixture teardown closing shared SQLite while accepted readers still held native borrowers. The fixture now awaits Gateway shutdown before resetting its registry. Seven session-handler suites likewise await their existing projection disposal before restoring mocks and closing shared SQLite. A session-status fixture now awaits
disposeSessionReadContexts(). The repository replay's mid-test reopen uses the existing async close owner and preserves its request-context binding. No assertions, timeouts, retries, or expected-failure baselines were weakened.The memory candidate-repair failure was upstream's polling race; this branch takes main's deterministic synchronization/cancellation fix from #155745 unchanged. The unrelated Knip unused export was reproduced on pure main and resolved upstream by
1619aff4781; no separate dependency fix is included here.Validation
check-changedon immutable9e36564cpassed in 33m42s, including core types, all 25 test graphs, all dead-code scans, scoped lint, formatting, storage guards, and zero runtime import cycles. Testbox run. Later fixture and concurrency deltas have the focused validation above; this earlier full result is not presented as final-head proof.The previous published head
25b82844fbae035bb9d06bf63d0ddb607c9e2abbfailed compact-large-18 onlocal-request-context.session-tools.test.ts(“lists then archives a visible session through built-in tools with roles enabled”):sessions.listexceeded its 10-second RPC deadline. Replaying the captured 25-file group passed 454/454 tests on both immutable pure main5ac833c17248e4b074e0f0aede9ec68724b001b4and the old PR head; the target took 1.730s and 2.521s respectively. Comparison run. Testbox had 16 CPUs versus CI's two, so this does not prove a fix or establish a main reproduction. No code or timeout was changed solely for that unreproduced failure. New exact-head CI and native preparation remain the landing gate.Earlier compact-large-2 auth-counter contention and a Windows Node/libuv worker-shutdown abort remain observed failures without claimed fixes; later changed-head CI passed those jobs. Setup failures (expired lease or transport lockfile mismatch) were corrected before validation using clean immutable checkouts and frozen installs.
Data-model compatibility:
backfillSessionRowTranscriptFieldsreads optional preview/terminal facts into the in-memory projection. It is not a persisted migration or backfill. Read-only worker tests verify unchanged stored metadata, no writer admission, and no creation of absent storage. Schema versions, written bytes, transactions, durability, retention, and update behavior are unchanged.Final-head CI
a8ae250e26f/ run35781939912reported one Discord pacing failure inchecks-node-changed-extensions-bundle-8:audio-worker-pacing.integration.test.ts:95counted 51 encoded packets against 50 source acknowledgements. The voice fixture and executed voice-only dependency path are unchanged by this PR. Existing production code flushes and pads partial Opus frames on underrun, and the existing PCM-underflow test verifies that encoded playback length can exceed source PCM length; the pacing fixture's one-chunk/one-packet assumption is timing-sensitive. This is source evidence for an unrelated fixture issue, not an observed explanation of that specific extra packet.The captured Discord group passed 292 files / 4,107 tests on pure main
8ba18cf19ad11e6171b2fbbb30e536b865f02f91both normally (169.97s, target 2.796s) and pinned to two CPUs with NodeavailableParallelism = 2(179.07s, target 2.932s), Node 24.19.0. Baseline comparison. The exact failure was not reproduced and no fix is claimed. No Discord code or assertions were changed. No CI job rerun was issued; the final workflow snapshot also exposed the separate cleanup defect below, requiring a repaired head.The completed same-head run also failed
checks-node-compact-small-8inserver.sessions.create.test.ts(“reset-in-place reports cleanup truth for a concurrently finalized checkout”): synchronous fixture teardown closed shared SQLite with active native borrowers. On Testbox, the captured 40-file group passed 590/590 on pure main (340.78s) but failed 10/590 on the unpatched PR (433.10s). The latter exposed eight reset-concurrency failures starting at premature shared-state close, a separate archive fixture history-read revocation, and an orphaned-recovery error whose mechanism was not established. Comparison run. This replay used Node24.19.0 and four permitted CPUs with the captured two-worker policy; the failed CI job advertised eight CPUs.The repair follows each actual lifetime owner. Direct-handler fixtures dispose and join their tracked projections before database shutdown; scoped state fixtures then use their existing async cleanup instead of a competing global synchronous close. The archive fixture closes its projection before its deliberate cold-storage read and recreates the context binding with the same worker services. Local Gateway fixtures use an explicit existing resource host instead of the process-lifetime fallback, and the production resource-release callback now awaits the projection's existing materialization drain after disposal. No new cleanup API, persisted-state contract, assertions, or timeouts were introduced. The orphaned-recovery test remains unchanged; it passes in the same-order repaired replay, without an independently established cause or a claimed separate fix. Fresh independent review of this eight-file repair found no actionable P0–P2 findings.
The hash-verified eight-file lifetime repair passed the original 40 files / 590 tests on the same Testbox in 379.78s; the previously failing create-finalized case took 2.639s. The unpatched PR comparison failed 10 tests, and the repaired group clears reset-concurrency, archive cold-reopen, and the unchanged orphaned-recovery case together. Full-index patch SHA256
58c8c4e9c0c3ab8aff7f7cb919b6b4bb85688278e17bd13dfc08208b3cad8f62and all eight source-file hashes were verified before execution. An initial preflight mismatch was solely Git's differing index abbreviation widths; no test ran before canonical source verification succeeded.The six changed lifetime suites also passed 244/244 tests with
pnpm test <six files> --maxWorkers=1: 271.00s Vitest / 273.91s measured wall. This covers the create/delete cleanup blocks, reset authority cases, model-catalog teardown, archive/Undo, and scoped local session tools. The list/archive case took 1.202s; the two failed-worker archive cases took 4.183s and 3.839s.Core typing passed (54.37s), and focused type-aware lint passed on all eight repair files with zero warnings/errors (9.5s). The six-suite run's recorded file durations were create 135.445s, delete/worktree 23.665s, reset-concurrency 4.881s, model-catalog 22.372s, archive/failed-worker 8.176s, and local session-tools 32.043s; combined wall above includes runner/transform overhead. Post-proof source hashes remained unchanged.
The final rebase onto main
9eec298184e08a6a3612016bca9932e30cbc2459applied without conflicts. All 73 PR files retain identical source bytes from the reviewed and validated repair; the incorporated main changes touch separate paths. The branch remains one commit with the original subject.Pre-extraction candidate:
e1d5492dd7b82f8fe6187f1ec39af29bdcc9028d. The post-rebase Testbox reconstructed the complete candidate treed92823310b1cab6e549077fff7cc95cc9702d6cbfrom immutable main plus the 73 hash-verified task files, and verified the same tree after execution. Focused worker RPC, local session tools, and session-ID routing proof passed 22 tests in three files (90.24s wall); core typing passed (74.62s). Rebase proof. All task Testbox leases are stopped. New exact-head CI and native completed-evidence preparation remain the landing gates.The
e1d5492run's remaining compact session-flow shard completed successfully. Its baseline-ratchet job rejected the additional disposal import because the already-oversized create suite grew from 6,971 to 6,972 counted lines. The existing Git-workspace fixture factory now lives unchanged in the already-imported sibling test-support module; its sole caller imports it, and the duplicate local implementation is removed. Coverage, fixture data, assertions, caps, and baselines are unchanged.On Testbox, captured pure main
469c2c75ea639a04d6fc8450df340a834afeb39apassed the line-cap check; unpatchede1d5492reproduced the exact one-line failure. The extraction passed max-lines, line-cap, and assertion-safety gates, the existing worktree provision/reuse case (3.285s test / 48.64s wall), and two-file type-aware lint (zero warnings/errors, 6.2s). Fresh isolated review found no actionable P0–P2 findings. The tested extraction patch SHA256 is1485133f682fd96bb2c72cbab212aa71953ba6b5c82e0751ce5effc938866c42.Published candidate:
2eadae970035771eac914143bd075d46e5c3c307, one commit with the original subject. All scoped source proof is complete and all task Testbox leases are stopped; new exact-head CI and native preparation remain the final landing gates.