Skip to content

perf(state): check state ownership once per read boundary - #159876

Merged
steipete merged 1 commit into
mainfrom
perf/state-owner-check-once-per-read
Sep 28, 2026
Merged

steipete merged 1 commit into
mainfrom
perf/state-owner-check-once-per-read

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: every shared-state read on the Gateway main thread repeated the full state-ownership check several times, so loading a Control UI session spent a large share of main-thread time in synchronous realpath and sidecar-lock open calls.

User Impact

Session loading and other state reads block the Gateway event loop less. On a warm Gateway, one Control UI reload of a long session now makes 1,300 synchronous realpath calls instead of 2,570 (−49%) and 452 sidecar-lock opens instead of 726 (−38%). Ownership semantics, error messages, and maintenance/lease outcomes are unchanged.

Why This Change Was Made

A warm Gateway CPU profile across one reload and three session switches attributed about 25% of main-thread busy time to synchronous realpath and openSync under assertStateDatabaseAccessAllowed(). Counting calls by caller showed about 780 checks per reload for about 128 state reads, so each read passed the full check (three realpaths plus one sidecar open) about six times. Several of those checks ran back to back in the same synchronous span, with no awaited work or side effect between them.

Caching the owner path was ruled out: access checks must keep selecting the owner of the current canonical target, so retargeting a state-directory alias during maintenance still refuses ordinary access and the old lease. This change keeps per-check freshness and removes only checks that repeat a boundary already checked in the same span.

  • openclaw-state-db-borrow.ts: the retainer admits once (maintenance admission + owner check) before finding the cached handle and passes that admission, synchronously, into retaining the same handle. The public retain entry still admits for itself.
  • openclaw-state-db-readonly.ts and openclaw-state-read-worker.ts: read preparation no longer repeats the owner check that the retainer (or, for snapshot reads, an explicit check) just made, and the transport's synchronous wrapper no longer checks before building the request. The pool's dispatch callback still checks current authority right before the worker receives the request, including after a queue wait, and again after the reply. Checks after snapshot preparation and before retaining snapshot temp directories remain.
  • resolveGatewayStateOwnerPath builds the Unix lock directory from the state directory derived from the freshly canonical database path, which is already canonical because it is an ancestor, instead of realpathing it again (resolveGatewayLockDirForCanonicalStateDir). The final lock-directory resolution stays, because tmp and its child may be links. The Windows layout is unchanged.

Kept on purpose: fresh alias resolution per check, path-based verifyStillHeld(), worker message receive/grant checks (intervening callbacks can revoke authority), generic actor preparation checks for direct callers, and native SQLite admission.

Evidence

  • Regression tests: one state read performs one owner-path resolution per synchronous span (fails on the original code); acquiring through an alias and retargeting it under maintenance still refuses ordinary access and the old lease; linked lock directories and missing path suffixes resolve to the same owner path as before; worker admission still refuses after a message hop when authority changed.
  • 931 tests across 60 related files pass (two platform skips), plus pnpm tsgo:core, pnpm tsgo:core:test, CI oxlint on the touched files, and independent Codex P2 review.
  • Syscall counts from a scratch preload that counts main-thread realpathSync.native/openSync by caller. Same seeded state (1,500-turn session + 30 × 60-turn sessions), one warm-up reload, then one measured reload: realpath 2,570 → 1,300, openSync 726 → 452. This is macOS count evidence, not a CPU-time or cross-platform claim.

Per-file cost: the four changed test files together take 57.8 s wall with --maxWorkers=1 on a heavily loaded host (100 tests); the new cases add 0.26 s combined. CI seconds will be added from the first run.

Update behavior: none. No config, state, schema, lock layout, or service lifecycle change.

@clawsweeper

clawsweeper Bot commented Sep 27, 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.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. 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 Sep 27, 2026
@clawsweeper

clawsweeper Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 27, 2026, 8:41 PM ET / September 28, 2026, 00:41 UTC (Revision 3).

ClawSweeper review

What this changes

The branch reduces repeated synchronous ownership checks during Gateway state reads and adds regression coverage for path aliases, maintenance admission, and worker dispatch.

Merge readiness

