Skip to content

perf(state): keep plugin and GitHub reads off the writer queue - #173534

Merged
steipete merged 5 commits into
mainfrom
steipete/perf-micro-writer-flood-other-classes-20260919
Oct 16, 2026
Merged

steipete merged 5 commits into
mainfrom
steipete/perf-micro-writer-flood-other-classes-20260919

Conversation

@steipete

@steipete steipete commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Uncached plugin-state reads and GitHub publication status queries occupy the shared SQLite writer queue during startup and UI reconnects, delaying unrelated writes and attachment metadata.

User Impact

Plugin-state and GitHub discovery reads stop delaying unrelated SQLite writes during reconnects. The measured GitHub-options cold-start timeout regression remains an explicit limitation below; this PR does not claim all RPCs are faster. No configuration or schema migration is required.

Why This Change Was Made

Move the five pure plugin-state reads (lookup, lookupMany, entries, key-range entries, count) and the GitHub publication read registry to the existing shared-state reader pool. Remove their writer registrations and dispatch branches. Plugin reads still observe preceding namespace mutations; mutations retain FIFO ordering. Overlapping reads do not reserve writer positions. Comparison observations and actual mutations remain with the writer, including their authority checks.

The runtime delta is +69 lines: the GitHub portion removes 11 lines; the plugin cutover adds 80 because typed error envelopes, missing-store behavior, and namespace-cache publication must cross the reader transport. The retired writer read path is deleted. No schema, configuration, cache, or timer is added.

Attribution

  • execute includes the generic GitHub publication read operations used by status discovery and reconciliation. Reconciliation starts immediately and repeats every minute; UI discovery also invokes those reads per session.
  • plugin_state included uncached keyed reads and catalog snapshots as well as real persistence. This change removes the pure reads from that class; actual catalog persistence and compound/compare operations remain writes.
  • githubRepository included the personalPending read called by sessions.github.options. That old writer command is removed; the existing publication read registry now owns it.

Coarse production request-class metrics and logs cannot assign exact operation counts to individual callers. The comparison below isolates these paths through real Gateway RPCs with synthetic state.

Measurement

Baseline source: 2aca37525ff0804790c29d9ab6fea1bb9e5f700e. Measured reader-cutover source: 735f802912798910e01a1eaff00a214d87ac33dc. The subsequent repair narrows the writer type contract and migrates one missed test caller; the measured reader path is unchanged. Both use the same final benchmark driver. Each run starts from independently generated state: 5,000 sessions, 6,000 retained runs, 200 approvals, 100 cron jobs, 12 projects with real worktrees, and a 4,641,595,392-byte agent database. All accounts, tokens, sessions, and model responses are synthetic.

The driver pairs 150 devices in batches before the measured crash, holds 30 real agent requests, kills its own Gateway, then starts all 150 reconnect clients concurrently. It polls session/sidebar, catalog, project, and GitHub-option RPCs for five minutes from restart spawn. Connection refusals/retries and RPC errors stay in the results. The synthetic catalog exercises real plugin-state lookup and session metadata without provider scans or external network latency.

node --import ./scripts/tsx.mjs scripts/perf/team-shape-fixture.ts --state-dir "$STATE_DIR" --transcript-mib 1500
node --import ./scripts/tsx.mjs scripts/perf/post-restart-burst-measure.ts --state-dir "$STATE_DIR" --clients 150 --runs 30 --seconds 300 --writer-reads --port 42340 --mock-port 42341

Five-minute target-class writer queue results:

Request class Before requests After requests Before queue wait After queue wait
execute 7,988 1 110.966 s 0.000012 s
plugin_state 7,710 0 202.102 s 0 s
githubRepository 7,987 0 191.606 s 0 s
Total 23,685 1 504.674 s 0.000012 s

All 150 clients connected in both runs. Readiness was effectively unchanged (20.491 → 20.577 s). Successful RPCs increased from 31,953 to 32,095; total RPC errors fell from 151 to 55. HTTP 503 connection refusals before successful retries were 165 → 41. An unchanged-baseline repeat produced 470.019 s of target writer wait and 23,553 target requests.

RPC Before p50 / p99 After p50 / p99 Before → after errors
sessions.list 11.6 / 195.9 ms 18.3 / 124.2 ms 0 → 0
sessions.catalog.list 19.8 / 438.1 ms 24.3 / 131.0 ms 149 → 0
projects.list 17.0 / 203.3 ms 25.2 / 131.7 ms 0 → 0
sessions.github.options 70.0 / 1324.9 ms 86.0 / 2879.5 ms 2 → 55

Adverse result and follow-up: GitHub-options cold-start latency/timeouts worsened in the final run. All 55 timed-out calls started before 25 seconds from restart; none timed out after the initial burst. Clients also began polling earlier (first-150 polling-start median 29.50 → 26.91 s). The repeated baseline had one GitHub timeout, so this is not dismissed as proven noise. The catalog errors were initially empty metadata results.

