Skip to content

perf(gateway): avoid copying sealed state during startup - #186176

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-boot-gateway-lock-health-read-20261027
Oct 27, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-boot-gateway-lock-health-read-20261027

Conversation

@steipete

@steipete steipete commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Gateway startup copies the entire shared-state database to read a few config-health or plugin-metadata rows, even after a verified clean close.

User Impact

Clean startup avoids that copy. Crash recovery, live-owner reads, source artifacts, integrity checks, and split-brain protection retain their existing behavior. No configuration, schema, durability, or retention changes.

Why This Change Was Made

The isolated reader acquires existing physical custody without waiting, rechecks the existing clean-close proof, reads the checkpoint immutably, and closes the native reader before releasing custody. Missing proof or contended acquisition retains the private-snapshot path. The parent seal check is only a hint; it cannot authorize the read across an awaited worker startup.

Production delta: +44 lines. The growth retains physical exclusion through native close; an unguarded seal shortcut before Gateway lock acquisition would weaken reader consistency. There is no new cache or persisted state.

Evidence

The regression replaces an ineffective staging spy with the actual snapshot-preparation boundary. It fails on main because a sealed config-health read makes one full-database copy; the candidate makes zero. Existing observation reuse, committed-write invalidation, and stale-update conflict assertions remain. Net test-line delta is zero; the existing over-ceiling tree is accepted by the unchanged ratchet.

Local macOS / Node 26.12.1 owner measurements use the existing scripts/perf/config-health-read-measure.ts, a synthetic 138,113,024-byte shared database, and AB/BA order. Timing and 4 KiB allocation-sampling passes are separate; each arm has two first-read samples and two 3,000-iteration warm samples.

Main-thread metric Base mean Candidate mean Change
First health-read CPU 37.47 ms 29.86 ms -20.3%
First health-read sampled allocation 4.24 MB 3.36 MB -20.7%
3,000 warm reads CPU 3,841 ms 3,719 ms -3.2%, context
3,000 warm reads sampled allocation 1,915.99 MB 1,915.66 MB effectively unchanged

These owner measurements were refreshed after the import-cycle correction on the final head. All eight outputs have the same semantic fingerprint. Mean cold source-run wall time was 7.99 → 7.95 s under host load 69–90, so no source-run wall-time improvement is claimed. Worker CPU/allocation and native buffers are outside the owner measurements.

Built Gateway proof used 10,000 sessions, eight agents, 44 startup plugins, and five clean plus five SIGKILL restarts per arm, in counterbalanced order. All 20 restarts and one overlapping restart per arm preserved config bytes, backup bytes, semantic health/plugin facts, readiness, and seeded-session access over WebSocket. The harness signals only its own recorded child PIDs. No Team access.

Built restart metric (mean, n=5 per arm) Clean base → candidate SIGKILL base → candidate
Server health-read phase 620.4 → 478.4 ms 479.7 → 460.6 ms
Server Gateway-lock phase 295.6 → 283.9 ms 244.0 → 237.9 ms
CPU of live process tree at ready 22.96 → 20.02 s 17.67 → 17.35 s
Gateway peak RSS 1,748.5 → 1,792.9 MiB 1,722.3 → 1,722.7 MiB
Main heap at ready trace 366.4 → 405.8 MiB 383.8 → 376.5 MiB
Client admission 12.16 → 10.05 s 9.41 → 9.86 s
Host 1-minute load at run start 34.90 → 36.87 31.20 → 30.17

Clean health-read ranges were 415–777 → 379–600 ms; crash ranges 390–641 → 398–617 ms. These are small-sample startup measurements, not p99 estimates. Process-tree CPU excludes already-exited workers and is not main-thread CPU; heap at ready is not post-GC retained heap. Clean startup RSS rose 2.5% and ready heap rose 10.8%, with substantial per-run spread; crash RSS was flat. Overlapping-restart smoke also passed (health-read 394 → 333 ms). There is no demonstrated whole-Gateway retained-memory win.

The synthetic fixture did not reproduce either reported eight-second stall. Dead-owner detection already precedes lease expiry, and lock policy remains unchanged. This fixes the independently reproduced residual whole-database copy after clean close. Crash recovery remains intact. The 10-minute steady-state stress campaign is omitted under the scoped fast-path proof rule; no steady-state GC, allocation, event-loop p99, or sessions.list p99 claim is made.

