Skip to content

perf(config): speed up validation with large live shared state - #183082

Merged
steipete merged 4 commits into
mainfrom
steipete/perf-micro-config-validate-latency-20260919
Oct 25, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/perf-micro-config-validate-latency-20260919

Conversation

@steipete

@steipete steipete commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

openclaw config validate slows down as unrelated shared-state data grows while a Gateway is running. Reading two plugin-metadata rows was first backing up the entire shared SQLite database.

User Impact

Config validation remains read-only and no longer needs space or time for a full database copy when a verified live Gateway owns the database. No configuration, schema, timeout, or migration changes.

Why This Change Was Made

Use the existing isolated SQLite inspection child and metadata-query owner to read the committed rows in one pinned read transaction. Preserve physical-identity, live-owner, access, schema-version, and parent-admission checks. Offline byte-preserving reads, retained snapshots, and managed schema/maintenance scopes retain their existing paths. Native source handles are closed in the isolated child, not alongside another thread's writer.

Production change: +95 lines in src/ excluding tests. The growth preserves the distinct live-source versus offline/pinned-snapshot contracts; there is no new cache or schema. The live-owner verifier is moved and shared with the existing snapshot owner. Benchmark usage is in its script header; the shared perf README is untouched.

Evidence

Local macOS, Node 26.12.1, baseline d8b07b7e02253e3703c5cbc3caee0a57bcb2e40e. Actual built CLI, synthetic 35 plugin entries, 3 agents, 2 providers/5 models, 10,000 sessions, 6,000 settled runs, and 1 GiB unrelated shared-state payload. A separate isolated loopback Gateway owns the database. No production data or services were used.

Final measurements repeat the reviewed implementation, including typed error propagation: two paired groups of five fresh CLI processes per side, candidate/baseline then baseline/candidate; identical instrumentation and startup metadata. All 20 invocations returned valid config. These local runs are sequential and counterbalanced, not simultaneous pinned-host pairs. The candidate was built before the final unrelated main rebase; affected owner sources did not change during that rebase.

Mean per CLI operation Baseline Candidate Change
Elapsed, group 1 3,596 ms 1,408 ms −60.8%
Elapsed, group 2 3,935 ms 1,397 ms −64.5%
Aggregate elapsed 3,765 ms 1,403 ms −62.7%
Total process-tree CPU 3,912 ms 1,707 ms −56.4%
Instrumented main-process GC 26.94 ms 22.85 ms −15.2%

Elapsed medians: 3,461/3,952 ms baseline and 1,392/1,364 ms candidate. Ranges: 3,311–4,275 / 2,864–5,130 ms baseline and 1,343–1,531 / 1,339–1,501 ms candidate. Baseline timing is noisy on the shared Mac; the candidate remains consistently below 1.54 s. An earlier 20-run paired experiment before the schema-error correction measured 2,957→1,294 ms (−56.3%) elapsed and 3,274→1,581 ms (−51.7%) CPU. The eliminated work is one whole-database backup for the live plugin-metadata read; the regression proves this without timing assertions by refusing snapshot staging with ENOSPC.

