Repository navigation
perf(state): stop re-reading the ownership lock on every shared-state read - #160139
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 28, 2026, 7:46 AM ET / 11:46 UTC (Revision 4). ClawSweeper reviewWhat this changesThe branch lets the Gateway’s dedicated SQLite state-read transport reuse recent ownership verification for up to one second and updates its documentation, wrapper inventory, and tests. Merge readiness⛔ Blocked before merge - 5 items remain Current main still checks the ownership lock on each shared-state read. The earlier merged performance PR removed repeated checks within a read, so this branch has distinct value. The documented one-second change to read authority needs explicit maintainer acceptance before merge. Priority: P2 Review scores
Verification
How this fits togetherGateway requests read shared SQLite state through a dedicated worker transport. The Gateway checks state ownership before dispatch; the worker returns rows used by features such as device pairing and sessions. flowchart LR
A[Gateway request] --> B[Shared-state read]
B --> C{Recent ownership proof?}
C -- No --> D[Verify owner sidecars]
C -- Yes --> E[Read worker]
D --> E
E --> F[SQLite rows and reply]
Decision needed
Why: The branch deliberately changes when physical ownership loss stops reads; source and proof can establish the bound, but cannot choose that safety tradeoff for maintainers. Before merge
Findings
Agent review detailsSecurityNeeds attention: The diff adds no dependency or secret-handling change, but deliberately delays read refusal after out-of-band loss of state-lock ownership. PR surfaceSource +120, Tests +308, Docs +14, Other +1. Total +443 across 13 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep ownership policy in the existing state owner, with bounded reuse for dedicated reads only if the responsible maintainer accepts its documented window and strict admission remains in place for mutations. Do we have a high-confidence way to reproduce the issue? Yes from source: current main performs fresh physical ownership checks on the read path, and the PR body reports repeated synchronous lock operations during a Control UI reload. I did not execute the Gateway in this read-only review. Is this the best way to solve the issue? Yes as a focused implementation path: it changes the existing state owner and dedicated reader instead of adding a competing lock owner. Its safety tradeoff still needs explicit acceptance. Full review comments:
Overall correctness: patch is correct AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 659f4b73d8e2. LabelsLabel changes:
Label justifications:
EvidenceSecurity concerns:
What 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 (3 earlier review cycles)
|
|
CI note for run 36380641313: the only failing job was This is a pre-existing Bun GC-timing flake, unrelated to this change:
The flake is tracked as a separate fix (deterministic GC check under Bun, without weakening the assertion). Rerunning the failed job on this head. |
Keep process/projection exclusion, schema leases, native-handle custody, physical database identity, maintenance admission, and SQLite transaction and commit grants. The hot cost was repeated observation of the same process owner at independent read lifetime boundaries. Monitor owner/projection sidecars every second and cache canonical owner paths for one second, invalidating them on ownership and schema lifecycle transitions. Only the dedicated shared-state read transport opts in. Reads tolerate that bounded window after out-of-band lock replacement or alias retargeting; writes and generic broker jobs keep fresh checks. Foreign and maintenance ownership remain strict. No schema or dependency changes; update behavior is unchanged. One warm Control UI reload on synthetic state (46 RPCs), base f5866a5 versus candidate: realpathSync.native 1478 -> 913 (-38.2%), openSync 536 -> 275 (-48.7%). Counter windows were 8.087s and 9.810s. The top-40 stack buckets show explicit-read sidecar opens 256 -> 0; candidate monitoring adds 20 opens. This is syscall evidence, not a latency claim. Validation: fake-timer ownership/projection theft, alias expiry, lifecycle and failed-cleanup invalidation, and no warm read ownership syscalls. The transport regression fails on the base with an owner-sidecar open. Both core typecheck lanes, touched-file CI oxlint, line-cap ratchet, diff checks, and independent P2 review pass. Runtime/UI builds pass with declaration emission disabled; runtime postbuild/stamps are included. The broader run initially timed out the unchanged synchronous snapshot test after 162.790s against its 120s deadline under heavy host load. Its same-file-order replay with the original concurrent lifecycle suite passed in 5.002s without a fix, so the original cause remains unresolved. The selected 57 files finish with 852 passing tests and two existing skips across the successful runs. No timeout or assertion was weakened. New ownership test cost: 8 cases, 7.879s summed test time and 80.49s shard wall under host load. The two changed read/borrow files shared a 417.61s unit shard; initial worker transformation dominated that cold run. Benchmark and broad-suite evidence use the original f5866a5 base; rebase integration preserves the unchanged ownership implementation. Benchmark limitations: an initial cold-start warmup timeout was discarded. Both base and candidate reproduce existing Teams/Zoom plugin shutdown cleanup failures, but both isolated Gateways stopped and state was removed. Both UI builds retain the existing 363.4/362.9 KiB startup-JS advisory.
d26e651 to
9ad3d98
Compare
Merge main while preserving relocated Doctor ownership and retained projection custody. Replace the fs-safe compromise monitor with monotonic timestamps for successful root and projection verification. Explicit reads synchronously refresh expired proof before worker dispatch; transient verification failures refuse one attempt without poisoning the owner. Strict access stays unchanged. Keep canonical-path expiry and lifecycle invalidation independent of sidecar proof. Root-only checks cannot renew projection evidence. The read-only transport accepts a bounded sub-second ownership window; writes, maintenance, schema leases, and generic SQLite worker jobs retain fresh checks. Production-transport regressions fail on 9ad3d98 for expired admission, delayed dispatch, and sticky transient errors. Update the ownership docs to state the timer-free bound and retry behavior. Live device.pair.list proof refused after replacement and 1250ms with zero shared-read dispatches, then recovered after restoring the original inode. Ownership sidecar opens stayed 280 -> 278; timer opens fell 18 -> 0. Raw reload counts were confounded by lazy startup work and do not prove aggregate speedup. Focused proof: 872 passed, 2 existing skips, and 2 unchanged child-process timeouts. The compile-cache replay passed all 11 cases without a code change; the initial timeout cause remains unresolved. Core/test types, touched-file CI oxlint, diff checks, and Codex P2 autoreview passed.
|
CI note for
These are timing flakes on loaded runners; they are being tracked separately. Rerunning only the failed job on this head. |
… read (openclaw#160139) * perf(state): monitor ownership for explicit shared-state reads Keep process/projection exclusion, schema leases, native-handle custody, physical database identity, maintenance admission, and SQLite transaction and commit grants. The hot cost was repeated observation of the same process owner at independent read lifetime boundaries. Monitor owner/projection sidecars every second and cache canonical owner paths for one second, invalidating them on ownership and schema lifecycle transitions. Only the dedicated shared-state read transport opts in. Reads tolerate that bounded window after out-of-band lock replacement or alias retargeting; writes and generic broker jobs keep fresh checks. Foreign and maintenance ownership remain strict. No schema or dependency changes; update behavior is unchanged. One warm Control UI reload on synthetic state (46 RPCs), base f5866a5 versus candidate: realpathSync.native 1478 -> 913 (-38.2%), openSync 536 -> 275 (-48.7%). Counter windows were 8.087s and 9.810s. The top-40 stack buckets show explicit-read sidecar opens 256 -> 0; candidate monitoring adds 20 opens. This is syscall evidence, not a latency claim. Validation: fake-timer ownership/projection theft, alias expiry, lifecycle and failed-cleanup invalidation, and no warm read ownership syscalls. The transport regression fails on the base with an owner-sidecar open. Both core typecheck lanes, touched-file CI oxlint, line-cap ratchet, diff checks, and independent P2 review pass. Runtime/UI builds pass with declaration emission disabled; runtime postbuild/stamps are included. The broader run initially timed out the unchanged synchronous snapshot test after 162.790s against its 120s deadline under heavy host load. Its same-file-order replay with the original concurrent lifecycle suite passed in 5.002s without a fix, so the original cause remains unresolved. The selected 57 files finish with 852 passing tests and two existing skips across the successful runs. No timeout or assertion was weakened. New ownership test cost: 8 cases, 7.879s summed test time and 80.49s shard wall under host load. The two changed read/borrow files shared a 417.61s unit shard; initial worker transformation dominated that cold run. Benchmark and broad-suite evidence use the original f5866a5 base; rebase integration preserves the unchanged ownership implementation. Benchmark limitations: an initial cold-start warmup timeout was discarded. Both base and candidate reproduce existing Teams/Zoom plugin shutdown cleanup failures, but both isolated Gateways stopped and state was removed. Both UI builds retain the existing 363.4/362.9 KiB startup-JS advisory. * fix(scripts): add gateway state owner directory to the PR wrapper inventory
What Problem This Solves
Fixes: the Gateway re-verified the same state-ownership lock file on every shared-state read. A single Control UI reload spent hundreds of synchronous
openandrealpathcalls on the event loop, re-proving an ownership fact that had not changed.User Impact
Shared-state reads verify ownership at most once per second instead of on every read, which removes most per-read lock-file opens and canonical-path resolutions from the Gateway event loop during session loading. Writes, schema/maintenance transitions, lease grants, and every generic SQLite worker job keep their current immediate checks. A transient filesystem error during a verification fails only that read, and the next read retries. No schema, config, protocol, or update behavior changes.
Why This Change Was Made
Maintainer question behind this: why so many locks? The inventory showed the hot path is mostly one lock re-verified at many independent read-lifetime boundaries: the process-owner sidecar, plus its compatibility projection. Each full check costs two canonicalizing
realpathcalls plus a re-read of the sidecar by path. The other layers protect distinct failures and are mostly memory checks. Maintenance admission keeps work out during maintenance. Physical database identity/generation keeps results from attaching to a replaced file. Native-handle custody prevents closing in-use handles. Worker request/grant admission stops mutations after authority changes. SQLite transactions serialize writes. This PR keeps all of them.The owner sidecar uses
staleMs: Infinitywith PID/start-time liveness and no heartbeat, so a conforming peer never evicts a live owner. Per-read re-verification therefore only guarded against out-of-band sidecar replacement or deletion, a peer misjudging liveness (for example across PID namespaces), and an operator retargeting a state-directory alias.gateway-state-owner.tsrecords a monotonicverifiedAtfor the root owner and its projection whenever a physical verification succeeds.assertStateDatabaseReadAllowed(used only by the dedicated shared-state read transport) admits from memory while the cached canonical owner path and both verifications are younger than one second. Otherwise it re-resolves the canonical path and runs a freshverifyStillHeld()synchronously before admitting. No read is ever admitted on a verification older than one second, independent of timers.assertStateDatabaseAccessAllowedbehavior is unchanged. Acquire, lease run/release, and cleanup invalidate the cached read state immediately.openclaw-state-db-readonly.ts, via the read-retention entry points inopenclaw-state-db-borrow.ts/openclaw-state-db-cache.ts) opts in. The generic SQLite worker broker has no read/write access-mode contract (for example,capture.listSessions/capture.readBlobshare the writable opener that can create state), so it deliberately stays strict.docs/gateway/gateway-lock.mdand the worker-access page document the bound: explicit reads can be admitted for at most one second after an out-of-band lock replacement or alias retarget; mutations never are; transient verification errors fail only the affected read.An earlier revision used fs-safe's
setIntervalcompromise monitor. Review correctly found that a late tick could stretch the window and that a transient verification error became permanent. This revision removes the timer and the sticky flag entirely.Evidence
device.pair.listRPC, which reads through the shared-state read transport; a scratch preload recorded workerpostMessageread dispatches by command ID only):UNAVAILABLE: "OpenClaw state ownership at /state/openclaw.sqlite could not be verified; retry after maintenance finishes.")pnpm tsgo:core,pnpm tsgo:core:test, CI oxlint on touched files, and independent Codex P2 review pass.Per-file cost: the new/changed owner and transport tests use fake clocks; CI seconds will be added from the first run.
Follow-up (not in this PR): give generic SQLite worker operations an explicit
read/writeaccess mode so audited read-only broker jobs can use the same bounded check;capture.listSessions/capture.readBlobfirst need a non-creating read-only opener.