The table above measures the initially reviewed implementation. CI then caught an import cycle through its general state-connection helper. The correction uses the native SQLite opener directly with the same admission, timeout, custody, and native-close rules; the cycle guard passes. The rebuilt final head passed an additional clean, SIGKILL, and overlapping restart, preserving all correctness checks. These are single-run smoke results under different host load, not a new A/B latency comparison:

Final-head smoke Health-read Gateway lock Live-tree CPU Peak RSS Ready heap Host load
Clean 426.4 ms 433.1 ms 23.51 s 1,750.1 MiB 353.7 MiB 67.22
SIGKILL 674.8 ms 367.8 ms 26.51 s 1,837.5 MiB 394.6 MiB 62.41
Overlap 752.7 ms 338.1 ms 27.51 s 1,716.3 MiB 410.2 MiB 74.64

Focused health-observation (32), Gateway owner-lease (45), and plugin-metadata-worker (15) tests passed. The final dependency correction reran the 47 health/plugin tests successfully. Changed-file formatting/lint and targeted core typecheck passed; baseline and candidate runtime builds passed. Existing lease tests prove dead owners are reclaimed before lease expiry and unverifiable/live owners remain protected. Lock polling and lease policy are unchanged.

Independent subagent review (autoreview route unavailable): no actionable P0/P1/P2 findings. The configured autoreview provider selector was refused; no operator configuration was changed. Final-head CI passes the architecture guard and all other substantive test/check jobs except PostgreSQL conformance (2/3); its aggregate CI gate is consequently red. Its one failure is the unpublished-schema deadline assertion in state-read-admission-publication.postgres.test.ts: the facts relay reports a generic timeout instead of the expected missing-schema error. That fixture directly calls the PostgreSQL read-connection path, bypassing this changed startup metadata path. Attribution: the exact file passed 5/5 independent runs on the PR head and 5/5 on base eb78444932faeff3e6ab23d082e6c02dc0ddcb2b (25 test cases per side), using the same pinned PostgreSQL image as CI, pgvector/pgvector@sha256:ac08538c6f8b9904c33c8224c5e5706dbe760aca29db1d096972b4052c22a75d. Base source equality was checked before testing; the reviewed patch was restored afterward. The fixture, PostgreSQL retry owner, and facts-relay owner are byte-for-byte unchanged by this PR. This meets the lane's unrelated-flake classification; it does not make CI green. No CI rerun, assertion relaxation, or baseline exemption was used.

Focused reproduction command (one file only): node scripts/test-database-conformance.mjs --engine postgres --connection <disposable-local-dsn> -- src/infra/database-engine/state-read-admission-publication.postgres.test.ts --maxWorkers=1.

Remaining CI failure. The relay uses the PostgreSQL admission retry's remaining deadline; a late facts exchange can throw the generic transport timeout instead of retaining the original schema-admission error. Correcting that requires a separately typed timeout distinction to preserve cancellation and owner-loss precedence. It is outside this sealed-startup-read change. CI remains red for this unrelated flake; this PR is ready, open, and deliberately unmerged for the lead's review.

Benchmark base: 98a9fdeb40ceacbd1c8f7de13862ff5fc7d0c5bc; candidate: the reviewed patch on that base. The required pre-push rebases did not change these owners. Final PR head: 4b40b625c5081889a5419c4d1c09e852d20a86ea.

@clawsweeper

clawsweeper Bot commented Oct 27, 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 27, 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-27T18:04:59.850403Z 4b40b62 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 scripts Repository scripts size: S labels Oct 27, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 27, 2026
@clawsweeper

clawsweeper Bot commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR reads sealed startup config-health and plugin metadata directly under existing physical custody instead of copying the database.

Example: Start with a cleanly closed 135,950,336-byte shared-state database and a retained config backup.

  • Before: The first config-health read prepares a full database copy.
  • After: The isolated reader verifies the seal under custody and reads directly; unavailable proof retains the snapshot path.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The focused patch has no identified correctness defect, but owner-level measurements do not complete the declared startup validation.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Gateway startup copies unrelated shared-state data to read a few rows after a verified clean shutdown.
