Skip to content

perf(infra): reuse SQLite readers in detached Gateway callbacks - #155779

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-readonly-session-child-churn-20260919
Sep 22, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-readonly-session-child-churn-20260919

Conversation

@steipete

@steipete steipete commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Detached Gateway connection and scheduled callbacks lose the reusable SQLite reader scope. After auth-row invalidation, model resolution starts and closes a fresh Node child for every read.

User Impact

Repeated model resolution after auth bookkeeping avoids child startup overhead. No configuration, schema, credential selection, retention, or update behavior changes. Doctor/update inspection and the existing process isolation remain intact.

Why This Change Was Made

Carry only the existing read-only worker scope through connection work, scheduled runs (cron, heartbeat, and hooks), and lazy cron/hook construction. Captured owners reject callbacks after shutdown and cannot borrow another Gateway's scope. The existing scope still owns FIFO, launch compatibility, fresh read admission, and child cleanup. The session spawner also reports admitted children through the existing process-spawn counter; it previously bypassed that counter. The counter stays in a transport-free module so reader entry points preserve the spawn broker's lazy boundary.

The auth child intentionally remains a process so SQLite reads can coexist with the memory publication worker. Its open uses readOnly: true, checks the schema version, reads auth rows, and closes handles; it does not run integrity validation or update the host verification record. Ordinary cron-store loads already use the shared-state worker. The separate artifact-preserving cron inspection path launches sync, not the observed session mode.

Evidence

Before/after measurements on Blacksmith Testbox (blacksmith-testbox, profile openclaw-check, lease tbx_01m34k1kqp9pk8cqhr7x87vjsf), Node 24.19.0, source runtime, synthetic SQLite auth database. A temporary probe ran real resolveTieredModel with a fixture provider hook through direct, connection, and scheduled entry points. Model fields and selected auth profile/mode matched the golden fixture throughout. Auth bookkeeping invalidated persisted rows before each measured resolution.

Entry point, 100 invalidated resolutions Before children After new children Before ms/resolution After ms/resolution
Detached connection 100 0 253.69 20.28
Detached scheduler 100 0 192.05 15.75
Direct inherited scope, control 0 0 29.35 23.47

One initial child served all 600 candidate resolutions, including the cache-hit controls. End-of-probe parent RSS was 667 MB before / 517 MB after; this short fixture run is not a production memory claim. Launch stacks identified runSqliteAuthProfileWorker → createScopedSqliteReadOnlyWorker → createSqliteReadOnlyWorkerSession. Cron timers explicitly detach their async context, explaining why startup-created scope reuse did not cover those calls.

Remote runs on the same lease (Testbox runner):

  • Temporary model probe: passed before and after using node scripts/run-vitest.mjs src/agents/embedded-agent-runner/model.child-churn.lane115.test.ts --pool=forks --testTimeout=240000; 55.48 s / 11.34 s test time. The temporary benchmark was removed after measurement.
  • Focused proof: node scripts/run-vitest.mjs src/infra/sqlite-readonly-worker.auth.test.ts src/infra/sqlite-readonly-worker-session.test.ts src/gateway/server-cron-lazy.test.ts src/gateway/scheduled-run-gateway-context.test.ts src/gateway/server-connection-work.test.ts src/gateway/server-runtime-state.test.ts --maxWorkers=1: 79 tests passed, 49.27 s runner wall. Existing auth transport tests now prove the same child and fresh rows through detached connection/scheduler callbacks for native, broker, and private-snapshot transports.
  • node scripts/check-changed.mjs: passed all selected typechecks, lint, storage/architecture guards, and zero runtime import cycles. Its default comparison base selected additional UI and Discord checks; these files are not part of the branch diff.
  • pnpm build: passed after the diagnostics import repair (6m 11.5s). It also printed a Control UI startup-gzip budget diagnostic: 370952 B versus a 370876 B threshold, while exiting successfully. No UI files changed.
  • Follow-up check-changed --base HEAD -- <five import-cutover production files> passed core types and 13 core-test shards before its backing Actions run was cancelled (remote command exit 255; no code failure). Completed proof was retained.
  • Replacement Blacksmith lease tbx_01m34rvgqp3q5x5t8m4sbvtxx2: original-code probes failed exactly as intended in four cases (three children instead of one across native/broker/snapshot transports; no session-spawn diagnostic). After restoring candidate bytes, all 63 tests in the four measured files passed. node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.core.test.other.json --incremental, targeted run-oxlint on the seven import-cutover production/test files, check-import-cycles.ts, and git diff --check all passed. The final command took 187 s. Both leases were stopped.