✅ Ready for maintainer review

Current main still repeats the ownership checks this PR targets. The proposed read path retains admission before native retention, at worker dispatch, and when accepting the result; this review found no concrete introduced defect.

Priority: P2
Reviewed head: f5866a5d0bccb9d679c6e39f8bf3a393a652ab0c

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused patch has relevant regression coverage and a specific runtime measurement, with no blocking defect identified.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: The maintainer-authored internal performance PR is exempt from contributor proof. Its body reports a measured warm macOS Control UI reload, while source review connects read retention to worker dispatch and result validation; no stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The maintainer-authored internal performance PR is exempt from contributor proof. Its body reports a measured warm macOS Control UI reload, while source review connects read retention to worker dispatch and result validation; no stored-data contract changes.
Evidence reviewed 7 items Current main retains repeated checks: The five touched production files have no changes between the pinned merge base and fetched main. Main still checks authority at read preparation and in the transport wrapper.
Synchronous read admission: The retainer checks maintenance admission and database access before finding and retaining the cached native handle.
Final read authority checks: The worker task checks current authority before receiving its request, including after queueing; the read owner checks again after the reply.
Findings None None.
Security None None.

How this fits together

The Gateway reads shared SQLite state for requests such as Control UI session loading. It checks access, retains the read source, sends work to a SQLite worker, and validates authority before using the result.

flowchart LR
  A[Control UI session request] --> B[Gateway state read]
  B --> C[Ownership admission]
  C --> D[Read source retention]
  D --> E[Worker queue]
  E --> F[Dispatch authority check]
  F --> G[SQLite read worker]
  G --> H[Result authority check]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +29, Tests +180. Total +209 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 5 65 36 +29
Tests 4 182 2 +180
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 247 38 +209

Review metrics

Metric Value Why it matters
Reported warm-reload syscalls realpath 2,570 → 1,300; lock opens 726 → 452 The PR body quantifies the intended main-thread improvement on one seeded macOS scenario.

Technical review

Best possible solution:

Keep admission at synchronous read retention and preserve fresh checks before worker I/O and result acceptance, with the alias and maintenance regressions guarding those boundaries.

Do we have a high-confidence way to reproduce the issue?

Yes. Current main visibly repeats ownership checks across read preparation and transport, and the PR body gives a seeded warm-reload measurement; this read-only review did not run that scenario.

Is this the best way to solve the issue?

Yes. The patch removes checks repeated within synchronous spans while retaining fresh checks across the worker queue and after the reply.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 86c4bf83e699.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The PR addresses a measured session-loading performance cost with limited blast radius.
  • merge-risk: 🚨 security-boundary: The patch removes repeated checks from a state-access path, so preserving authority checks at dispatch and result acceptance matters before merge.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The maintainer-authored internal performance PR is exempt from contributor proof. Its body reports a measured warm macOS Control UI reload, while source review connects read retention to worker dispatch and result validation; no stored-data contract changes.

Evidence

What I checked:

  • Current main retains repeated checks: The five touched production files have no changes between the pinned merge base and fetched main. Main still checks authority at read preparation and in the transport wrapper. (src/state/openclaw-state-db-readonly.ts:513, 86c4bf83e699)
  • Synchronous read admission: The retainer checks maintenance admission and database access before finding and retaining the cached native handle. (src/state/openclaw-state-db-borrow.ts:38, f5866a5d0bcc)
  • Final read authority checks: The worker task checks current authority before receiving its request, including after queueing; the read owner checks again after the reply. (src/state/openclaw-state-read-worker.ts:559, f5866a5d0bcc)
  • Alias and maintenance coverage: Introduced tests cover retargeting a state-directory alias while the old owner is held and refusing worker admission after maintenance starts. (src/infra/gateway-state-owner.test.ts:697, f5866a5d0bcc)
  • Reported production measurement: The PR body reports one seeded warm macOS Control UI reload reducing main-thread realpath calls from 2,570 to 1,300 and sidecar-lock opens from 726 to 452. No raw trace is linked. (f5866a5d0bcc)
  • Feature history: Recent merged state and Gateway work includes the SQLite coordination fix and worker-operation performance work by Peter Steinberger, alongside owner-bound update work by Dallin Romney. This is routing context, not proof of feature introduction. (src/state/openclaw-state-db-readonly.ts, 86c4bf83e699)

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Dallin Romney: 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 (2 earlier review cycles)
  • reviewed 2026-09-27T20:19:51.935Z sha 94386bfffc8239cfe1b07c838d1c9585b56bfc4d :: needs maintainer review before merge. :: none
  • reviewed 2026-09-27T21:10:43.962Z sha 80cda3117c8b5950a3c582ad173d94dff11414eb :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the perf/state-owner-check-once-per-read branch from 94386bf to 80cda31 Compare September 27, 2026 21:03
