Skip to content

perf(auth): reuse readers for equivalent state roots - #167024

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-auth-profiles-read-cost-20260919
Oct 8, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-auth-profiles-read-cost-20260919

Conversation

@steipete

@steipete steipete commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Auth-profile reads can repeatedly restart their shared SQLite reader when one caller leaves the default state directory implicit and another explicitly pins that same directory.

User Impact

Repeated auth reads reuse the existing child across equivalent state-directory representations. Different roots, other environment changes, source changes, shutdown, and read admission retain their existing behavior. No schema, configuration, stored-format, or update migration changes.

Why This Change Was Made

The read-worker launch owner now captures the canonical effective state directory before comparing launch environments. Auth runtime and usage callers already pin this root; catalog callers can leave it implicit. Comparing those representations previously discarded the warm child and repeated process startup and imports. The query itself reads two keyed JSON blobs, without a table scan or decryption.

Production delta: +5 lines. This uses the existing state-directory resolver at the existing launch owner; the growth supplies the canonical launch fact needed for safe reuse. It adds no cache, fallback, export, or second lifecycle owner.

Evidence

Blacksmith Testbox, profile openclaw-check, lease tbx_01m4cy7qhmpyff16d77q4qrkk7. Synthetic 20-profile WAL database, real source-mode SQLite reader and spawn broker, one cold warmup followed by ten measured reads:

Case Before mean After mean
Alternate implicit/explicit same state root 752.36 ms 1.46 ms
Already identical environment (50 reads) 1.38 ms 1.36 ms

The affected warm-read case improves 516× and falls below the 10 ms target. Source-mode cold startup remains approximately 0.7–0.8 seconds; these are synthetic source-worker timings, not deployed Gateway latency or a claim that all auth reads become faster. Parent RSS at the end of the alternating case was 252.2 MB before and 251.9 MB after; no allocation reduction is claimed.

  • crabbox run --id tbx_01m4cy7qhmpyff16d77q4qrkk7 --timing-json -- bash -c <synthetic benchmark>: passed before and after (46.06 s and 22.67 s remote command time, including setup).
  • Regression before the production change: node scripts/run-vitest.mjs src/infra/sqlite-readonly-worker.auth.test.ts -t 'reuses equivalent state roots' --maxWorkers=1 failed at the expected assertion: two equivalent reads spawned two children instead of one.
  • Fallback validation on a Linux rig (Node 26.8.1 / SQLite 3.53.4), with the exact base 3d74794d863e7a9bce2846d6dd51a69f470b3a36 and SHA-256 checks of all three patched files. The auth-worker file, transport/session/cwd/generation/retention/diagnostic/operation siblings, and remaining compile-cache/agent auth-store tests passed.
  • Five pre-existing failures in src/infra/sqlite-readonly-worker.model-auth.test.ts reproduced on that unmodified base: WAL publication timestamps (shared and local), unchanged credentials with host/external rotation, and incognito cache reuse. The baseline file finished with the same five failures and 16 passes (440.47 s including cold compiled-subprocess preparation). These are recorded failures, not passing coverage.
  • Independent Codex review: scoped-clean through P2.
  • Changed-file cost: /usr/bin/time -p pnpm test src/infra/sqlite-readonly-worker.auth.test.ts --maxWorkers=1 passed all 18 tests in 215.19 s wall time on the shared rig, including cold compiled-subprocess preparation (80% of Vitest duration); test execution accounted for 18%. This existing file verifies real native/broker process reuse, revocation, bounded field transfer, and cleanup, which cannot be proved by a mocked launch comparison. The patch extends its existing lifecycle case rather than adding a new process fixture.
  • Staged gate on the rig: nice -n 10 ionice -c3 node scripts/check-changed.mjs --staged passed, exit 0 (05:23–07:15 UTC, approximately 112 minutes).
Gate summary Result
Core types and all 27 selected test-type projects Passed
Changed-file lint 0 warnings, 0 errors
Production, full-tree, and script dead-export scans 0 unused exports
Native schema, legacy-store, runtime-sidecar, import-cycle, webhook and pairing guards Passed; 0 runtime import cycles

