Skip to content

perf(gateway): streamline startup environment health reads - #184338

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-gateway-select-environment-startup-20261026
Oct 26, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-gateway-select-environment-startup-20261026

Conversation

@steipete

@steipete steipete commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Gateway environment selection reads config-health state when a config backup exists. Its cold promise-only read unnecessarily starts retained native supervision and snapshot staging workers before bootstrap.

User Impact

Startup uses fewer worker layers, and every completed startup phase: line reports process rssMb and main-isolate heapUsedMb in MiB. These are completion-time readings, including buffered CLI output, rather than peak measurements. No config, schema, recovery-policy, or authorization changes are required.

Why This Change Was Made

Select the existing awaited snapshot path already used by plugin metadata and restart-handoff reads. Config-health reads still use strict artifact-preserving copies, captured source identity, fresh admission, final authority checks, and joined cleanup. Existing retained readers remain reusable. Retrospective bootstrap trace replays omit current memory to avoid attributing it to an earlier phase.

Production runtime delta is +13 lines: the performance change replaces one argument line, while the requested shared memory formatter and completion-log integration account for the growth. The required non-test/non-doc diff is +185 lines, of which benchmark code adds 172 lines for reproducible cold/warm CPU and allocation measurements and backup-shaped boot coverage.

The teamBoot benchmark now creates a matching .bak, exercising the health read that a backup-free fixture misses. Usage remains in the script header; the shared performance README is unchanged.

Evidence

A real work-count regression fails on the baseline because the cold health read captures a snapshot staging owner once. The candidate captures none and returns the same stored health signature; subsequent committed changes remain visible. Memory regressions also fail on the baseline and verify completion-time sampling before buffered output.

Built Gateway boots

Five boots per arm, fresh synthetic fixtures per boot: 10,000 sessions, eight agents, 44 plugins, 130 MiB shared state, matching config backup, isolated loopback ports, and an 8 GiB Node heap limit. All ten reached readiness, served the seeded session RPC, and shut down cleanly.

Metric (median, 5 boots/arm) Baseline Candidate
Environment selection 2,031.1 ms 886.2 ms
Environment-selection range 1,322.1–3,335.2 ms 696.6–1,141.6 ms
Full benchmark completion 31,369.5 ms 22,612.1 ms
Process-tree CPU through completion 47,770 ms 37,890 ms
Peak sampled process RSS 3,901.1 MiB 3,910.9 MiB

The boots were sequential cohorts, with materially different host load: baseline 1-minute load 47.0–63.3; candidate 22.7–30.1. Treat these as observed results, not a controlled attribution of the full wall/CPU difference. Baseline build: 99501d269444, with phase-memory probes added for diagnosis (output formatting refined in the candidate). Separate traced full-startup allocation runs were 2,686.6 → 2,697.5 MiB (+0.4%, context only); traced timings are not compared.

The first diagnostic boot without a backup spent 2.6 ms in config recovery; adding a backup raised that to 1,132.9 ms. Runtime-version probes were not the cause. The change removes worker layers from that existing read rather than bypassing the recovery check.

Owner measurements

config-health-read-measure.ts uses the real owner and artifact-preserving reader against the same synthetic state. Timing is AB then BA; allocation is BA then AB, in separate fresh processes, with collected-object sampling. Two cold reads and 6,000 warm reads per arm in each measurement mode. All snapshots have identical fingerprints and non-null read bases; the fixture has an empty health table, and its database size/mtime remain unchanged.

Main-thread metric (mean per run) Baseline Candidate
Cold read CPU, 1 read/run 35.359 ms 37.780 ms
Cold read wall, 1 read/run 8,945.3 ms 5,357.1 ms
Cold sampled JS allocation 4,561,600 B 4,059,600 B
Warm CPU, 3,000 reads/run 3,293.4 ms 3,181.5 ms
Warm sampled JS allocation, 3,000 reads/run 1,851,046,908 B 1,850,781,036 B