Admit native read retention once before finding and retaining its handle.
Keep that admitted step private to the synchronous retainer entry points.
Let the retainer own the initial database access check and the read transport
own queued dispatch admission, removing repeated checks in read preparation
and the transport's synchronous wrapper.

Build the Unix lock layout from the freshly canonical database ancestor,
without realpathing that ancestor again. Still resolve the final lock directory
because tmp and its child may be links. Windows layout is unchanged.

Revalidate after snapshot preparation and queue waits, before worker dispatch,
and after worker replies and cleanup. Preserve worker message receive and grant checks because domain
callbacks can revoke authority, generic actor checks for direct callers, native
SQLite admission, fresh alias resolution, and path-based verifyStillHeld.
No cross-await cache, dependency, configuration, schema, or update change.

Proof: 931 tests passed across 60 files, with two platform skips; core and core
test typechecks, CI oxlint on touched files, formatting, and diff checks passed.
The four changed test files also passed with one worker (100 tests, 57.84s wall;
new cases 0.264s combined). Count regressions fail on the original code. Alias
retargeting, linked lock directories, missing suffixes, and message-hop refusal
retain their outcomes. Independent Codex review is clean through P2.

Matched warm scratch-harness runs on base 42e53a4 reduced main-thread
realpathSync.native calls from 2570 to 1300 (49.4%) and openSync calls from
726 to 452 (37.7%). Runtime JavaScript and Control UI builds passed. This is
syscall-count evidence on macOS/Node, not a CPU-time or cross-platform claim.
@steipete
steipete force-pushed the perf/state-owner-check-once-per-read branch from 80cda31 to f5866a5 Compare September 28, 2026 00:34
@steipete
steipete merged commit e8336e8 into main Sep 28, 2026
209 checks passed
@steipete
steipete deleted the perf/state-owner-check-once-per-read branch September 28, 2026 04:01
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 28, 2026
…aw#159876)

Admit native read retention once before finding and retaining its handle.
Keep that admitted step private to the synchronous retainer entry points.
Let the retainer own the initial database access check and the read transport
own queued dispatch admission, removing repeated checks in read preparation
and the transport's synchronous wrapper.

Build the Unix lock layout from the freshly canonical database ancestor,
without realpathing that ancestor again. Still resolve the final lock directory
because tmp and its child may be links. Windows layout is unchanged.

Revalidate after snapshot preparation and queue waits, before worker dispatch,
and after worker replies and cleanup. Preserve worker message receive and grant checks because domain
callbacks can revoke authority, generic actor checks for direct callers, native
SQLite admission, fresh alias resolution, and path-based verifyStillHeld.
No cross-await cache, dependency, configuration, schema, or update change.

Proof: 931 tests passed across 60 files, with two platform skips; core and core
test typechecks, CI oxlint on touched files, formatting, and diff checks passed.
The four changed test files also passed with one worker (100 tests, 57.84s wall;
new cases 0.264s combined). Count regressions fail on the original code. Alias
retargeting, linked lock directories, missing suffixes, and message-hop refusal
retain their outcomes. Independent Codex review is clean through P2.

Matched warm scratch-harness runs on base 05eb3a8 reduced main-thread
realpathSync.native calls from 2570 to 1300 (49.4%) and openSync calls from
726 to 452 (37.7%). Runtime JavaScript and Control UI builds passed. This is
syscall-count evidence on macOS/Node, not a CPU-time or cross-platform claim.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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