Skip to content

perf(sqlite): prevent runtime lease checks from stalling Gateway requests - #184586

Merged
steipete merged 6 commits into
mainfrom
steipete/perf-micro-main-sync-fs-under-writeback-20260919
Oct 26, 2026
Merged

steipete merged 6 commits into
mainfrom
steipete/perf-micro-main-sync-fs-under-writeback-20260919

Conversation

@steipete

@steipete steipete commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes Gateway stalls during disk writeback when MCP config changes, personal GitHub credential updates, transcript exports, recovery cleanup, or periodic WAL maintenance verify SQLite ownership. Follow-up to #184275: these callers still used native lease verification, and cleanup-client opening and worker publication repeated synchronous identity checks.

User Impact

Slow SQLite ownership filesystem reads no longer block unrelated Gateway requests in these flows. Original ownership loss still refuses new effects; accepted writes retain settlement authority. No schema, configuration, or public SDK changes.

Why This Change Was Made

Migrate runtime callers to the existing async lease and heartbeat owners, retaining original context through staging and final publication. Resolve runtime ownership paths asynchronously. Cleanup and lease requests carry their original file identity and birthtime to the existing worker guard, including identity published by cold acquisition. Conflicting bindings refuse; accepted settlement and sibling clients sharing an actor remain intact.

The heartbeat retains its original Gateway owner and freshly verifies custody within the existing request deadline. Its worker verifies the original database before verification, renewal, and contention fallback. Close-checkpoint diagnostics await filesystem inspection and recheck original cleanup authority before publication. Periodic WAL carries identity through existing-only opening and execution; warm descriptor retention and worker publication reuse existing admitted facts. Cold alias reconciliation and native bootstrap/CLI/SDK contracts remain.

Plugin/package and project/worktree runtime callers are separate follow-ups. This PR does not claim to eliminate every synchronous filesystem operation in the Gateway.

Evidence

Predeclared owner benchmark: 10,000 retained lease keys across 40 synthetic scopes; 2,000 warmed effect checks per arm, five alternating native/async pairs. CPU and sampled allocation use separate unwrapped passes; counts and the injected 20 ms filesystem-delay probe are separate. Final measurements include all ownership fixes. One-minute host load ranged 16.2–19.3.

Held-lease measurement Native median Async median Mean paired change
Main-thread CPU / 2,000 checks (ms) 273.681 79.112 -195.858 (-70.8%)
Total process CPU / 2,000 checks (ms) 326.310 489.356 +151.766 (+45.7%)
Main-thread sampled allocation / check (B) 50,534.612 11,857.208 -38,636.305 (-76.6%)
Total sampled allocation / check (B) 50,545.328 45,270.064 -5,243.243 (-10.4%)
Host synchronous FS calls / 2,000 checks 40,000.000 0.000 -40,000.000 (-100.0%)
Main-thread heartbeat delay with injected FS latency (ms) 523.760 0.068 -526.137 (-100.0%)

All five pairs reduce main-thread CPU and allocation, and all five increase total process CPU. The process CPU cost is about 76 µs/check: fresh verification moves to workers while retaining fail-closed ownership. This is an explicitly requested responsiveness repair, not a throughput improvement. Under injected storage delay, unrelated main-thread work proceeds without waiting for filesystem verification. Earlier measurements that omitted the final authority checks are superseded.

This measures verification inside a held lease, not capture/release or whole-Gateway throughput. The real MCP regression separately covers acquisition, staging, publication, and release; it failed on the base with 20 host owner-file reads. Additional regressions failed before the final owner fixes: cold database replacement was accepted, held Gateway replacement allowed an effect, warm retains performed two stats, and periodic WAL repeated host identity reads. The fixed tests cover zero host WAL identity reads, physical replacement, deadline cancellation with no late dispatch, accepted settlement, sibling reuse, and cold alias reconciliation. Close-checkpoint fault injection covers delayed inspection, file replacement, and revoked cleanup custody.

Reproduce: node --expose-gc --import ./scripts/tsx.mjs scripts/perf/sqlite-native-lease-measure.mjs [--baseline] --iterations 2000 --delay-ms 20.

No Team or production server was used. This follows the requested owner fast path; no whole-Gateway p99, GC, RSS, or stress result is claimed.