The reviewed patch was rebased onto current main before publication; all three changed file hashes are unchanged. CI run 37743569356 passed on the published head. In checks-node-changed-3, the changed auth-worker file passed all 18 tests in 64.41 s including wrapper/worker preparation (62.44 s Vitest duration; 70% transform, 28% tests). Both security-review gates passed. The PR merged as a06612710e674f493a3ae8fe1158f60bb56d3924.

The Testbox's later sync timed out before sibling tests started. AWS and Hetzner allocation both returned the shared fleet's active-lease limit; neither created a lease. The Testbox lease was stopped and the authorized rig fallback was used.

@clawsweeper

clawsweeper Bot commented Oct 8, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: XS labels Oct 8, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 8, 2026
@clawsweeper

clawsweeper Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 8, 2026, 3:31 AM ET / 07:31 UTC (Revision 2).

ClawSweeper review

What this changes

The branch resolves the effective state directory before comparing SQLite reader launch environments so equivalent roots reuse the existing child.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused patch appears correct and has sufficient native-worker boundary evidence, but its performance proof does not run a complete shipped Gateway flow.
Proof confidence 🦐 gold shrimp (3/6) Sufficient (live_output): The recorded Testbox benchmark exercises the changed launch owner through real source-mode SQLite children and the spawn broker, showing equivalent-root reads improve from 752.36 ms to 1.46 ms while the identical-environment control stays steady. This proves the scoped process-reuse benefit, not deployed Gateway latency; source inspection verifies that no stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Repeated authentication reads pay process-startup costs even when callers select the same state directory.
Reason: The recorded redundant startup cost is substantial relative to this small owner-level repair. Prior merged area-owner work already establishes compatible reader reuse as the intended direction.

Merge readiness

✅ Ready for maintainer review

This PR remains useful: current main still replaces readers for equivalent implicit and explicit state roots. No actionable defect was found, and the recorded native-worker benchmark supports the scoped performance benefit.

Priority: P2
Reviewed head: 1f9fdd6c8c296f2770c52ce01f66c485aeca03db

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: A complete shipped Gateway flow was not exercised by the supplied benchmark; deployed Gateway latency is explicitly outside its claims. The recorded pre-fix failure and after-fix native-worker results cover the changed reuse boundary.
Agent review details

How this fits together

OpenClaw reads stored authentication profiles through isolated SQLite child processes. A Gateway-owned scope reuses compatible children while each request retains its own database identity, admission, and cleanup checks.

flowchart TD
  A[Authentication profile read] --> B[Resolve effective state directory]
  B --> C[Capture environment and process owner]
  C --> D{Compatible scoped reader?}
  D -->|Yes| E[Reuse child]
  D -->|No| F[Close and replace child]
  E --> G[Validate source and read fresh rows]
  F --> G
Loading

Technical review

Best possible solution:

Keep state-directory normalization at the existing launch owner while preserving distinct-root replacement, fresh per-read admission, and joined shutdown.

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

Yes: current main compares environment keys literally, so alternating an absent OPENCLAW_STATE_DIR with its resolved default replaces the reader. The body records the matching pre-fix real-child failure; this reviewer did not execute it.

Is this the best way to solve the issue?

Yes: using the existing state-directory resolver at launch capture repairs equivalence without adding a competing cache or weakening the other compatibility checks.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 939380f4920c.

Provenance checked

  • src/infra/sqlite-readonly-worker.ts: captureSqliteReadOnlyWorkerLaunch keeps the original intent (600657d: Capture launch facts before queueing or awaited retirement and retain environment, working-directory, broker-owner, and source boundaries.)
  • src/infra/sqlite-readonly-worker.auth.test.ts: environment/source replacement case keeps the original intent (d3d2d2e: Prove real-child reuse, fresh rows, replacement, and lifecycle cleanup for Gateway-owned auth readers.)
  • docs/auth-credential-semantics.md: reusable reader lifecycle keeps the original intent (d3d2d2e: Document lifecycle-owned child reuse while each read retains source admission and closes SQLite handles before returning.)