A separate, temporary stage trace on final code using the reused synthetic fixture located its observed timeout in session preparation (6,227 ms), before publication reads began. Other traced slow calls spent about 1,850 ms in session preparation; personal-pending reads took at most 6 ms, shared-publication reads 273 ms, and identity discovery 52 ms. This identifies a remaining cold-session readiness bottleneck, but the different diagnostic run does not conclusively attribute all 55 original timeouts. No diagnostic instrumentation is included in this PR. The change removes target writer contention; it does not claim a universal RPC latency improvement. Medians increased in this run even where p99 improved.

The scrape occurs at five minutes from restart spawn. Counters cover events observed after exporter initialization; work still waiting at the cutoff is counted only when it starts. This is a cold-start comparison, not a statistical latency study or a production deployment claim.

Evidence

Focused local files passed with one worker: plugin-state-worker (20 tests), plugin-state-publication (15), plugin-state-store (23), shared-state summary (5), shared-state imports (6), GitHub pending-publication (6), and persisted session-list worker (3). Changed-file formatting/lint and diff checks passed. Broad validation belongs to PR CI.

The plugin regression fails on old routing with five writer requests, then passes with five reader requests and zero writer requests while preserving prior-write visibility. The GitHub regression fails on old routing when writer dispatch is unavailable, then passes after the reader cutover. Existing quarantine, corruption, cache invalidation, and authority tests remain in force.

CI and review caught and drove repairs for stale cache-dispatch assertions, a contract import cycle, quarantine error classification, the worker-entry boundary, and one remaining test caller of the retired writer read. That session-list test failed before its caller migration and passes afterward. The shared writer type now excludes all five read operations. The final dispatcher lives in the existing worker module; no guard allowance was added.

Independent subagent review (autoreview route unavailable) found no actionable P0/P1/P2 findings, including the CI repairs and final writer-contract/caller repair. Operator configuration was not changed. No Testbox/Crabbox lease was used. Runtime benchmark builds ran only in the isolated Linux sandbox. Local validation used focused test files and changed-file lint/format. An initial lint invocation entered dependency-artifact preparation and was stopped; the corrected core-only lint passed. No local test suite or standalone repository-wide typecheck/build was run.

Final CI

CI run 38826388682 passed on final head df6ff99bf4a107f472a127a20b060cb1471a7bd7, including the test shards, architecture checks, production/test types, lint, builds, PostgreSQL conformance, and SQL ratchet. The final contract/caller repair independently passed the persisted session-list worker file (3 tests) and plugin-state worker file (20 tests), changed-file lint/format, and independent review.

The PR-description check initially rejected the nonstandard “Proof” heading. The body was corrected to the required “Evidence” heading, and its replacement check passed on the same head. Earlier-head CI caught the source repairs documented above and had two pre-checkout action-download failures; final CI has no failed shards. No CI rerun or branch update was requested to chase green.

The benchmark sandbox has been removed after verifying all task processes stopped. Cold-session GitHub-options readiness remains the explicit performance gap described above; the separate diagnostic does not conclusively explain the final measured timeout increase. No user-profile code or production state was changed.

Route five pure plugin-state operations and GitHub publication queries through the existing shared-state reader pool. Preserve mutation ordering, read-after-write visibility, authority checks, and typed failures; remove the retired writer handlers.
@clawsweeper

clawsweeper Bot commented Oct 15, 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 15, 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-15T23:58:57.812833Z df6ff99 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 gateway Gateway runtime size: L labels Oct 15, 2026
Add an opt-in synthetic plugin metadata and GitHub options workload to the existing owned Gateway restart driver. Capture authenticated Prometheus queue totals at five minutes and document its observation limits.
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Oct 15, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6fdac91c67

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 15, 2026
@clawsweeper

clawsweeper Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR moves pure plugin-state and GitHub publication reads from the shared writer queue to the existing reader pool.

Example: A reconnect reads plugin namespace restart-catalog while unrelated writes are queued.

  • Before: An uncached metadata lookup occupies the shared writer queue.
  • After: The lookup uses the reader pool after preceding namespace mutations settle.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The production approach is useful and has focused worker coverage, but an existing caller still targets the removed route.
Proof confidence 🦐 gold shrimp (3/6) The ordinary proof gate is waived for this maintainer-authored PR; supplied evidence covers focused worker tests, while the Gateway reconnect comparison remains unpublished.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Startup and reconnect state reads compete with unrelated writes on the shared SQLite writer queue.
Reason: The maintainer-directed change removes unnecessary writer contention through an existing reader boundary without adding a production setting or persistence owner.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep this PR open: the reader cutover is useful, but one remaining writer caller breaks an existing session-list test.

Priority: P2
Reviewed head: 735f802912798910e01a1eaff00a214d87ac33dc

Before merge

  • Migrate the remaining direct plugin lookup to the reader API (P2) - The session-list persistence test still calls runOpenClawStateWorkerOperation with pluginState.lookup at src/gateway/server-methods/sessions-list-persisted-worker.test.ts:252. This guard now rejects that command, and no writer handler replaces it, so the test rejects instead of returning the stored true value. Migrate that caller to the plugin-state reader facade and narrow OpenClawStateWorkerOperations to exclude PluginStateReadType so the retired route cannot remain type-valid. This also completes the caller cutover required by root AGENTS.md.

Findings

  • [P2] Migrate the remaining direct plugin lookup to the reader API — src/plugin-state/plugin-state-worker-contract.ts:249

Tests

  • Missing end-to-end proof: The planned shipped-Gateway reconnect comparison has no published result.
Agent review details

How this fits together

Gateway and plugin callers submit typed state requests; reader workers return committed rows, while the existing writer owner retains mutations, admission, and publication receipts.

flowchart TD
  A[Gateway and plugin callers] --> B[Typed state facade]
  B --> C[Namespace write settlement]
  C --> D[Shared reader pool]
  B --> E[Shared writer queue]
  D --> F[Canonical state database]
  E --> F
Loading

Technical review

Best possible solution:

Complete the reader cutover by migrating the remaining session-list test caller and excluding pure reads from the shared writer contract.

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

Source inspection establishes that the existing session-list test submits a command rejected by the new writer guard; no target code or tests were executed during this read-only review.

Is this the best way to solve the issue?

Reusing the existing reader pool and namespace settlement owner is appropriate; completing the caller and type-contract migration is preferable to restoring a parallel writer read path.

Full review comments:

  • [P2] Migrate the remaining direct plugin lookup to the reader API — src/plugin-state/plugin-state-worker-contract.ts:249
    The session-list persistence test still calls runOpenClawStateWorkerOperation with pluginState.lookup at src/gateway/server-methods/sessions-list-persisted-worker.test.ts:252. This guard now rejects that command, and no writer handler replaces it, so the test rejects instead of returning the stored true value. Migrate that caller to the plugin-state reader facade and narrow OpenClawStateWorkerOperations to exclude PluginStateReadType so the retired route cannot remain type-valid. This also completes the caller cutover required by root AGENTS.md.
    Confidence: 0.99
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 3f99631b7ea2.

Provenance checked

  • Plugin-state read scheduling changes intended behavior with a stated reason (2ff1f93: Move Promise-based keyed operations off the calling thread while preserving storage semantics and ordering.)
  • GitHub publication read scheduling changes intended behavior with a stated reason (c5ccf14: Consolidate publication lifecycle operations and reads through the shared worker and remove duplicate reader dispatch.)
  • Plugin namespace ordering and cached observations keeps the original intent (2cd5dea: Coordinate preceding namespace mutations through the existing settlement owner.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/gateway/server-methods/sessions-list-persisted-worker.test.ts --maxWorkers=1
  • pnpm test src/plugin-state/plugin-state-worker.test.ts --maxWorkers=1
  • node scripts/check-changed.mjs --dry-run -- src/gateway/server-methods/sessions-list-persisted-worker.test.ts src/plugin-state/plugin-state-worker-contract.ts src/state/openclaw-state-worker-contract.ts
  • git diff --check

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 2cd5dea adds src/plugin-state/plugin-state-worker-client.ts:69 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 2cd5dea12c86; files: src/plugin-state/plugin-state-worker-client.ts)

PR surface

Source +69, Tests +61, Docs +14, Other +55. Total +199 across 24 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 16 200 131 +69
Tests 6 143 82 +61
Docs 1 15 1 +14
Config 0 0 0 0
Generated 0 0 0 0
Other 1 59 4 +55
Total 24 417 218 +199

Review metrics

Metric Value Why it matters
New benchmark flag --writer-reads Adds an opt-in synthetic reconnect workload and writer queue metrics capture without changing product configuration defaults.

Labels

Label changes:

  • add P2: A useful internal performance improvement has a concrete, limited test-suite regression requiring a focused repair.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: A useful internal performance improvement has a concrete, limited test-suite regression requiring a focused repair.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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 15, 2026, 7:37 PM ET / 23:37 UTC.

@steipete
steipete merged commit 6574349 into main Oct 16, 2026
148 of 149 checks passed
@steipete
steipete deleted the steipete/perf-micro-writer-flood-other-classes-20260919 branch October 16, 2026 00:15
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
…law#173534)

* perf(state): keep plugin and GitHub reads off the writer queue

Route five pure plugin-state operations and GitHub publication queries through the existing shared-state reader pool. Preserve mutation ordering, read-after-write visibility, authority checks, and typed failures; remove the retired writer handlers.

* test(perf): measure writer reads during reconnect bursts

Add an opt-in synthetic plugin metadata and GitHub options workload to the existing owned Gateway restart driver. Capture authenticated Prometheus queue totals at five minutes and document its observation limits.

* fix(state): finish plugin reader contract cutover

* fix(state): preserve plugin reader admission errors

* fix(state): exclude pure plugin reads from writer contract
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant