Repository navigation
perf(pairing): run channel mutations in the SQLite worker - #167239
Conversation
Keep adapter preparation outside SQL, reread the exact request before approval, and retain live transaction and commit grants. Preserve normalized account scope and update changed rows without rewriting the channel snapshot. Keep the released synchronous allowlist reader isolated. Also fix removal of legacy whitespace-padded allow entries, with a failing-then-passing owner regression. Runtime statement budgets and package/update proof remain pending before publication.
Route the real Telegram pairing writer test through the existing fork-based database-worker project, preserving the broker host boundary. Resolve the worker cutover lint findings without changing SQL or mutation behavior.
|
🦞👀 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 8, 2026, 1:33 PM ET / 17:33 UTC (Revision 2). ClawSweeper reviewWhat this changesMoves channel pairing mutations into the existing SQLite worker, updates only changed rows, and propagates validated native SQLite capability facts. Example: Remove sender foreign from account alpha
Review scores
ProductKind: Performance · Worth it: Yes Merge readiness✅ Ready for maintainer review This PR remains useful and review-ready: current main still has the central performance problem, the supplied runtime evidence covers the change, and no actionable introduced defect was found. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherChannel pairing stores pending requests and approved senders in shared SQLite state. The Gateway and CLI submit account-scoped operations, and the storage owner returns requests, approval results, and updated allowlists. flowchart TD
A[Gateway or CLI pairing request] --> B[Capture store and caller authority]
B --> C[Existing SQLite worker]
C --> D[Prepare channel approval on host]
D --> E[Reread selected request]
C --> E
E --> F[Check transaction and commit authority]
F --> G[Write changed rows and return result]
Technical reviewBest possible solution: Keep pairing mutations with the existing shared-state worker while preserving channel policy, released SDK behavior, and acknowledged write settlement. Do we have a high-confidence way to reproduce the issue? Yes: current-main source performs pairing mutations synchronously, and the supplied matched runtime measurements establish their Gateway-thread SQL cost; the padded-entry removal regression is also reported failing before the fix. Is this the best way to solve the issue? Yes: the patch uses the existing storage and transport owners, preserves approval policy and public operations, and replaces snapshot rewrites with bounded differential writes. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 56c033e8267a. Provenance checked
TestingProof path: shipped entry point. Added test files: 8. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +479, Tests +578, Docs +14, Other +4. Total +1075 across 27 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
…67239) * refactor(pairing): move channel mutations to the shared-state worker Keep adapter preparation outside SQL, reread the exact request before approval, and retain live transaction and commit grants. Preserve normalized account scope and update changed rows without rewriting the channel snapshot. Keep the released synchronous allowlist reader isolated. Also fix removal of legacy whitespace-padded allow entries, with a failing-then-passing owner regression. Runtime statement budgets and package/update proof remain pending before publication. * fix(pairing): align worker transport and test ownership Route the real Telegram pairing writer test through the existing fork-based database-worker project, preserving the broker host boundary. Resolve the worker cutover lint findings without changing SQL or mutation behavior. * perf(pairing): remove redundant approval preparation queries * style(pairing): normalize supervision fixture formatting * fix(pairing): preserve worker admission and committed results * test(pairing): cover worker custody in CLI and registration fixtures
What Problem This Solves
Channel pairing APIs returned promises while still executing their SQLite mutations on the Gateway thread. Each request refresh, prune, approval, or allowlist edit also replaced the entire channel snapshot, including unchanged accounts and entries.
User Impact
Pairing mutations use the existing shared-state SQLite worker. Removing an approval now also matches legacy whitespace-padded entries by their canonical sender ID. The released synchronous allowlist reader remains supported and reads only its own table.
There are no schema, durability, retention, configuration, or permission-policy changes, and no new migration is required.
Why This Change Was Made
One semantic worker operation retains the captured physical store and writer ordering. Preparation reads requests through existing read-only admission. The transaction reads requests and allowlist rows in one statement; a fresh no-match result with nothing to prune retains native write admission and final host authority without an empty transaction. Channel-specific approval callbacks prepare their result on the host outside SQL; the worker then rereads the exact selected request before consuming it and adding an approval. Live host authority is checked at transaction entry and immediately before commit. The commit grant linearizes the accepted mutation: a later revocation cannot turn its committed result into a reported failure. Unknown write outcomes are not replayed.
The writer preserves canonical account normalization, request expiry/caps, code uniqueness, approval burn behavior, and allowlist ordering. It compares authoritative rows with the normalized result and writes only changed rows, with bounded batches. Doctor keeps its existing offline snapshot migration; the obsolete runtime full-state reader is removed.
The existing SQLite worker also returns its completed native capability fact on one successful reply. The native runtime owner validates process/library identity and the current WAL safety floor before making that fact available to later sibling workers. This avoids an extra first-reader probe without another request, caller-thread SQL, or any change to reader permissions; malformed hints never replace an accepted write outcome.
Production TypeScript grows by 479 net lines (857 added, 378 removed). The added worker owns differential writes and the approval preparation/reselection handshake; the host facade and shared pure model replace the former monolithic runtime path. Native capability propagation adds 66 net production lines in the existing admission/transport owner; removing the post-commit rejection simplifies the facade. Tests, routing, documentation, and inventory accounting comprise the remaining changes.
Evidence
Comparison base:
2095264a927102e6ff70b68afd3c1477861e7249; candidate:56c5ba4072a3ecc7ba8b046ef244b10360dfb41e. A conflict in the database-worker test-routing list required integrating this base; the resolution retains both sets of consumers. The final diff contains 22 lane files.node scripts/database-worker-inventory.mjs --jsonreports repository T1 799 → 790 and pairing T1 10 → 1. The remaining site serves the released synchronous allowlist reader. Static site retirement is separate from runtime statement savings.Measurements use one AWS
c7a.2xlargehost ineu-west-1, Linux x64, Node 24.21.0, and SQLite 3.53.4. Base and candidate have separate exact-commit checkouts, runtime builds, and isolated state. Frozen pnpm installs share immutable dependency files through supported hardlinks; all 253 workspace dependency links per side resolve to their own checkout. The final benchmark runtimes were built with the canonicalqaRuntimeprofile and source maps, then checked against HEAD, build-info, file hashes, and all nine compiled pairing entrypoints.The shared workload and statement counter are unchanged from the campaign harness (
run.mtsSHA-2561de5109a7b89eaf8c10ef943bde724a89bd44772b7d70419bd344caf18d92cd1). The task-owned observer adds request/authority/timestamp attribution. Counts below retain scheduled maintenance, and all ranges are medians [min–max]. Database requests and native authority requests are summed within each run before taking the median; continuation frames and settlement notices are reported separately.Direct pairing owner
Three alternating base/candidate pairs completed. Each counted operation includes its predefined one-second settling window; background SQL remains in the totals. These are instrumented execution-count measurements. The full fixture includes the listed operations, four request seeds, one seed read, foreign-row aging, and cleanup. All six native/census/CSV joins reconcile exactly; failed native executions, fork IPC requests, and continuation frames are zero.
All migrated mutation operations execute zero MAIN SQL. The two candidate MAIN statements in the complete fixture belong to its symmetric raw foreign-row aging setup. Actual SQL falls 1825 → 1770 (−55); moving SQL to a worker is accounted for separately.
The request cost is explicit: 21 mutation commands + one actor open + one close add 23 database requests. Live authority adds 19 transaction grants + 21 commit grants + two host-approval preparations + two schema-maintenance preparations. Baseline checks ran in-process. The unchanged async reader remains one request. Separately, settlement notifications are 0 → 21 and other observed controls are 1 → 2 per fixture; those controls are not counted as additional database operations.
The host-empty approval is 10 → 10 for operation SQL and 10 → 11 including settling: the extra statement is
PRAGMA wal_checkpoint(PASSIVE)from the unchanged WAL scheduler. The same timer also contributes one statement to allow-remove settling. No database or authority request is sent in either settling window. The timer retains its original actor-open context; it is not a second approval command. The +1 phase increase uses the documented non-turn tolerance, with all raw work retained.For visibility into cold handoff cost, API-only instrumented time is 0.385 [0.369–0.387] → 1.037 [1.034–1.044] seconds. The counted operation-plus-settle duration ratio is 1.470503, below 1.5; all other numbered operation windows are below 1.008.
Shared workload
Three alternating base/candidate pairs completed all 13 top-level turns, the native child, control RPCs, cron, committed compaction, and graceful shutdown. All six runs exited 0 with no remaining fixture children or failed native SQL executions. Host idle admission was 99.875–100%. The warmed gate uses the median of each run’s ten-turn mean, as specified by the shared harness; individual turn rows remain visible.
Fork IPC request counts are zero throughout. Other transport observations, shown separately from request sends:
Gate disposition: first-turn +16 / 3540 = 0.452% and warmed +0.5 / 1349.7 = 0.037% pass the documented ≤0.5% noise allowance after the untouched-owner attribution below. MAIN is unchanged. The warmed combined request median is unchanged at 485.6 per turn (301.6 database + 184 authority). Channel-pairing mutation requests are absent from this workload; no shared-turn saving is credited to this PR. Native runtime capability probes are six per complete run on both sides, at most one per process. Separate WAL-policy version queries remain counted.
Attribution uses the actual median-SQL runs: first M3/C1, warmed M3/C2, second-session M1/C2. The native event sequence is joined exactly to the corresponding process/thread census; request medians above are computed independently and are not reconstructed by summing category medians.
The cron boundary is directly witnessed: M3 process 12808/worker 5 executes request 49 during connect,
1791462895984–1791462896002ms; first-turn starts at1791462896004. C1 process 12266/worker 5 executes the same request type at1791462706761–1791462706877; first-turn starts at1791462706756. Its 13 successful statements move with the request. SQL events are bounded by timestamped request/phase events; no unrecorded per-statement timestamp is invented.The five extra snapshot statements are a second
table_info(agent_databases),table_info(session_watch_cursors),sqlite_masterlookup for operator approvals, config-machine-state read, and watcher-cursor read. Warmed row reads occur on worker 9, shared projection reads on worker 7; the extra shared read’s stack reacheswithSessionRowDatabaseFacts → refreshBatch → drain. The paired queued history read retains its transport stack rather than an invented missing upstream frame. These business/scheduler/reader paths are unchanged from the base; the modified native-capability path introduces no extra capability probe or channel mutation request.Second-session +10 uses the non-turn tolerance: row facts +10, shared facts +1, transcript anchors +2, message presence +1, mentions +1, offset by auth rows −2, entry preparation −2, and domain publication −1. These are unchanged projection/read/cache owners. Connect’s −13 is the cron relocation, and shutdown’s −1 is unchanged maintenance timing; neither is counted as a PR saving.
Adjacent-window sums remain visible for context; the first/warmed gate above uses the noise rule, not a combined-window waiver:
Statement attribution
Every changed statement class is included below, including replacement writes and additional freshness/maintenance work. Group counts are summed within each full fixture before taking medians.
The UNION replaces two authoritative table reads. Differential DML replaces full-channel rewrites while retaining foreign rows and canonical account ordering. Fresh host-side absence can avoid two empty transactions after current native admission and the final grant. The existing private worker connection owns its busy-timeout/WAL policy, avoiding temporary policy save/restore work. Three additional freshness observations are retained for correctness; two periodic checkpoints remain counted. Native runtime capability probes are one per process on both sides: propagation prevents a regression and earns no probe-saving credit.
Regressions cover foreign commits/account aliases and scoped rows (read fusion/differential DML), expiry/caps/code reuse and collision handling, native supervision plus revoked transaction/commit grants (including missing approvals), callback metadata/selection/expiry races, null/error burns, accepted-write settlement, and current native-library/WAL-floor validation. The released synchronous reader stays separate.
Validation on the final implementation:
CI=1 node scripts/check-changed.mjs --base 2095264a927102e6ff70b68afd3c1477861e7249 --timed: passed on the committed candidate in 1,307.46 s, including all ratchets, formatting, production and all 27 core-test typecheck graphs, three zero-entry export scans, lint, and authorization/ownership guards. An earlier invocation during the pending merge selected the old merge-base and unrelated upstream changes; it is superseded by this correctly scoped run.pnpm check:madge-import-cycles: zero cycles;pnpm deadcode:knip: passed on the merged candidate.The legacy padded-entry removal regression failed before the bounded owner fix (
changed: false, entry retained), then passed. The accepted-approval regression also failed before removing the facade's post-commit rejection, then passed while the transaction/commit revocation tests continued passing. Other owner tests protect physical store capture, FIFO, foreign rows and account aliases, native supervision for selected and missing requests, adapter errors/null burns, and metadata/selection/expiry races. Native admission tests preserve current WAL safety and process/library matching; invalid hints cannot alter a completed database outcome.The canonical SDK diff completed successfully for the exact base and candidate (619.14 s, exit 0; digest
6ba670aa2ebb20018561a34a726269cab75bfeed1bf8e5a18e2efaceef3f491b). It reports 131 reachable-type closure changes across 24 entrypoints, zero entrypoints added/removed, and zero visible export declarations or signatures changed. Its sole detailed declaration delta is the optional internal successful-reply fieldnativeRuntimeAdmission?: unknownonSqliteWorkerReply.Compatibility disposition: this is an additive, backward-compatible internal transport change. Existing replies without the field remain valid; the broker validates and consumes the optional metadata without exposing it as a domain result. No public operation, required parameter, authority, trust, or persistence contract changes. The diff is explicitly acknowledged here as
hasChanges: true. An additional proof-wrapper assertion expecting an empty diff exited 1; that overstrict expectation is recorded, not represented as a canonical SDK failure or an empty API diff.Remote proof used Blacksmith Testbox lease
tbx_01m4dfbzs1barcdz9q0d3kz25h(run), pinned to the exact base and candidate above. Package build/validation and both canonicalqaRuntimebuilds passed. The published 2026.9.8 driver × candidate update cell passed: run75259e00-032e-4f0d-87ef-b4b3ccb22086finished, readiness returned 200, the service PID changed, and the running server reported the exact candidate build ID2026.9.8-56c5ba4072a3-2026-10-08T10-04-07.212Z. The identity probe was scope-limited but included the server build identity; installed-file equality alone was not used as running-version proof.The focused Doctor discovery test passed on both revisions at its unchanged 120-second timeout: base test 14.019 s / command 46.64 s, candidate test 19.078 s / command 64.62 s. Both runtime archives were verified against source SHA, role, file hashes, source maps, relative symlinks, and build-info before the lease stopped successfully; terminal status was
completed, with zero active leases. Source fingerprints were unchanged.This Testbox validation run waited 60 s for an ordinary proof slot; source capture took 18.725 s, and provider/setup before the payload took 148.794 s (the provider does not expose a separate queue-only duration). Earlier attempts encountered the shared AWS fleet cap without obtaining a lease, and one recorded slot wait lasted 1,220.303 s before pausing for the native-admission fix. Other historical wait durations are unavailable. No fleet limit was bypassed. The aggregate remote helper exited 1 solely for the extra SDK zero-diff assertion described above; the package, update, Doctor, SDK comparison, and runtime build commands themselves exited 0.
The first local compiled probe could not start because the dist-only runtime archive omitted workspace package outputs; that failed setup is retained outside the measurement series. A bounded package supplement used one later Testbox lease,
tbx_01m4dj9byvsj40da9gmbp1gt4q(run), after 420 s waiting for an ordinary slot and 16.827 s source capture. Both canonical package builds passed. Its initial export smoke used the wrong resolution owner and failed; after that command settled, a sequential package-owned export check and archive recovery passed in 5.277 s without rebuilding or changing product source. Both revisions resolved and imported 163 exports across 17 packages. All 415 package output files were byte-identical across the independently built revisions; source/input/output manifests and archive hashes were verified before cleanup. The lease iscompleted, with zero active leases. Local installation replaced only generated package outputs and preserved the original verified Gateway runtimes and build IDs. No SQL result from the failed setup is included in the tables.The existing Telegram paired-DM consumer passed after routing through the established fork-based database-worker project. Its earlier thread-project refusal (
Shared-state admission requires the host broker) and the routing fix remain recorded. A loaded local Doctor run timed out before a later successful replay; the replay is not represented as a timeout fix or proof of an inherited failure. The final remote Doctor comparison above passed on both revisions; it does not establish a fix for the earlier loaded-host timeout.The retained synchronous SDK reader is a separate compatibility boundary. A mixed worker-first mutation followed by its first synchronous read opens and admits a distinct MAIN handle; worker publication does not transfer that handle. MAIN also retains its own native capability probe. That source-level +1 probe is part of an otherwise unmeasured cold-admission path, including ownership, schema, connection policy, and WAL setup. The async mutation performance claim does not cover this mixed sequence, and no total or tolerance pass is claimed for it. The released synchronous contract remains isolated until its documented next-major retirement.
Final measurement proof used AWS lease
cbx_c3b99228147d, runrun_5d2c1c3740e4967d67a267d31782c854, on the exact heads above. Both three-pair batches exited 0. All 1,413 raw evidence files and source/build/binding/load/cleanup receipts were verified before release (archive SHA-2567f11886b5918af1d216d1e2eef3e1d3b0f974ef9d2c5c19205db1501ea735c70). The lease is released, with no host or active owned lease; the ordinary proof slot and native SSH resources were released too.Measurement recovery is preserved: six earlier alternating macOS pairs had cold duration ratio 2.122775 and are diagnostic-only, never pooled with AWS. A later Testbox attempt waited 780 s for an ordinary slot, then timed out after 914.302 s without a payload; it was stopped before AWS. The first AWS setup hit the
/tmpquota before measurements. The successful retry used the workspace filesystem and supported pnpm hardlinks (installs 44.5 s / 5 s); no disk-size increase or dependency change. Native archive transfer was too slow (13.55 MB in about five minutes), so the owned transfer was stopped and canonical same-lease runtime builds replaced that transport step. Earlier source, update, Doctor, and SDK evidence remained valid because the reviewed source stayed unchanged. All attempts retained at most one lease, and all are stopped.Landing follow-through
The reviewed pairing implementation was integrated with main
fc1b2e66564e80ee567c5af844420572ef02671bin merge commit5bc73079f0ae7442e6eb781d6f216845e966129d, without conflicts. The existing alternating-pair SQL, released-driver update, and canonical SDK comparison evidence above remains valid; landing reuses it under the maintainer's proof-reuse direction.CI run https://github.com/openclaw/openclaw/actions/runs/37781150278 exposed two fixture adaptations caused by the worker cutover. The administrative CLI routing fixture ran its Gateway handler inside a Vitest thread and observed only main-thread SQL; it now uses the established host-owned project and observes native SQL on both the CLI thread and workers while retaining custody, no-replay, and durable-state assertions. The worker-registration fixture's closed native SQLite mock lacked the optional capability-capture function, preventing its synthetic reply from settling; the mock now explicitly returns no capability fact while keeping native database creation forbidden. No production fallback or weaker assertion was added.
The same run's unrelated typecheck/package-boundary failure (
clearFailedSystemAgentSessionStatemissing insrc/system-agent/agent-turn.ts) was fixed on main by19f37f076862830f9b8953287f94a4725e3b8908. UI active-run/display-tail failures were fixed on main bye8e341ecebf70a0d3802b3f52deecb4d53ec1ebbandd0194c3401f9c225dfd24d232715011e7dbf3f5d. Those fixes are included in this integration.Released SDK surface was checked against
v2026.10.1-beta.1and stablev2026.9.9: public pairing operations retain their parameter shapes and return types. The synchronous reader remains covered by its existing compatibility record and type test; removed full-state SQLite readers and the relocated account helper are internal. No new environment-variable names are introduced.Focused landing validation passed 49 tests across the administrative CLI custody suite, worker registration, shared-state imports, and runtime process build graph. The CLI suite passed all 25 cases in 264.70 s on this loaded host; it retains real process/RPC routing, offline lock custody, and lost-acknowledgement settlement, which an in-process mock cannot prove. The complete three-shard command took 745.73 s, including a 326.64 s cold compiled-worker preparation. The wrapper dependency inventory passed separately (28.32 s command, 25.18 s Vitest). Production typechecking and Madge passed with zero cycles. The first post-integration test-type invocation found an installed pre-integration ghostty declaration; refreshing this task-owned checkout to its frozen lockfile resolved that mismatch. No source workaround was made for it.
The fixture repair is commit
1858e96a5a3f; fresh Codex P2 autoreview of the integrated implementation and fixes is scoped-clean. Its earlier index-only finding was resolved by staging the already-reviewed fixture repair. The test-mock allowance inventory was regenerated and shrank by one exact legacy entry.