Resource context, startup, and limitations
  • GC group 1: 140→129 collections; minor 110→109, 19.80→20.02 ms/op; major 15→10, 4.39→2.94 ms/op; incremental 15→10, 0.48→0.30 ms/op. Maximum pause 2.12→2.64 ms.
  • GC group 2: 140→130 collections; minor 110→110, 22.87→19.47 ms/op; major 15→10, 5.52→2.69 ms/op; incremental 15→10, 0.80→0.27 ms/op. Maximum pause 6.41→2.16 ms. Major-GC counts are below tail-gating minima. V8 metrics cover the instrumented CLI process, not every native helper/worker; /usr/bin/time CPU includes the whole process tree.
  • Event-loop samples total 1,144→178 and 1,119→170 across five processes; candidate processes are below the p95/p99 sample minima. Mean reported p95 is 12.15→12.10 and 12.07→12.33 ms. Reported p99 changes 13.06→557.11 and 12.74→547.62 ms because the much shorter processes retain far fewer idle samples around the same startup pause; these are context only. Maximum delay 651→581 and 1,562→601 ms.
  • Maximum instrumented process RSS: 258.0→283.7 MiB and 256.4→273.2 MiB (about +8.3% across groups). This is the measured memory tradeoff alongside more than halved CPU and a shorter process lifetime.
  • Gateway startup's complete CLI config phase measured 1,102/1,026 ms baseline versus 1,069/1,122 ms candidate; plugin-config subphase 599/552 versus 585/664 ms. Only two starts per build: effectively neutral, not a claimed startup speedup. Startup's retained-snapshot path is preserved.
  • Separate --cpu-prof run shows the baseline main thread mostly waiting (2.18 s idle) while metadata preparation runs; it is not a timing sample. Initial empty-state validation was about 1.2 s and missed the full-copy path.
  • Remote benchmark preparation was abandoned after repeated disk-pressure guard violations. These are authorized local-dev-Gateway results; there is no production latency claim, Linux measurement, or deployed-build verification. Preliminary runs before matching startup metadata are excluded from the final paired table for that build-protocol mismatch.

Reproduce with scripts/perf/config-validate-measure.mjs (header commands), --payload-mib 1024; --profile is a separate traced pass. The fixture's mock model endpoint is not contacted by config validation.

  • Regression: base read-operation path fails on the intended ENOSPC snapshot-allocation error; candidate succeeds with a real separate writer, committed metadata changes, and unrelated payload growth.
  • Focused metadata-reader tests: 15/15 passed, including offline byte preservation and retained snapshots; new regression 477 ms, whole file 10.68 s.
  • PR-wrapper closure tests: 22/22 passed after registering the two new runtime modules. Export-name collision guard passed.
  • Snapshot-owner focused tests: 3/3 passed, covering live-writer checkpoints, offline byte preservation, unknown owners, and replaced physical identity.
  • Core typecheck, changed-file format and lint passed. Full baseline build and candidate runtime performance build passed; startup metadata generated for both.
  • Independent subagent review (autoreview route unavailable): clean at P2. Autoreview preflight rejected the requested provider because it did not match operator configuration; no configuration was changed. Mechanical lint/inventory corrections followed review.
  • CI caught a guarded synchronous writer in benchmark fixture setup. Switched setup to the canonical async writer; synthetic setup completed, the database-worker ratchet passed (170→170 T1 calls; 15→15 compatibility calls), and independent follow-up review was clean. Production and measurement paths are unchanged.
  • Automated review found that the generic child transport dropped typed schema refusals. Fixed with the existing state-error codec inside the metadata read callback, retaining admission phase and native cleanup boundaries. A real live-writer newer-schema regression was red before correction and green afterward; all 15 metadata tests and 22 closure tests passed, and independent follow-up review was clean.
  • CI also caught lost TypeScript narrowing between separate result checks. Nested the discriminant check without casts or behavior changes; core typecheck, changed-file checks, and the live-reader regression then passed. Independent review was clean.
  • PR CI supplies broad validation. No Testbox/Crabbox lease was allocated under the lane's validation policy.

@clawsweeper

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

@steipete
steipete marked this pull request as ready for review October 25, 2026 01:06
@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: L labels Oct 25, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 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-25T01:41:03.167955Z 55ecfd1 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.

@steipete
steipete force-pushed the steipete/perf-micro-config-validate-latency-20260919 branch from 9079689 to e398f7c Compare October 25, 2026 01:15

@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: e398f7cd07

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

@steipete

Copy link
Copy Markdown
Contributor Author

The two type-check failures on head e398f7cd07c70ced4da27f0cb875b006ebefebac are inherited:

  • PR run 40149925428, jobs check-prod-types (121039736765) and check-test-types-core-2 (121039736821), both report TS2739 at src/gateway/server-methods/session-catalog.test-helpers.ts:122: the empty connection object lacks minProtocol, maxProtocol, and client.
  • Scheduled main run 40149301577 on f0dcb354e45b06d60df466de136f85cd1b7b148e reports the identical diagnostic in jobs 121037449659 and 121037449682.
  • The failing file has identical Git blob 630e32eb81c4e62823f842b6d075f8f791490b3f on scheduled main, this PR head, and CI's actual merge checkout b2fdc1e8beb2c20b5deed8a7a8074d4b0dc74b1d.

The earlier benchmark fixture writer violation was fixed in this PR and passed its local guard. Broad CI is still running; no failing check is being reported as green.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. 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: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 25, 2026
@clawsweeper

clawsweeper Bot commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR reads plugin metadata directly from verified live SQLite databases instead of copying unrelated shared state.

Example: Run openclaw config validate against a live Gateway with 1 GiB of unrelated shared-state payload.

  • Before: The supplied benchmark reports 2,957 ms average elapsed time while backing up the database.
  • After: The supplied benchmark reports 1,294 ms average elapsed time while reading the metadata in a pinned transaction.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong, relevant CLI performance evidence supports a useful change, but the typed-error regression blocks correctness approval.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied evidence exercises the actual built config-validation CLI on macOS with an isolated live Gateway and 1 GiB synthetic shared state, records valid baseline and candidate results, and measures reduced elapsed time and CPU; the committed regression separately rejects snapshot allocation while reading real committed updates.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Config validation gets slower and needs temporary disk space as unrelated live shared-state data grows.
Reason: The maintainer-authored direction removes measured unnecessary work without adding production settings, schemas, caches, or a competing query owner.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep this PR open: the measured optimization is worthwhile, but the new transport loses typed schema refusals and needs a focused repair.

Priority: P2
Reviewed head: e398f7cd07c70ced4da27f0cb875b006ebefebac

Before merge

  • Preserve typed schema refusals through the live-read transport (P2) - When a CLI reads a verified live Gateway database whose schema or content version is newer than that CLI supports, the new handler throws SqliteSchemaVersionError. The inspection child serializes it as a message string, and sqlite-readonly-worker-protocol.ts reconstructs a plain Error. Fresh admission before this call checks access and quarantine, not schema compatibility, so it does not prevent this trigger. Unlike the previous state-read transport, the new path therefore bypasses findStartupMaintenanceRequiredError recognition, and config/io.snapshot.ts reports CONFIG_READ_FAILED instead of propagating the newer-build requirement. Preserve structured error encoding and hydration for this operation and add a regression through the metadata consumer.

Findings

  • [P2] Preserve typed schema refusals through the live-read transport — src/state/openclaw-state-read-operation.ts:286-288
Agent review details

How this fits together

Plugin-aware config validation requests persisted inventory and discovery metadata through the shared-state read owner, which selects an isolated SQLite child or a retained private snapshot and returns committed metadata rows.

flowchart TD
  A[Config validation] --> B[Shared state read owner]
  B --> C[Verify admission and live owner]
  C --> D[Isolated SQLite child]
  C --> E[Offline or retained snapshot]
  D --> F[Plugin metadata query]
  E --> F
  F --> G[Config validation result]
Loading

Technical review

Best possible solution:

Keep the isolated live-row read and preserve structured schema errors through its transport using the existing error codec.

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

Source confirms that main copies the database for this metadata read, and the supplied built-CLI measurements exercise the large live-state trigger; this read-only review did not run a reproduction.

Is this the best way to solve the issue?

The smallest complete optimization reuses the existing isolated inspection child, metadata query, and live-owner verifier; the distinct snapshot paths remain justified by their byte-preservation contracts.