Runtime production delta: +697/−309, net +388 lines. Necessary growth preserves existing authority across asynchronous boundaries, deadline/cancellation, and per-client physical binding. Migrated callers remove their native runtime lease path; no new cache or parallel fast path. Benchmark tooling adds 248 lines separately. The simplification retains existing admission, heartbeat, and settlement owners; synchronous public/native callers retain their existing contract.

Focused validation: the final consumer run passed 121 tests in 5 files (read admission, WAL, MCP, GitHub OAuth, transcripts); heartbeat proof passed 37 tests in 4 files; the preceding WAL/admission/async-lease run passed 45 tests in 3 files. Earlier runtime/cleanup/close-checkpoint proof passed 240 tests in 15 files, with additional focused OAuth/identity coverage. Targeted core typecheck, scoped lint/format, one-page MDX sanity, and diff checks passed. Both import-closure files passed (26 tests).

Independent subagent review (autoreview route unavailable), including the final physical binding, heartbeat deadline, and cold-alias corrections, found no remaining actionable P0–P2 issues. A too-broad early identity gate blocked settlement; the final boundary checks new effects while permitting accepted work to settle. No schema or retention changes.

CI and follow-up validation

CI run 40341514714 on 027d43735fede8fc6e7f0d2ce4be92776383e788 completed with 71 successful jobs, 24 skipped jobs, and three failed test jobs plus the aggregate gate. All prior admission, retained-read, alias lifecycle, typed lease-loss, and profiler failures passed; all PostgreSQL conformance shards passed. Earlier CI exposed real physical-binding and lease-loss notification-order defects, which are repaired and covered by focused regressions. The original Doctor SHM checksum failure reproduced on unchanged main in the earlier run and did not recur here.

Remaining failures in that run were the mocked-UI group-defaults focus assertion, an MCP authorization child exceeding 30 seconds, and update-resume returning a Doctor warning. The exact CI base 8f737e10ef62f393697c72bd605a51941485e26a and candidate each passed the complete MCP file (12 tests) and update-resume file (9 tests). The UI case passed five times on each revision; its mocked Gateway does not load this PR's SQLite/runtime code. The process tests do reach changed code, so passing replays are not claimed as inherited-failure proof or a fix.

The MCP fixture bypassed the existing compiled-child owner and cold-loaded raw TypeScript with tsx inside its 30-second deadline. It now declares and resolves the same production authorization entry through the existing prepared-module owner. The cross-process lifetime, disposal, error/exit assertions, and deadline remain unchanged. On this Mac the case fell from 10.977 s to 2.697 s; this measures removed fixture work, not proof of the CI timeout's cause. Failure diagnostics retain synthetic child stdout, and the update harness now includes its complete synthetic result when its unchanged success assertion fails. The Doctor warning remains unclassified.

After this fixture repair, both complete process files pass (21 tests), both import-closure files pass (26 tests), and scoped lint/format pass. Independent subagent review (autoreview route unavailable) is clean. No CI reruns, deadline increases, assertion relaxations, or Team operations were used. Final exact-head CI is recorded below.

Current reviewed head: 474b1f278e76f276996283833eb6e42261cfd479, rebased onto 5089aa71b681. All 75 code/docs/test files are byte-identical to reviewed pre-rebase source; the mock-export baseline also retains upstream removals. Run 40349088993 completed successfully on this exact head: 77 successful jobs and 24 skipped, including all PostgreSQL shards, all UI shards, and the previously failing MCP/update-resume jobs. The exact-run watcher exited 0. Earlier unexplained intermittent failures are retained above; this passing run is not claimed as a diagnosis of them.

@clawsweeper

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-26T16:32:07.936773Z 474b1f2 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts commands Command implementations agents Agent runtime and tooling size: XL labels Oct 26, 2026
@github-actions

github-actions Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 474b1f278e76f276996283833eb6e42261cfd479
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/gateway/github-personal-oauth.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/infra/client-credential-async.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 26, 2026
@clawsweeper

clawsweeper Bot commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR moves runtime lease verification and cleanup identity checks off the Gateway thread while preserving final ownership guards.