Per-file cost on the replacement lease, using pnpm test <file> --maxWorkers=1 --reporter=dot: sqlite-readonly-worker.auth.test.ts 33.94 s wall; sqlite-readonly-worker-session.test.ts 6.09 s; server-cron-lazy.test.ts 16.27 s; spawn-utils.test.ts 6.94 s. The auth file includes 13.3 s of cold worker compilation and existing real lost-broker cleanup coverage (about 10 s); actual test time was about 16 s. The added detached-read assertions reuse its existing child fixtures. Resume CI job timing is recorded below.

Setup corrections: the first Testbox invocation found missing synced-checkout dependencies; pnpm install --frozen-lockfile fixed that. The initial model probe used a Vitest thread, where shared-state admission correctly refused a non-host caller; using the fork pool exercised the actual host boundary. Neither was a product failure. The first build then caught an ineffective dynamic import introduced by importing metrics through spawn-utils; moving the existing counter and its consumers to spawn-diagnostics preserves that lazy boundary.

Scope: +49 net production lines (+3 documentation lines), no new result cache. Independent Codex review found no actionable P0–P2 findings. No live Gateway was changed; the synthetic Testbox measurements do not establish the exact production process rate or savings on a 26 GB database.

CI repair and resumed validation

The compact shard failed while importing src/cli/gateway-cli/run-loop.test.ts: connection callback capture eagerly loaded the SQLite worker logger before the fixture logger initialized. The reader scope and capture operation now live in a lightweight context module; all four Gateway consumers use it, while the existing worker retains ownership of admission, FIFO, cancellation, and child cleanup. The interrupted repair was preserved and completed.

The other two failures were upstream defects already fixed on main: memory candidate-repair synchronization in #155745, and the Windows checkout fixture's duplicate PID-file publication in #154720. This branch incorporates those fixes by rebase; it adds no duplicate repair.

Blacksmith Testbox lease tbx_01m356v8b9x0y31h1eqyf9p8q4 (run):

  • Pure main 065eb1f58f13c5355be49edd113f82f22bc86f1d: all 218 CLI-loop tests passed (63.15 s runner wall), plus all 3 memory candidate-repair tests (34.99 s).
  • Repaired candidate: node scripts/run-vitest.mjs src/cli/gateway-cli/run-loop.test.ts src/infra/sqlite-readonly-worker-session.test.ts src/infra/sqlite-readonly-worker.auth.test.ts src/gateway/server-cron-lazy.test.ts src/gateway/scheduled-run-gateway-context.test.ts src/gateway/server-connection-work.test.ts src/gateway/server-runtime-state.test.ts --maxWorkers=1 passed all 297 tests across seven files, 126.50 s total runner wall.
  • Formatting and git diff --check passed. The lease was stopped. No tests, typechecks, or builds ran on the saturated Mac.

Fresh independent AutoReview of the fully staged repair is clean through P2. The repair was folded into one commit with the original subject and rebased without conflicts.

Exact-head CI run 35770030471 passed for edb9902b19d9974977c425154a7ecd9697246360, including openclaw/ci-gate. No job rerun was needed. Previously failing job wall times: compact-small-19 356 s, changed-extensions-bundle-28 298 s, Windows-node-test-2 357 s; these are whole-shard times, not the cost of the added assertions.

Final rebased-candidate proof on Blacksmith Testbox tbx_01m3579138f36dj8qqy3m19z4v (run): node scripts/check-changed.mjs --base HEAD passed all selected checks, including core types, all 25 test-type shards, zero dead exports, zero lint warnings/errors, storage/architecture guards, and zero runtime import cycles. pnpm build passed in 6m 14.1s, including the CLI bootstrap guard, 95 plugin packages, and built control-plane module/Doctor import checks. The combined command took 38m 30s. The build emitted an advisory startup-CSS budget warning while staying within its hard limit; this PR changes no UI files.

The raw Testbox checkout deliberately retained the main Git base with the candidate applied as a working-tree delta. An initial HEAD-only assertion stopped before validation; the corrected preflight verified the exact base, all 16 changed paths, and every changed file's SHA-256 against the pushed commit before running proof. Both task leases were stopped after use.

@clawsweeper

clawsweeper Bot commented Sep 22, 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 gateway Gateway runtime size: M maintainer Maintainer-authored PR labels Sep 22, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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 22, 2026
@clawsweeper

clawsweeper Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 22, 2026, 3:00 PM ET / 19:00 UTC (Revision 2).

ClawSweeper review

What this changes

Preserves reusable SQLite reader processes across detached Gateway callbacks and includes their launches in existing process diagnostics.

Merge readiness

✅ Ready for maintainer review

The change remains useful: fetched main still loses reader reuse across detached callbacks. No actionable correctness or security defects were found, and the supplied production-path measurements support the improvement.

Priority: P2
Reviewed head: edb9902b19d9974977c425154a7ecd9697246360

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused lifecycle repair with useful measured runtime evidence and no blocking findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The captured Testbox evidence exercises real model resolution and SQLite child processes through detached connection and scheduler entrypoints, showing eliminated repeated launches with unchanged model/auth results and fresh rows. Transport regressions supplement that evidence; no stored-data contract changes require migration proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured Testbox evidence exercises real model resolution and SQLite child processes through detached connection and scheduler entrypoints, showing eliminated repeated launches with unchanged model/auth results and fresh rows. Transport regressions supplement that evidence; no stored-data contract changes require migration proof.
Evidence reviewed 8 items Pinned change ownership: Reviewed the merge-base-to-head delta from ab4c2cd to edb9902. Base-only CI test changes were excluded from attribution.
Still needed on fetched main: Fetched main preserves the spawn broker in connection work and scheduled runners but does not capture the SQLite reader scope. The earlier merged implementation at #152266 supplies reusable readers, leaving this detached-callback gap.
Captured lifetime remains isolated: The capture helper restores only the reader carrier, exits an unrelated reader scope when no owner was captured, and rejects inactive or aborted owners before invoking callbacks. It does not capture startup admission or request identity.
Findings None None.
Security None None.

How this fits together

The Gateway reads stored authentication rows when resolving models for connections and scheduled work. Its reader scope owns reusable child processes while each request independently acquires database admission and reads fresh rows.

flowchart TD
  A[Connection callbacks] --> C[Captured Gateway reader scope]
  B[Scheduled callbacks] --> C
  C --> D{Owner still active?}
  D -->|No| E[Reject late callback]
  D -->|Yes| F[Reusable reader process]
  F --> G[Fresh database admission and rows]
  G --> H[Model resolution]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +49, Tests +107, Docs +3. Total +159 across 16 files.

View PR surface stats
Area Files Added Removed Net
Source 11 138 89 +49
Tests 4 115 8 +107
Docs 1 3 0 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 16 256 97 +159

Review metrics

Metric Value Why it matters
Production versus test growth Production +49 net lines; tests +107; docs +3 Growth implements scope capture and diagnostic integration with focused regression coverage; the current delta exceeds the body's older +37 production estimate.

Technical review

Best possible solution:

Keep reader reuse with the existing Gateway lifecycle owner while preserving per-read admission, fresh rows, and joined shutdown cleanup.

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

Yes: fetched main's detached callbacks omit the reader scope, causing unscoped auth reads to create and close children. The supplied before/after Testbox runs demonstrate that mechanism; this review did not execute it locally.

Is this the best way to solve the issue?

Yes: carrying the existing reader scope through the owning callback boundaries repairs reuse without adding another cache, changing credential selection, or retaining startup authority.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 097cd998a151.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Removes repeated child startup overhead during model resolution without changing configuration or stored-data contracts.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The captured Testbox evidence exercises real model resolution and SQLite child processes through detached connection and scheduler entrypoints, showing eliminated repeated launches with unchanged model/auth results and fresh rows. Transport regressions supplement that evidence; no stored-data contract changes require migration proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured Testbox evidence exercises real model resolution and SQLite child processes through detached connection and scheduler entrypoints, showing eliminated repeated launches with unchanged model/auth results and fresh rows. Transport regressions supplement that evidence; no stored-data contract changes require migration proof.

Evidence

What I checked:

  • Pinned change ownership: Reviewed the merge-base-to-head delta from ab4c2cd to edb9902. Base-only CI test changes were excluded from attribution. (edb9902b19d9)
  • Still needed on fetched main: Fetched main preserves the spawn broker in connection work and scheduled runners but does not capture the SQLite reader scope. The earlier merged implementation at perf(auth): avoid per-turn auth reader spawns on Gateways #152266 supplies reusable readers, leaving this detached-callback gap. (src/gateway/server-connection-work.ts:11, 097cd998a151)
  • Captured lifetime remains isolated: The capture helper restores only the reader carrier, exits an unrelated reader scope when no owner was captured, and rejects inactive or aborted owners before invoking callbacks. It does not capture startup admission or request identity. (src/infra/sqlite-readonly-worker-context.ts:28, edb9902b19d9)
  • Fresh admission and shutdown preserved: The existing reader owner serializes auth reads, compares launch environment and transport ownership, and joins pending work and child cleanup. The child reacquires its database lease and checks physical identity for each request; reusing the process does not reuse an authorization grant or open database handle. (src/infra/sqlite-readonly-location.worker.ts:244, edb9902b19d9)
  • Real behavior evidence: The captured PR body, sourceRevision 626e35cffbf5503b365520d09ce8fa5636e013778f141a7d30789c26594cb519, records Node 24.19.0 Testbox runs through real model resolution with synthetic SQLite auth data. For 100 invalidated resolutions, detached connection and scheduler paths each went from 100 child launches to zero additional launches; one initial child served all 600 candidate resolutions while selected model and auth fields matched the fixture. Reported latency changed from 253.69 to 20.28 ms and 192.05 to 15.75 ms respectively. These are fixture measurements, not production-scale savings. (edb9902b19d9)
  • Regression coverage and validation: The auth transport tests delegate to real native or broker child processes and verify fresh rows, one child across detached callbacks, and shutdown cleanup across three transport cases. The body reports original-code failures for all three cases and the missing diagnostic, followed by 63 passing tests, targeted checks, and a successful build. This reviewer ran no tests; the read-only diff check passed and the checkout remained clean. (src/infra/sqlite-readonly-worker.auth.test.ts:172, edb9902b19d9)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Marvinthebored: 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 (1 earlier review cycle)
  • reviewed 2026-09-22T14:55:25.759Z sha 5cf37af :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the steipete/perf-micro-readonly-session-child-churn-20260919 branch from 5cf37af to edb9902 Compare September 22, 2026 18:52
@steipete
steipete merged commit 43d85e5 into main Sep 22, 2026
198 checks passed
@steipete
steipete deleted the steipete/perf-micro-readonly-session-child-churn-20260919 branch September 22, 2026 19:34
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

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 gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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