Full review comments:

  • [P2] Preserve typed schema refusals through the live-read transport — src/state/openclaw-state-read-operation.ts:286-288
    When a CLI reads a verified live Gateway database whose schema or content version is newer than that CLI supports, the new handler throws SqliteSchemaVersionError. The inspection child serializes it as a message string, and sqlite-readonly-worker-protocol.ts reconstructs a plain Error. Fresh admission before this call checks access and quarantine, not schema compatibility, so it does not prevent this trigger. Unlike the previous state-read transport, the new path therefore bypasses findStartupMaintenanceRequiredError recognition, and config/io.snapshot.ts reports CONFIG_READ_FAILED instead of propagating the newer-build requirement. Preserve structured error encoding and hydration for this operation and add a regression through the metadata consumer.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 149416139cf8.

Provenance checked

  • Live metadata snapshot selection changes intended behavior with a stated reason (f150189: Use online backup for verified live owners to avoid repeated copy failures during WAL checkpoints while preserving offline artifacts.)
  • Live-owner verification keeps the original intent (0ff7795: Keep unverifiable owners protected and distinguish ordinary admission from ownership reclamation.)
  • Shared read lifecycle keeps the original intent (997e2bf: Join read completion and native cleanup under the existing async owner while retaining admission, cancellation, and snapshot custody.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/plugins/plugin-metadata-state-worker.test.ts src/state/openclaw-state-worker-error.test.ts --maxWorkers=1
  • pnpm test src/state/openclaw-state-read-worker.test.ts --maxWorkers=1
  • git diff --check
  • Verify a newer-schema live metadata read retains SqliteSchemaVersionError through the config snapshot consumer.

What I checked:

PR surface

Source +64, Tests +93, Other +287. Total +444 across 8 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 5 97 33 +64
Tests 1 93 0 +93
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 287 0 +287
Total 8 477 33 +444

Review metrics

Metric Value Why it matters
Benchmark controls 5 script options and 1 instrumentation environment variable These controls belong to the synthetic measurement script; production config and database formats are unchanged.

Labels

Label changes:

  • add P2: The optimization benefits large live databases, with a bounded schema-error handling regression requiring repair before merge.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: The optimization benefits large live databases, with a bounded schema-error handling regression requiring repair before merge.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • 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 execution lanes are retired.

Reviewed October 24, 2026, 9:30 PM ET / October 25, 2026, 01:30 UTC.

@steipete
steipete force-pushed the steipete/perf-micro-config-validate-latency-20260919 branch from e398f7c to 6d6f2c7 Compare October 25, 2026 01:31
Read plugin metadata through the existing isolated SQLite inspection child instead of backing up unrelated state. Preserve offline artifact-neutral reads, pinned snapshots, managed schema scopes, and live identity/admission checks.

Synthetic 1 GiB live shared-state fixture: CLI elapsed 2.96s to 1.29s (-56%), total process-tree CPU 3.27s to 1.58s (-52%). Independent review clean; focused metadata/closure tests and core typecheck passed.
@steipete
steipete force-pushed the steipete/perf-micro-config-validate-latency-20260919 branch from 6d6f2c7 to 55ecfd1 Compare October 25, 2026 01:38
@steipete
steipete merged commit 7e57516 into main Oct 25, 2026
147 of 149 checks passed
@steipete
steipete deleted the steipete/perf-micro-config-validate-latency-20260919 branch October 25, 2026 01:48
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 25, 2026
…law#183082)

* perf(config): speed up validation with large live shared state

Read plugin metadata through the existing isolated SQLite inspection child instead of backing up unrelated state. Preserve offline artifact-neutral reads, pinned snapshots, managed schema scopes, and live identity/admission checks.

Synthetic 1 GiB live shared-state fixture: CLI elapsed 2.96s to 1.29s (-56%), total process-tree CPU 3.27s to 1.58s (-52%). Independent review clean; focused metadata/closure tests and core typecheck passed.

* fix(perf): seed config benchmark through async state writer

* fix(config): preserve schema refusals during live metadata reads

* fix(config): narrow live metadata read outcomes explicitly
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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