Example: Update an MCP server's tool selection while ownership filesystem reads are slow.

  • Before: Synchronous ownership reads can stall unrelated Gateway requests.
  • After: Ownership verification is awaited through existing workers before guarded config publication.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful, coherent owner reuse with substantial boundary regressions, but the credential-rotation authority composition lacks final-effect proof.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦐 gold shrimp (3/6) Security review found an item that needs attention.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Slow disk metadata reads during ownership verification can freeze unrelated Gateway requests.
Reason: The maintainer-authored direction addresses an established responsiveness problem through existing owners, with the remaining plugin and project migrations explicitly outside scope.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep open: this maintainer-directed follow-up addresses remaining synchronous ownership checks on main, and no definite introduced code defect was found.

Priority: P2
Reviewed head: 8dc8132f3213ac21693643a18afeb9823deb6371

Before merge

  • Add real behavior proof - Authority-chain proof required: the MCP, transcript, and cleanup regressions exercise actual persistence or filesystem outcomes, but personal GitHub RPC tests mock refreshGitHubOAuthToken and bypass its changed authority callback. Supply a production-path trace through the real lifecycle and OAuth client showing allowed dispatch and rejection after disconnect or reassignment before network I/O; redact credentials and private endpoints. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Resolve security review attention item - No concrete bypass was established, but composed authority evidence for outbound personal-token rotation remains incomplete.
  • Resolve merge risk - Personal GitHub refresh now awaits lease verification before rotating credentials; rejection of a disconnected or reassigned profile at the final outbound effect remains unverified.

Findings

None.

Tests

  • Missing end-to-end proof: Show the real personal-refresh lifecycle reaching OAuth dispatch for a current profile and refusing dispatch after disconnect or reassignment during delayed ownership verification.
Agent review details

How this fits together

Gateway operations enter the shared-state lease and SQLite admission owners, which authorize credential, config, export, and cleanup effects and retain accepted writes through settlement.

flowchart TD
A[Gateway operation] --> B[Captured state context]
B --> C[Async lease verification]
C --> D[Current owner guard]
D --> E[Filesystem or SQLite effect]
E --> F[Native settlement and cleanup]
Loading

Technical review

Best possible solution:

Retain the existing async lease owners, per-client physical identity binding, and separate settlement authority.

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

Main still routes the migrated callers through native lease verification; source and the submitted baseline regression establish the blocking path, but no target code was executed during this read-only review.

Is this the best way to solve the issue?

Reusing existing async lease, heartbeat, and admission owners is a coherent fix that preserves synchronous SDK contracts and avoids a competing cache or ownership manager.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 9302c1147252.

Merge-risk options

Maintainer options:

  1. Prove refresh authority at dispatch (recommended)
    The PR owner should exercise the real personal-refresh lifecycle and OAuth transport with delayed lease verification, showing an authorized request and no outbound request after disconnect or reassignment.

Provenance checked

  • Runtime lease verification and cleanup keeps the original intent (65bc5f6: Move OAuth persistence and lease lifecycle work into existing workers while preserving original authority and native settlement.)
  • Admitted ownership paths keeps the original intent (10154a2: Reuse canonical paths captured during admission rather than resolving them during every dispatch.)
  • MCP lifecycle serialization keeps the original intent (103e1a4: Serialize MCP ownership and config mutation so rejected or concurrent operations cannot corrupt lifecycle ownership.)
  • Personal GitHub publication keeps the original intent (4c0588d: Bind personal credentials to the authenticated profile and connection generation, invalidating authority on disconnect or replacement.)
  • Automatic recovery cleanup keeps the original intent (fb9e117: Retire eligible recovery copies through the actual state owner, preserving current rollback data and advisory failure semantics.)
  • Worker commit receipt placement keeps the original intent (4a4f9c8: Capture receipt facts once while preserving commit, rollback, and failed-delivery settlement; this PR relocates the helpers without changing that contract.)

Testing

Proof path: in-process harness.

Security

Needs attention: No concrete bypass was established, but composed authority evidence for outbound personal-token rotation remains incomplete.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 05a0dd8 adds src/infra/gateway-state-owner.ts:592 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 05a0dd8ee67f; files: src/infra/gateway-state-owner.ts)
  • Gio Della-Libera: Raw commit 103e1a4 adds src/agents/mcp-lifecycle-lease.ts:4 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 103e1a4cc9de; files: src/agents/mcp-lifecycle-lease.ts)

PR surface

Source +238, Tests +515, Docs +16, Other +248. Total +1017 across 55 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 36 503 265 +238
Tests 16 543 28 +515
Docs 1 16 0 +16
Config 0 0 0 0
Generated 0 0 0 0
Other 2 249 1 +248
Total 55 1311 294 +1017

Review metrics

Metric Value Why it matters
Runtime versus regression coverage Runtime +503/−265; tests and support +543/−28 Runtime growth carries async preparation and final ownership guards; the added regressions cover replacement, revocation, settlement, and affected consumers.

Labels

Label changes:

  • add P2: The repair addresses Gateway responsiveness during slow ownership filesystem reads in several bounded runtime flows.
  • add merge-risk: 🚨 security-boundary: The changed asynchronous authority callback precedes remote credential rotation, and composed final-effect revocation evidence is incomplete.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Label justifications:

  • P2: The repair addresses Gateway responsiveness during slow ownership filesystem reads in several bounded runtime flows.
  • merge-risk: 🚨 security-boundary: The changed asynchronous authority callback precedes remote credential rotation, and composed final-effect revocation evidence is incomplete.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Add final-effect proof through the real personal-refresh lifecycle and OAuth client for an authorized profile and for disconnect or reassignment during ownership verification.

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 execution lanes are retired.

Reviewed October 26, 2026, 8:14 AM ET / 12:14 UTC.

@steipete
steipete force-pushed the steipete/perf-micro-main-sync-fs-under-writeback-20260919 branch 4 times, most recently from 76b398d to 027d437 Compare October 26, 2026 14:38
Move MCP mutations, personal GitHub credential publication, transcript exports, recovery cleanup, and borrowed cleanup identity checks through existing async owners. Preserve original custody, physical identity and birthtime, final publication guards, and accepted-write settlement. Resolve runtime owner paths and close-checkpoint diagnostics asynchronously.

Follow-up to #184275. Five alternating 2,000-check owner samples reduced total process CPU by 62% and sampled allocation by 62%; injected slow filesystem heartbeat delay fell from 491 ms to 0.095 ms. Focused behavior, core typecheck, lint, closure checks, and independent review passed.
Retain the same cancellation predicate in synchronous and awaited MCP fixture checks. Expect the broker physical-identity refusal after lease cleanup moved to its existing admission owner, preserving the original database lease-row assertion.
@steipete
steipete force-pushed the steipete/perf-micro-main-sync-fs-under-writeback-20260919 branch from 027d437 to 474b1f2 Compare October 26, 2026 15:24
@openclaw-barnacle openclaw-barnacle Bot added the cli CLI command changes label Oct 26, 2026
@steipete
steipete merged commit e0b550b into main Oct 26, 2026
173 of 176 checks passed
@steipete
steipete deleted the steipete/perf-micro-main-sync-fs-under-writeback-20260919 branch October 26, 2026 15:53
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 27, 2026
…ests (openclaw#184586)

* perf(sqlite): keep runtime lease checks off the Gateway main thread

Move MCP mutations, personal GitHub credential publication, transcript exports, recovery cleanup, and borrowed cleanup identity checks through existing async owners. Preserve original custody, physical identity and birthtime, final publication guards, and accepted-write settlement. Resolve runtime owner paths and close-checkpoint diagnostics asynchronously.

Follow-up to openclaw#184275. Five alternating 2,000-check owner samples reduced total process CPU by 62% and sampled allocation by 62%; injected slow filesystem heartbeat delay fell from 491 ms to 0.095 ms. Focused behavior, core typecheck, lint, closure checks, and independent review passed.

* test(sqlite): align lease fixtures with current ownership guards

Retain the same cancellation predicate in synchronous and awaited MCP fixture checks. Expect the broker physical-identity refusal after lease cleanup moved to its existing admission owner, preserving the original database lease-row assertion.

* fix(sqlite): preserve physical custody through async lease checks

* fix(sqlite): scope captured identity to its admitted lifetime

* fix(sqlite): publish observed heartbeat loss before returning

* test(sqlite): prepare MCP authorization subprocess before its deadline
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling cli CLI command changes commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts security-sensitive-changed size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant