Repository navigation
perf(infra): move device pairing database access into workers - #154671
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 21, 2026, 8:38 AM ET / 12:38 UTC (Revision 8). ClawSweeper reviewWhat this changesMoves device-pairing database reads and writes into existing workers and updates node, notification, and prompt consumers to use asynchronously prepared pairing facts. Regression provenancePossible regression — suspected (reviewed change). No predecessor PR is attributed. Merge readiness⛔ Blocked before merge - 5 items remain The worker migration remains useful and is not implemented on current main. The previously reported cancellation blocker remains in the pinned head, so this PR is not ready to merge. Priority: P2 Review scores
Verification
How this fits togetherDevice pairing records determine which connected devices may execute node commands and receive notifications. The Gateway now obtains those records through database workers and uses published identity bindings to check subsequent operations. flowchart TD
A[Device and Gateway requests] --> B[Pairing operations]
B --> C[Read workers]
B --> D[Writer broker]
C --> E[Shared SQLite database]
D --> E
C --> F[Published pairing facts]
D --> F
F --> G[Node and notification authorization]
G --> H[Commands and push delivery]
Before merge
Findings
Agent review detailsSecurityNone. PR surfacePR surface statistics unavailable: the file list is incomplete. Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep worker-backed pairing authority while giving invocation teardown a narrowly scoped path bound to the original pending connection. Do we have a high-confidence way to reproduce the issue? Yes, source establishes the patch regression: start an invocation, hold an unrelated pairing mutation before publication, then abort or expire the invocation. The cancellation send is rejected after pending state is removed; no runtime reproduction was executed in this read-only review. Is this the best way to solve the issue? The existing reader and writer owners are the appropriate migration path, but the blanket event-send guard must distinguish teardown from admission of new work. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against f914e0f5f86c. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (7 earlier review cycles)
|
01d9cc6 to
6c7bd52
Compare
|
6c7bd52 to
4fa6f5a
Compare
6b1fd3e to
bdd90ae
Compare
Move runtime pairing reads into the read-only worker scope and mutations through the shared SQLite broker. Publish committed authority facts and revalidate live approval and node leases before commit; reconcile replaced grants even when result delivery fails. Testbox: 1,208 focused and sibling tests passed, plus type, lint, build, and golden checks. At 5,000 devices and 50 callers, list main-thread CPU fell 30.025 to 8.530 ms; readonly lists fell 38.907 to 8.950 ms. Tiny keyed lookups add worker overhead. No schema or config changes.
bdd90ae to
c702551
Compare
|
Merged via squash.
|
…aw#154671) Move runtime pairing reads into the read-only worker scope and mutations through the shared SQLite broker. Publish committed authority facts and revalidate live approval and node leases before commit; reconcile replaced grants even when result delivery fails. Testbox: 1,208 focused and sibling tests passed, plus type, lint, build, and golden checks. At 5,000 devices and 50 callers, list main-thread CPU fell 30.025 to 8.530 ms; readonly lists fell 38.907 to 8.950 ms. Tiny keyed lookups add worker overhead. No schema or config changes.
Related: #154189, #154318
What Problem This Solves
Device pairing lists, token/approval mutations, and node/push authority checks still execute SQLite on the Gateway request thread, delaying other clients.
User Impact
Paired/pending-device, bootstrap-token and node-surface database work runs in the existing readers and writer broker. List/lookup bytes, pairing decisions, and node/push ordering remain intact. No schema, config, stored representation, retention, or update changes are required.
Why This Change Was Made
Readers project pending/paired lists and keyed results in the read-only worker. The existing snapshot cache checks SQLite
data_version; a content revision allows facts from different reader/writer connections to be compared. The Gateway retains compact node identity/generation bindings. Reads validate the publication epoch independently; only a superseded read joins the writer queue and rereads, so disconnects do not wait behind unrelated queued history writes. Unchanged list revisions reuse those bindings without transferring them again. Historical inspection snapshots never publish live authority; current lookups and privileged push preparation read canonical state.Writers execute synchronous domain operations under the existing shared-state broker transaction. They reread authoritative records and obtain current host approval, node/probe, or connection admission before mutation and immediately before commit. Native commit receipts publish changed bindings and the revision before caller continuation. Bootstrap grant retirement also consumes the receipt, so a lost result reply cannot leave replaced operator grants connected; callback failure cannot redeliver retirement. Obsolete read replies cannot replace newer publications. Web Push starts sending while both subscription and pairing scopes remain held, then releases those scopes before provider completion. APNs registration moves its shared pairing reread into the same worker transaction as registration. Timestamped presence and connection/disconnection history retain their existing durable generation/timestamp semantics.
Evidence
Final same-machine comparison on Blacksmith Testbox
tbx_01m31ht3xfms3p94t4jt536qdq, providerblacksmith-testbox, profileopenclaw-check, Node 24.19.0. Original source051563c9b242765a947e8b094421ff3555e6be2dran in an isolated temporary source tree with its own frozen-lockfile installation. Fixture: 5,000 synthetic devices, 50 callers, two warm-up rounds and five measured rounds. CPU is the calling thread's CPU time; wall time is batch duration divided by 50, not individual request latency. The measurement candidate was01d9cc6a9c2; its rebase ontoaa099e492dapreserves every added/removed source line, with post-rebase shared-worker validation recorded below.Tiny lookups pay worker admission/transfer overhead. List CPU and elapsed time improve substantially; this cutover removes SQL from the calling thread rather than promising every individual lookup is faster. Complete serialized list/lookup goldens passed. The no-host-query regression was run against original code on
tbx_01m314gk9kx9rchq6stzkvv7a0and failed for four host Kysely calls, then passed on the candidate.Final validation: 745 tests across 28 affected files and 463 tests across 20 sibling files passed on Blacksmith Testbox (1,208 tests total). All 24 canonical core-test type graphs passed in the earlier serial campaign. Final core types and the affected infra, Gateway root/methods, and services graphs passed; the full build, lint, and selected changed-check guards passed. Independent Codex review completed through P2, with its accepted commit-reconciliation finding fixed and regression-proven.
The final read-ordering and skill-version repairs also received clean independent review through P2. The mechanical rebase to
aa099e492dapreserved every added/removed source line;6c7bd52b06eadditionally passed core types and 110 shared-worker tests across 11 files, plus scoped lint/format checks. Its full build passed (492.8 s). Initial exact-head CI exposed the integration gaps repaired below. Final Testbox commands used normal source sync throughout; no local tests, typechecks, lint, or builds ran on the Mac.The separate
device_pairing_join_codesstore remains a synchronous runtime path for onboarding shortcode generation/redemption; it is adjacent migration work outside this store/node/push cutover, not a maintenance exception.The proof is synthetic Testbox and mocked Gateway boundary coverage. No live Gateway deployment, provider send, or production CPU profile was performed.
Cutover inventory and synchronous exceptions
Inventory source: the program snapshot at
849c9a3c265d16dd181b1e3cddd76b26008cdfc0. The referenced program inventory recordssrc/infra/device-pairing-store.tsas 29 primitive expressions: 19 query calls, 4 take-first calls, and 6 shared-state transaction calls. The task brief estimated 32; this report uses the reproducible scanner count, whose primitive set excludes direct SQLite methods and other wrappers. The regenerated inventory still labels the native store primitives T1 because its tier is static; caller tracing and the no-host-SQL boundary regression prove the execution-context cutover. Its runtime callers now enter the reader scope or the worker broker:device-pairing-cloud-worker.tsmove transitively inside setup consumption’s existing transaction; they update the owningworker_environmentsrow.Row codecs, native transactions, and schema probes remain synchronous inside workers. Doctor’s legacy device/node imports retain
withPairedDeviceRecords; the desktop opt-out migration runs synchronously before node admission. Ordinary CLI pairing uses the worker facade. Other APNs cleanup mutations remain with their existing owner and are outside this pairing cutover. Retired runtime synchronous list/lookup and callback mutation paths were removed; there is no native fallback after worker failure.Remote runs and diagnosed preparation failures
All leases used
blacksmith-testbox/openclaw-check; commands used the installedcrabboxCLI and normal sync. Linked workflow runs identify the leases, not PR CI results.tbx_01m311rfq3brnmhgvpr790effbtbx_01m314gk9kx9rchq6stzkvv7a0tbx_01m316bp3d9p8a9v70vtg8bz9htbx_01m31920n5n46sdhagmfzznf2btbx_01m31aadrgw1yn0jp7f0pf1cdqnode scripts/run-tsgo-core-test-shards.mjs --stripe N/24. Dead-export checks then identified retired aliases; those were removed. Stopped.tbx_01m31cgj6v4p88x2jnscx3a8x5tbx_01m31fe6q8bnfbk5ebqfc31ze1pnpm install --frozen-lockfilepassed. The old bootstrap result-callback path failed the lost-reply regression; receipt reconciliation passed all seven worker cases. Individual focused Gateway tests passed untilwatch-node-http.test.tsexposed a deadlock: a fresh currentness read queued behind the history lock deliberately held by its disconnect regression. The lease was stopped, and the read owner was repaired without changing that test.tbx_01m31g2a0k7nvvw6f48zsvkysgpnpm test <file> --maxWorkers=1wall totaled 375.71 s. Watch-node HTTP completed in 30.95 s, including the unchanged disconnect regression (499 ms). The additional sibling batch passed 17 fast tests and 204 unit tests, but found a skill-snapshot version fence missing across the new preparation await and a cancellation fixture that assumed immediate build entry. Those three failing assertions/timeouts were diagnosed and repaired before final proof. Stopped.tbx_01m31h19xxwt3wmv4bnacs1ma1tbx_01m31ht3xfms3p94t4jt536qdqpnpm tsgo:core(56.93 s; active compiler observed at ~3.9 GB RSS),node scripts/run-tsgo-core-test-shards.mjs --stripe N/24for 7/4/22/13, regenerated inventory via the program script, canonical targeted lint, assertion/max-lines ratchets, changed-file formatting,pnpm build(560.5 s), original/candidate benchmark withOPENCLAW_DEVICE_PAIRING_BENCH=1 node scripts/run-vitest.mjs src/infra/device-pairing-worker.benchmark.test.ts --maxWorkers=1, and the measured snapshot fixture rerun. Stopped before commit.tbx_01m31kqgfdthyxdt26r88yaaze6c7bd52b06e:pnpm tsgo:corepassed (74.84 s);node scripts/run-vitest.mjsfor pairing worker/publication/bootstrap/bins, APNs, exec-authorization worker, shared read workers, skill resource reads, watch-node HTTP and push storage scope passed 110 tests / 11 files (68.53 s); canonical targeted lint and formatting passed for the five shared dispatch/read files;pnpm buildpassed (492.8 s). Overall remote command 719.61 s. Stopped.Reused leases sometimes fell back to a full sync and reached Blacksmith's fixed two-minute sync deadline. Fresh leases restored targeted sync; no sync bypass was used. Explicit pre-fix regression probes restored the candidate source before its passing run.
Measured test cost
Each affected file was run with
pnpm test <file> --maxWorkers=1ontbx_01m31g2a0k7nvvw6f48zsvkysg; wall includes runner/compiler startup and cleanup, not just test bodies. The suite uses existing worker/fork owners and suite fixtures; the measurement flag is not a new CI pin. CI timing for the PR head is pending.src/gateway/watch-node-http.test.tssrc/gateway/approval-web-push.test.tssrc/gateway/control-ui.http.test.tssrc/gateway/device-pair-setup-completion.test.tssrc/gateway/event-web-push.storage-scope.test.tssrc/gateway/event-web-push.test.tssrc/gateway/node-reapproval-coordinator.test.tssrc/gateway/node-registry-pairing.test.tssrc/gateway/node-registry.test.tssrc/gateway/server-methods/nodes.apns-registration.test.tssrc/gateway/server.node-pairing-ssh-verify.test.tssrc/gateway/user-profiles-http.auth.test.tssrc/infra/device-bootstrap.test.tssrc/infra/device-bootstrap.worker.test.tssrc/infra/device-pairing-approval-policy.test.tssrc/infra/device-pairing-churn.test.tssrc/infra/device-pairing-migration.test.tssrc/infra/device-pairing-node-bins.worker.test.tssrc/infra/device-pairing-node-desktop-migration.test.tssrc/infra/device-pairing-node.lifecycle.test.tssrc/infra/device-pairing-node.test.tssrc/infra/device-pairing-prune.test.tssrc/infra/device-pairing-publication.test.tssrc/infra/device-pairing-worker.test.tssrc/infra/device-pairing.test.tssrc/infra/node-pairing-migration.test.tssrc/infra/push-apns.store.test.tssrc/skills/runtime/remote.test.tsThe changed cancellation fixture was additionally measured with the same command on
tbx_01m31ht3xfms3p94t4jt536qdq:src/skills/runtime/session-snapshot.test.ts2.89 s wall (all cases passed).The opt-in 5,000-device benchmark is skipped in normal test runs. New worker tests protect native commit/rollback, publication races and live authority at real broker boundaries; a helper-only mock cannot prove those contracts.
Exact-head CI repair
Reviewed head:
c702551d87dd9498b21a4e50497334bfee02ee80, one commit with the original subject, rebased onto1ccccb02788a. Mechanical rebases preserved every added and removed PR source line while retaining conversation-binding, placement-reader, and Cron recovery registrations from main. The final Cron rebase reuses unchanged scoped proof; its complete combined context is gated by exact-head hosted CI.CI exposed integration gaps beyond the initial focused proof. Private worker kernel exports now have distinct names, real database consumers run under the existing forked broker owners, and current-authority assertions use committed publication. Subscription fixtures update synchronous authority with their generation. The bootstrap fixture records the WebSocket challenge before awaiting token creation; startup proof observes the actual admission release instead of an event-loop tick. Gateway test paths remain sorted, and broad script watch selection retains both tooling and database-worker coverage.
The APNs domain contract and worker now own registration and both read operations together. The central dispatcher delegates after its existing database-open boundary, reducing its counted lines from 707 to 698 without baseline or suppression changes. The registration transaction, pairing-generation check, live admission, tombstone versions, and read helpers are unchanged.
Validation:
tbx_01m31tz01a7qfeqnmwmc1y0014(environment run).tbx_01m31vrjywk8xypb3rhaegwxf3(environment run); remote command 143.58s.Fixture costs measured with
pnpm test <file> --maxWorkers=1on Testbox:src/gateway/server/ws-connection.startup.test.tssrc/gateway/server-node-session-runtime.test.tssrc/gateway/server.node-pairing-memo.test.tssrc/infra/device-pairing-publication.test.tssrc/infra/node-pairing-state.test.tstest/scripts/test-projects.test.tsStartup and memo retain existing real handshake/Gateway fixtures to prove registered admission and
node.listdispatch. The existing routing matrix covers CLI/watch ownership; the obsolete isolated case was moved into its mixed-owner table without adding a scenario. No new CI worker pin, timer, polling loop, or per-case Gateway boot was added.Some reused Testboxes hit the provider's two-minute checksum-sync deadline before executing checks; fresh leases restored sync. The initial new-head PR workflow failed to start, and one Security Review attempt hit GitHub installation API rate limiting. The queued explicit CI run was cancelled after that head needed rebase. No failed GitHub jobs have been rerun.
The final dispatcher follow-up adds an explicit unsupported-command throw, matching sibling worker executors and the consistent-return rule. Pure-main infra/dispatcher lint passed 2,133 files; the candidate passed targeted lint on all four APNs/dispatch files with zero warnings/errors and all 11 APNs store tests on Blacksmith Testbox
tbx_01m31y6kt44j4a54fqxab8rk3s. Independent P1 autoreview was clean. The preceding full CI run passed every check except this corrected lint rule.The earlier external auto-merge request was explicitly retired after verifying its current head and squash method, so native landing can own its final recorded merge request. Exact-head CI run 35599383909 and the enforced
openclaw/ci-gatepassed. Native squash landing completed as05117d9db7bf8211ac1d5fe6b3a3da6232eedb25, verified on GitHub and in main history. No admin bypass or PR-operation lock recovery was used. Native verification reported relevant main drift in docs, test routing, and tooling and proceeded under the repository’s normal drift policy; the retained merge receipt verified the landed change. Peter, repository administrator, directed this landing and authorized the native admin route if an enforced review requirement blocks it; exact-head CI remains mandatory.