Skip to content

perf(gateway): avoid copying state during startup lock admission - #169097

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-boot-to-ready-critical-path-20260919
Oct 11, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-boot-to-ready-critical-path-20260919

Conversation

@steipete

@steipete steipete commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Gateway startup copied the entire shared database to inspect the previous owner's lease after it had already acquired exclusive physical state ownership. That adds avoidable I/O and a synchronous child-process wait to every restart.

User Impact

Shorter restart admission, especially with a large shared database. No schema, configuration, lease expiry, or update behavior changes; live and unverifiable owners still prevent startup.

Why This Change Was Made

Use the existing custody-checked read-only worker for every lock role. Make custody required at the sole call site and remove the unused snapshot fallback. Doctor retains its private snapshot for schema repair. The transaction still independently rechecks the previous owner before publishing the new lease, and heartbeat readiness remains mandatory.

Production code: 13 fewer lines. The regression extends the existing publication test rather than adding another Gateway boot fixture.

Evidence

  • Independent P0–P2 review: clean.
  • Regression on unchanged base 30469f450063: fails specifically at the unwanted shared-state snapshot.
  • Blacksmith Testbox tbx_01m4n9rfpvctd1b2y2600gqvns: baseline regression verified after dependency installation; subsequent candidate runs stopped before tests due to two sync timeouts. Lease stopped; validation continued on the authorized AWS fallback.

Measurement

Same isolated Linux rig, Node 26.8.1, three retained-state unprofiled boots per revision, 3,000 synthetic conversations across three agents, synthetic transcripts, and a 175,747,072-byte shared database containing 100,000 synthetic audit rows. Each boot performs a real chat.send / agent.wait through a loopback mock provider. Retryable not-ready responses reuse the same idempotency key. No production state or services were touched.

Median, ms Baseline Candidate
Environment selection 659.1 673.1
Pre-bootstrap 6.3 7.8
CLI Gateway bootstrap (inclusive) 4,443.3 4,262.1
State-snapshot admission (inclusive) 3,863.7 3,653.7
Database readiness 982.6 852.6
Plugin configuration 1,588.4 1,426.8
Gateway lock 1,131.9 408.1
Process bootstrap (cumulative) 8,682.1 7,983.5
Server schema preflight 809.8 742.8
Session admission 881.6 888.1
Main-session recovery 1,081.7 920.8
Worker-environment startup 101.7 80.5
Plugin services 31.1 32.7
HTTP bound (cumulative) 16,049.2 14,577.1
Process start → readyz 200 19,466.1 17,764.1
Process start → first completed chat 32,827.1 29,285.8

Lock admission is 2.77× faster, saving 724 ms. End-to-end medians improve by 1.70 s to readiness and 3.54 s to first chat; the rig has variable background load, so the full end-to-end difference is not attributed solely to this patch. Post-ready transcript maintenance also varied (2,702 → 1,100 ms).

Separate --cpu-prof runs confirm the removed path: baseline spends 595 ms synchronously preparing the lock-inspection snapshot; the candidate has no samples on that path. The pre-custody preflight snapshot remains (720 / 633 ms). Early baseline module compilation accounts for about 912 ms: process.bootstrap is cumulative startup time, not an independent 11-second import operation.

The remaining pre-custody snapshot and deferred agent admission still dominate parts of the outage. Real provider latency, production data, and production-host timing were not measured. No schema change or deferred authority check is introduced.

Validation

  • AWS Crabbox cbx_432c45522ae2, run run_d05f5503540ff62ff2e1e79c11b30129: node scripts/run-vitest.mjs src/infra/gateway-owner-lease.test.ts src/infra/gateway-lock.test.ts src/infra/gateway-lock.write-failure.test.ts src/infra/gateway-lock.namespace.test.ts src/infra/gateway-state-owner.test.ts src/infra/gateway-state-owner.heartbeat.test.ts --maxWorkers=1 — 116/116 passed, six files, 76.82 s wall time (one worker; about 77 CI worker-seconds). The extended publication regression itself took 899 ms. No new test file or test-only production seam.
  • Both revisions: full pnpm build passed on the isolated Linux rig.
  • git diff --check: passed.
  • Staged changed gate, AWS run run_5cc596a846e77df03cdfdfeee2f1b2f6: core typecheck, all 28 test type graphs, formatting, boundary and ratchet checks passed. The gate stopped at existing unused exports in agent, voice, and UI modules. Fresh Testbox tbx_01m4ney1zdwnt7x7rfd63ge741 reproduced the identical production and full-tree export lists on a verified unchanged 30469f450063 tree. All remaining planned checks then passed on the candidate: typed lint (0 warnings/errors), native schema, database-first storage, media helpers, runtime sidecar loaders, import cycles, webhook body ordering, and pairing guards. No guard was disabled.

Inherited hosted CI failure

CI run 38139414266 failed only at the repository duplicate scan (check-guards); its downstream CI gate failed and fail-fast canceled sibling jobs. A clean worktree of the exact CI baseline 0690a2ef175fc73d69d73105638b69a90af35fe6 reproduces the same uncovered worker-heap-flag.mjs and duplicate groups outside this PR. Verified on Testbox tbx_01m4ney1zdwnt7x7rfd63ge741 with node scripts/check-duplicates.mjs. Canceled hosted jobs are unrun; the scoped remote proof above is retained.

@clawsweeper

clawsweeper Bot commented Oct 11, 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 size: M labels Oct 11, 2026
@steipete
steipete marked this pull request as ready for review October 11, 2026 12:28
@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 Oct 11, 2026
@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR inspects the previous Gateway lease in the existing read-only worker under physical state custody instead of copying the shared database.

Example: Restart with a 175,747,072-byte shared database on the supplied isolated Linux rig.

  • Before: Reported median Gateway lock admission takes 1,131.9 ms.
  • After: Reported median Gateway lock admission takes 408.1 ms.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A useful, focused optimization with supplied entry-point proof and no actionable finding; failed CI attribution remains unresolved.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied isolated Linux CLI boots exercise retained shared state, readiness, and completed chat after the optimization, with profiles confirming that lock-inspection copying disappears; the provider is mocked and production-host timings are not claimed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Copying the whole shared database to inspect a small lease record delays Gateway restart admission.
Reason: The area owner's optimization has measured value, reduces production code, and preserves the existing storage and repair boundaries.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it removes measured startup overhead, preserves the existing ownership checks, and introduces no identified correctness defect; required CI remains unresolved.

Priority: P2
Reviewed head: 18ee92dc620fd85c39a5ee5ef902cbf826c8fb23

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway startup acquires exclusive state custody, reads the previous owner's persisted lease, checks liveness, and transactionally publishes its own identity before heartbeat readiness.

flowchart TD
 A[Gateway startup] --> B[Physical state custody]
 B --> C[Read-only worker]
 C --> D[Previous owner lease]
 D --> E[Liveness check]
 E --> F[Transactional publication]
 F --> G[Heartbeat readiness]
Loading

Technical review

Best possible solution:

Use the existing custody-checked worker for startup inspection while retaining Doctor snapshots and transactional lease publication checks.

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

Fetched main routes normal Gateway admission through the copying fallback despite holding custody, corroborated by the supplied baseline regression and startup profiles.

Is this the best way to solve the issue?

This is a focused solution that reuses the existing worker and ownership contract, removes the superseded path, and preserves Doctor's distinct repair requirements.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Startup lease inspection changes intended behavior with a stated reason (e40606f: The earlier change enabled direct worker inspection under offline CLI custody while retaining Doctor's private snapshot; this PR explains extending that existing path to Gateway startup.)
  • Worker liveness and cleanup keeps the original intent (65829ea: perf(runtime): release completed callers from lifecycle resources #164465 moved inspection into the worker to detect hidden or ambiguous lease claims and preserve custody, process-liveness refresh, and native retirement ordering.)
  • Owner-publication regression keeps the original intent (5469328: fix(gateway): preserve live owners through restart #147242 established publication before listening and release with the lifecycle lock; the extended test retains those assertions.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 5469328 adds src/infra/gateway-owner-lease.ts:120 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 5469328b6c31; files: src/infra/gateway-owner-lease.ts)
  • Dallin Romney: Raw commit 418018b adds src/infra/gateway-owner-lease.ts:128 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 418018b67ff8; files: src/infra/gateway-owner-lease.ts)

PR surface

Source -13, Tests +12, Docs +5. Total +4 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 106 119 -13
Tests 1 14 2 +12
Docs 1 5 0 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 125 121 +4

Review metrics

Metric Value Why it matters
Production versus test LOC Production +106/-119; tests +14/-2. The optimization removes a fallback and extends the existing publication regression without another boot fixture or production test seam.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: A measured restart-performance improvement with limited scope and no established urgent regression.
  • 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.
  • 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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-11T12:35:20.946Z sha 18ee92d :: needs maintainer review before merge. :: none

Reviewed October 11, 2026, 8:41 AM ET / 12:41 UTC (Revision 2).

@steipete

Copy link
Copy Markdown
Contributor Author

Landing under the operator-authorized inherited-failure exception. CI run 38139414266 failed in check-guards at node scripts/check-duplicates.mjs; openclaw/ci-gate failed downstream and sibling jobs were canceled by fail-fast. Canceled jobs are not claimed as passing evidence.

The identical scan fails on unchanged CI baseline 0690a2ef175fc73d69d73105638b69a90af35fe6, reproduced in a clean worktree on Testbox tbx_01m4ney1zdwnt7x7rfd63ge741. It reports the same uncovered worker-heap-flag.mjs and duplicate groups in immutable-launcher fixtures, triage-update fixtures, worker launch-descriptor fixtures, Gateway system-agent tests, and QA node-control-plane tests. None of those files are in this PR's four-file diff.

Independent P0–P2 review is clean. Focused ownership tests passed 116/116; core and all 28 test type graphs passed; both full rig builds passed; all remaining planned changed checks passed. The separate local unused-export failure was also reproduced on the unchanged original base, as recorded in the PR body.

The native landing wrapper stopped before mutation because its canonical tooling checkout has stale dependencies. Using the authorized exact-head API fallback for 18ee92dc620fd85c39a5ee5ef902cbf826c8fb23; no CI rerun or branch update was requested.

@steipete
steipete merged commit 7c2aa57 into main Oct 11, 2026
193 of 233 checks passed
@steipete
steipete deleted the steipete/perf-micro-boot-to-ready-critical-path-20260919 branch October 11, 2026 12:48
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
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. 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