Testing

Proof path: in-process harness. Added test files: 1.

Security

None.

Evidence

What I checked:

  • Pinned production change: The introduced delta resolves OPENCLAW_STATE_DIR through the existing resolver at launch capture; the remaining environment, working-directory, runtime-generation, transport-owner, and source comparisons remain intact. (src/infra/sqlite-readonly-worker.ts:261, 1f9fdd6c8c29)
  • Current-main necessity: Fetched main has no changes to the three touched files since the merge base and still captures the unnormalized environment. The central optimization is therefore absent from the reviewed current-main context. (src/infra/sqlite-readonly-worker.ts:261, 939380f4920c)
  • Lifecycle provenance: The introducing patch and merged refactor(state): move fixed-read snapshot coordination off the main thread #151829 establish capture before queue admission or awaited retirement, together with replacement for incompatible launch facts. This PR preserves that intent. (src/infra/sqlite-readonly-worker.ts:252, 600657d52843)
  • Real-child regression value: The changed test observes actual spawned children, verifies reuse for equivalent roots, and verifies successful retirement after environment, root, and source changes. The spawn spy delegates to the real implementation; this is meaningful lifecycle coverage rather than a mocked launch predicate. (src/infra/sqlite-readonly-worker.auth.test.ts:292, 1f9fdd6c8c29)
  • Recorded performance and validation: The complete supplied PR body, captured as sourceRevision dc16da07a3d679220df1e325228690151547cc19c49d0f8e8ab0defa94b7e74e, reports a Testbox run using the real source-mode reader and spawn broker with a synthetic 20-profile WAL database. Alternating equivalent roots improved from 752.36 ms to 1.46 ms; the identical-environment control stayed near 1.36 ms. It records the expected pre-fix two-child regression and 18 passing auth-worker tests afterward. These are contributor-recorded results, not reviewer executions or deployed Gateway latency. (1f9fdd6c8c29)
  • Admission and storage compatibility: The prepared auth reader retains pre-read and post-await authority checks, and the child validates physical database identity around each read. The patch changes only captured process-launch facts and adds no stored format, schema, migration, credential-selection, or permission contract. (src/agents/auth-profiles/sqlite-read.ts:177, 1f9fdd6c8c29)

Likely related people:

  • Peter Steinberger: Raw commit 600657d adds src/infra/sqlite-readonly-worker.ts:229 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 600657d52843; files: src/infra/sqlite-readonly-worker.ts)

PR surface

Source +5, Tests +9, Docs +3. Total +17 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 1 6 1 +5
Tests 1 15 6 +9
Docs 1 3 0 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 24 7 +17

Review metrics

Metric Value Why it matters
Recorded test cost 18 tests passed in 215.19 s wall time The body attributes most duration to cold compiled-subprocess preparation and explains why real process-lifecycle coverage is needed.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded reader-startup optimization with measured benefit and no established urgent user-facing failure.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-08T07:25:46.784Z sha 1f9fdd6 :: needs maintainer review before merge. :: none

@steipete
steipete marked this pull request as ready for review October 8, 2026 07:27
@steipete
steipete enabled auto-merge (squash) October 8, 2026 07:30
@steipete
steipete merged commit a066127 into main Oct 8, 2026
199 of 200 checks passed
@steipete
steipete deleted the steipete/perf-micro-auth-profiles-read-cost-20260919 branch October 8, 2026 07:41
RomneyDa pushed a commit that referenced this pull request Oct 8, 2026
Backport main's lighter CLI imports, schema/proxy/temp-root boundaries, and
reader identity normalization to the October release. Preserve the release
Gateway request executor and strict malformed-PID cleanup behavior.

Backport of #166657, #166722, and #167024 to release/2026.10.1.

(cherry picked from commit 7875352)
(cherry picked from commit 87f2a98)
(cherry picked from commit a066127)

Proof: 715 focused/sibling tests pass; one optional socat skip. The equivalent
root regression fails against the original worker. Fresh P0-P2 review clean.
No dependency, version, schema, permission, or performance-budget changes.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XS 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