Cold allocation falls 11%; cold main CPU rises 2.421 ms (+6.8%), so this is not a cold main-CPU win. Warm allocation is neutral. Owner wall time includes source-worker startup; it excludes parent module imports and is not built-Gateway startup latency. Worker CPU/allocation and native buffers are outside this microbenchmark's scope.

A built, trace-disabled Gateway emitted:

[gateway] startup phase: cli.main.gateway-run-select-environment 711.0ms total=2926.9ms start=2215.9ms rssMb=175.0 heapUsedMb=74.0

Validation

  • pnpm build baseline and pnpm build:runtime candidate: passed.
  • Health/recovery: 85 tests across three focused files passed (91.53 s wrapper).
  • Startup tracing: 29 tests across two files passed (4.27 s wrapper).
  • Startup benchmark harness: 45 tests passed (36.55 s wrapper).
  • Import/PR-wrapper closure: 24 tests passed (65.77 s wrapper); export-name collision guard passed.
  • Changed-file formatting, lint, and git diff --check: passed.
  • Independent subagent review (autoreview route unavailable): no actionable P0–P2 findings. The helper refused the configured route because it did not match the operator configuration; no configuration was changed.

This is a startup-only transport selection, covered by built boot comparisons and the cold/warm owner measurement. No production Gateway was modified or load-tested. The lane's fast-path exception applies; no ten-minute whole-Gateway load campaign was run. Exact-head PR CI is green on 2da94397565e85b527f02dd6b654bbfcb82fe4c3: 74 checks passed, 51 intentionally skipped, with no failed or pending checks. The PR remains ready and unmerged for the lane owner.

Use the existing awaited snapshot owner for cold config-health reads, preserving source identity, recovery checks, and joined cleanup. Report process RSS and main-isolate heap on completed startup phases, and cover config backup reads in the Team-shaped startup fixture.

Release-note context: reduce pre-bootstrap worker overhead during Gateway environment selection and make startup memory growth visible in phase logs.
@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

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 🔄 Running since 2026-10-26T07:18:29.118410Z 2da9439 PR opened
ℹ️ 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 cli CLI command changes scripts Repository scripts size: M labels Oct 26, 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. 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. 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 26, 2026
@clawsweeper

clawsweeper Bot commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR selects the existing awaited config-health reader and adds completion-time memory readings to startup logs.

Example: A Gateway starts with an existing openclaw.json.bak.

  • Before: The cold config-health read starts retained supervision and snapshot-staging workers, and startup completion logs omit memory.
  • After: The read uses the existing awaited snapshot path, and a supplied Gateway log reports rssMb=175.0 heapUsedMb=74.0.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, correct optimization with shipped-path evidence; differing host loads limit the precision of the reported startup speedup.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Supplied built Gateway boots exercise environment selection with matching backups, reach readiness, serve seeded sessions, and shut down cleanly; actual startup output shows the new memory fields. Source inspection verifies a no-migration case: the query, stored formats, write policy, and recovery guards are unchanged.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Gateway environment selection starts unnecessary worker layers when reading config-health state, and startup logs lack phase memory readings.
Reason: The maintainer-authored direction removes measured work through an existing capability and adds bounded diagnostics without new configuration or storage.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR removes avoidable startup worker layers with a focused change; no actionable correctness or security defects were found.

Priority: P2
Reviewed head: 2da94397565e85b527f02dd6b654bbfcb82fe4c3

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway environment selection reads persisted config-health facts through the shared-state reader; startup tracers report phase completion to CLI output and Gateway logs.

flowchart TD
  A[Gateway CLI startup] --> B[Environment selection]
  B --> C[Config health owner]
  C --> D[Shared state reader]
  D --> E[Awaited snapshot preparation]
  E --> F[SQLite health facts]
  A --> G[Startup trace owner]
  G --> H[Completion logs with memory]
Loading

Technical review

Best possible solution:

Use the existing awaited reader for cold health reads and the shared startup tracer for completion-time memory.

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

Current main selects the default retained transport for cold health reads; source and the supplied baseline regression identify the unnecessary staging-owner capture, without executing target code during this review.

Is this the best way to solve the issue?