Reason: The maintainer-authored direction removes measured redundant work through existing lifecycle owners without adding configuration or changing stored-data contracts.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it removes a concrete startup copy that remains on main, and source review found no actionable code defect.

Priority: P2
Reviewed head: 68521adfe97bedb03ec883eb5d6ead7200d0b068

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Supply the declared built-Gateway clean and SIGKILL restart results, including startup resource measurements and preserved config, metadata, readiness, and seeded-session access.
Agent review details

How this fits together

Gateway startup requests config-health and plugin metadata through the shared-state reader, which returns admitted rows from an isolated SQLite reader or a private snapshot.

flowchart TD
 A[Gateway startup] --> B[Shared state read owner]
 B --> C[Isolated metadata reader]
 C --> D[Verified live owner read]
 C --> E[Custody and seal verification]
 E --> F[Immutable checkpoint read]
 B --> G[Private snapshot fallback]
Loading

Technical review

Best possible solution:

Reuse the existing isolated reader, seal verifier, and custody owner to eliminate sealed-state copies while preserving private recovery and current-admission checks.

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

Current main sends sealed offline metadata reads through snapshot preparation; the PR reports a base-failing copy-count regression, but this read-only review executed no target code.

Is this the best way to solve the issue?

This is a focused extension of existing owners: direct reads remain isolated, seal verification occurs under custody, and unsealed or contended cases retain the established fallback.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +44, Tests 0, Docs +5, Other +26. Total +75 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 60 16 +44
Tests 1 3 3 0
Docs 1 5 0 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 1 49 23 +26
Total 6 117 42 +75

Review metrics

Metric Value Why it matters
Production versus tests Production +44 net lines; tests +0 net lines The production growth holds existing custody through seal verification and native close; the regression strengthens an existing test without adding scaffolding.

Labels

Label changes:

  • add P2: Avoiding a full shared-state copy improves a limited startup path without evidence of an urgent outage.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Avoiding a full shared-state copy improves a limited startup path without evidence of an urgent outage.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

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 27, 2026, 1:58 PM ET / 17:58 UTC.

Read startup config health and plugin metadata from the verified clean checkpoint under physical custody in the isolated reader. Keep unclean recovery, live-owner reads, schema checks, and source artifacts unchanged. Extend the restart benchmark with clean and owned-child crash modes.
@steipete
steipete force-pushed the steipete/perf-boot-gateway-lock-health-read-20261027 branch from 68521ad to 4b40b62 Compare October 27, 2026 18:02
@steipete

Copy link
Copy Markdown
Contributor Author

Admin-merging over PostgreSQL conformance (2/3) (and the ci-gate that rolls it up). The only failing test is state-read-admission-publication.postgres.test.ts > unpublished schema reaches its bounded deadline, a Postgres-engine conformance case that measures bounded waiting with real worker clocks (4.9 s on the CI runner). This PR changes only the SQLite startup-metadata branch, gated on a SQLite clean-close seal, so it cannot reach the Postgres admission-publication path. The lane also ran that unchanged file 5/5 on both base and head. Every other check is green at 4b40b625c508.

Reviewed: the parent's seal check is only a hint. The worker re-reads the seal under schema-maintenance custody (busyTimeoutMs: 0), opens the file immutable and read-only, closes before releasing custody, and returns undefined on a custody conflict or pending admission. The caller then falls through to the unchanged snapshot-preparation path, so unclean and contended databases keep their recovery owner.

@steipete
steipete merged commit c4c345a into main Oct 27, 2026
135 of 138 checks passed
@steipete
steipete deleted the steipete/perf-boot-gateway-lock-health-read-20261027 branch October 27, 2026 18:53
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 28, 2026
…6176)

* perf(gateway): avoid copying sealed state during startup

Read startup config health and plugin metadata from the verified clean checkpoint under physical custody in the isolated reader. Keep unclean recovery, live-owner reads, schema checks, and source artifacts unchanged. Extend the restart benchmark with clean and owned-child crash modes.

* perf(gateway): keep sealed metadata reader dependencies acyclic
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. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: S 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