The smallest complete fix is the existing reader option plus shared completion-time formatting, preserving the health query, captured source, admission checks, and cleanup owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Asynchronous config-health reads keeps the original intent (d640aef: Keep config recovery responsive through asynchronous artifact-preserving snapshots while retaining source and final file-effect guards.)
  • Captured health-read ownership keeps the original intent (8d89449: Simplify observation bookkeeping while retaining persisted-row comparison and authority checks at actual effects, as documented in refactor(config): simplify captured reads and cached admission #175077.)
  • Startup progress and slow-service logging keeps the original intent (3d05374: Expose slow top-level service startup without verbose tracing or sensitive payloads; the added memory fields preserve visibility and outcome behavior.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Pinned change and current main: The introduced diff changes the health-read transport selection and startup diagnostics; fetched main retains the original behavior in those runtime owners. (src/config/io.health-state.ts:178, 2da94397565e)
  • Existing snapshot contract preserved: The awaited path supplies captured source identity, uses strict raw-copy preparation for config-health reads, and retains cancellation and cleanup through the existing operation owner. (src/infra/sqlite-snapshot-source.ts:247, 2da94397565e)
  • Admission remains at dispatch: The selected transport rechecks current authority and expected physical identity after queue admission and before dispatch; the health owner checks admission again after the read. (src/state/openclaw-state-read-worker.ts:330, 2da94397565e)
  • Behavioral regression coverage: The existing real health-read test now checks that cold observation returns the stored signature without capturing a staging owner, while retaining committed-write freshness and stale-update rejection coverage. (src/config/io.observe-freshness.test.ts:383, 2da94397565e)
  • Supplied shipped-entry-point evidence: The PR supplies built Gateway comparisons with matching config backups, seeded session RPC success, clean shutdown, and actual memory-bearing startup output. It explicitly acknowledges differing host loads and a 2.421 ms cold main-thread CPU increase, limiting performance attribution. (2da94397565e)
  • Original recovery intent: improve(config): keep recovery responsive during health snapshots #145965 introduced asynchronous artifact-preserving health snapshots to keep recovery responsive while preserving final config and backup guards; this PR continues using asynchronous preparation. (src/config/io.health-state.ts:175, d640aef875e8)

Likely related people:

  • Peter Steinberger: Raw commit 8d89449 adds src/config/io.health-state.ts:148 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 8d8944985883; files: src/config/io.health-state.ts)
  • Vincent Koc: Raw commit c1ee660 adds src/cli/startup-trace.ts:8 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: c1ee660b858b; files: src/cli/startup-trace.ts)

PR surface

Source +13, Tests +47, Docs +6, Other +172. Total +238 across 9 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 19 6 +13
Tests 3 50 3 +47
Docs 1 6 0 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 2 172 0 +172
Total 9 247 9 +238

Review metrics

Metric Value Why it matters
Runtime production versus tests Runtime production +19/-6 lines; tests +50/-3 lines. Runtime growth supports shared memory formatting and completion logging; tests cover buffered sampling, phase completion, replay exclusion, and cold-reader work.

Labels

Label changes:

  • add P2: This improves Gateway startup overhead and diagnostics for configurations with backups, without evidence of an urgent availability regression.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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: This improves Gateway startup overhead and diagnostics for configurations with backups, without evidence of an urgent availability regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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 execution lanes are retired.

Reviewed October 26, 2026, 3:34 AM ET / 07:34 UTC.

@steipete
steipete merged commit c3904c6 into main Oct 26, 2026
161 of 164 checks passed
@steipete
steipete deleted the steipete/perf-gateway-select-environment-startup-20261026 branch October 26, 2026 07:44
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 27, 2026
…184338)

Use the existing awaited snapshot owner for cold config-health reads, preserving source identity, recovery checks, and joined cleanup. Report process RSS and main-isolate heap on completed startup phases, and cover config backup reads in the Team-shaped startup fixture.

Release-note context: reduce pre-bootstrap worker overhead during Gateway environment selection and make startup memory growth visible in phase logs.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes docs Improvements or additions to documentation gateway Gateway runtime 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. scripts Repository scripts 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