Repository navigation
perf(gateway): move startup maintenance after readiness - #165218
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: blocked before merge. Reviewed October 5, 2026, 1:01 AM ET / 05:01 UTC (Revision 4). ClawSweeper reviewWhat this changesThe PR moves optional Gateway maintenance after readiness, shares startup admission reads, transfers orphan settlement to database workers, and adds startup timing details. Merge readiness⛔ Blocked before merge - 5 items remain Five prior findings are addressed, but idle cleanup still drops scheduler cancellation. The useful startup improvement remains distinct from main; published-updater upgrade proof is also outstanding. Priority: P2 Review scores
Verification
How this fits togetherThe Gateway admits configuration, plugins, and session databases before serving clients. Its background maintenance repairs session projections and reclaims retired plugin artifacts under tracked lifetimes. flowchart TD
A[Configuration and stored state] --> B[Required startup admission]
B --> C[Gateway readiness]
C --> D[Client requests]
C --> E[Tracked background maintenance]
E --> F[Session repair workers]
E --> G[Plugin artifact cleanup]
H[Restart and cancellation] --> E
Before merge
Findings
Agent review detailsSecurityNone. PR surfacePR surface statistics unavailable: the file list is incomplete. Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Copy recommended automerge instructionTechnical reviewBest possible solution: Retain the deferred startup design with cancellable cleanup and published-updater upgrade proof preserving existing state. Do we have a high-confidence way to reproduce the issue? Yes, source establishes the remaining defect: start idle cleanup behind a held plugin lease, then begin restart drain; the scheduler signal aborts while cleanup waits on the unrelated connection signal. No target code was executed during this review. Is this the best way to solve the issue? Yes, the existing admission, worker, and maintenance owners are the appropriate boundaries; forwarding their cancellation signal is a narrow correction. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against fe291d617b79. LabelsLabel changes: No label changes. Label justifications:
EvidenceAcceptance criteria:
What I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (3 earlier review cycles)
|
Attribute CLI bootstrap and listener-to-ready work with the existing recorder, share admitted state reads, and carry prepared stores into tracked post-ready maintenance. Reuse admitted checkpoint ownership and preserve ownership metadata in prepared agent schema headers. Settle orphan status and its failure receipt atomically on the existing database worker. Preserve retained recovery ownership and revalidate current authority around commit grants. Move capture reclamation to idle cleanup under worker-backed lease authority, retain reload waiter accounting, and overlap main-session marking with plugin loading. A matched synthetic Linux run on base a754556 reduced metadata-refresh startup from 64.113s to 43.876s and warm startup from 49.597s to 36.868s. First sessions.list completed in 589ms and 634ms. The 20-second startup target remains unmet; no production Gateway was changed.
84180b3 to
fb114db
Compare
) Attribute CLI bootstrap and listener-to-ready work with the existing recorder, share admitted state reads, and carry prepared stores into tracked post-ready maintenance. Reuse admitted checkpoint ownership and preserve ownership metadata in prepared agent schema headers. Settle orphan status and its failure receipt atomically on the existing database worker. Preserve retained recovery ownership and revalidate current authority around commit grants. Move capture reclamation to idle cleanup under worker-backed lease authority, retain reload waiter accounting, and overlap main-session marking with plugin loading. A matched synthetic Linux run on base 9e4bb34 reduced metadata-refresh startup from 64.113s to 43.876s and warm startup from 49.597s to 36.868s. First sessions.list completed in 589ms and 634ms. The 20-second startup target remains unmet; no production Gateway was changed.
What Problem This Solves
Large Gateways remain unavailable during updates while startup repeats state reads and waits for maintenance before readiness.
User Impact
Mandatory config, schema, permission, session, model, and channel admission remains before
ready; nonessential maintenance runs afterward through the existing tracked lifetime. On the latest matched synthetic rig, startup improved from 64.113 s to 43.876 s with refreshed metadata and 49.597 s to 36.868 s warm. The candidate served its firstsessions.list589 ms / 634 ms after ready.The ≤20-second startup target is not met. No production Gateway was changed. There is no new configuration option, schema, public protocol, installation migration, or durable cache.
Why This Change Was Made
The existing recorder now attributes CLI admission, metadata refresh and leases, session admission/materialization, and listener-to-ready work. Each read-only CLI admission pass shares one coherent state snapshot and releases it before live guards or writes. Checkpoints reuse admitted shared-state ownership; the separate legacy/native bootstrap contract remains. Prepared agent headers preserve verified ownership metadata.
Transcript repair, orphan settlement, channel maintenance, pairing diagnostics, and restored subagent activation use the tracked post-ready lifetime. The existing transcript-report worker atomically writes interrupted status and its idempotent receipt, retaining physical identity, live commit authority, cancellation, and shutdown settlement. Existing recovery owners return a typed no-write outcome; custody acquired during a write still rolls it back. Ordinary failure-receipt callers retain
Promise<void>.Retired plugin/native captures move to idle cleanup. Its plugin-owned asynchronous lease uses the existing worker lifecycle for acquisition, verification, renewal, and release. It shares waiter accounting with ordinary plugin lifecycle work so a reload draining root work can still escape a lease wait cycle. Main-session orphan marking overlaps plugin loading, with both joined before model/channel admission or failure propagation.
The composite foreground maintenance path, fallback store discovery, native orphan-settlement callback, native cleanup lease adapter, and obsolete test routing are removed. Production LOC is positive: requested attribution and the deferred worker handoff require explicit identity, current authority, atomic publication, retained outcomes, and lifecycle settlement. Under the requested exclusions (
:!*.test.ts,:!*test-support*,:!docs/*), production/tooling is +1,666 / −924 = +742 lines. The existing recorder, scheduler, state-worker, lease, and cleanup owners are reused; no competing manager or cache is introduced.Evidence
Ubuntu Linux rig, 8 cores, Node 26.8.1, real dist Gateway bound to loopback. Synthetic fixture: 38 public plugins, two agents, a 4,833,120,256-byte primary agent database with 8,065 nodes and 4,071,821 transcript events; secondary database 1,282,048 bytes with one session and 505 events; shared state approximately 537 MB. External channel accounts and private plugins were absent.
The initial unarchived fixture reproduced 54.166 s startup, including 16.644 s foreground maintenance. Normal maintenance subsequently archived 3,064 rows. Matched runs retain that same state and use fixture-only
session.maintenance.maxEntries=10000to prevent further capacity archiving. All runs load 38 plugins, return 5,002 visible sessions, serve history, and settle deferred maintenance.The latest pair uses source base
a75455653ba88b468cf2c8dfcb32357293f5a463; the baseline adds timing instrumentation only. “Refresh” is the first startup following the runtime rebuild; “warm” reuses its metadata. The OS page cache was not cleared. These are single observations on a shared host, not statistical estimates.sessions.listParent and child spans overlap; durations must not be added:
Database-readiness records represent separate fleet passes, not one record per agent; inspection already uses concurrency two. Plugin registration is synchronous by contract and occurs after CLI bootstrap. The new refresh span attributes 6.505 s to plugin-index refresh.
Load variability is material. An earlier matched pair on base
5f497e71d52c043277574351714ab3bde246f843measured 41.575→29.286 s refresh and 31.086→24.986 s warm, with candidate first lists in 349/324 ms. An initial smoke on the newer source measured 48.487/35.647 s and 1,226/438 ms to the first list; the refreshed smoke missed the handoff target. These results are retained, not replaced by the later pair.Validation
The latest measured runtime source (
c8b847edc7e4e5089cec4b01ca056727f24e279aintegration) reached ready in 38.818 s metadata refresh / 31.805 s warm, with first session lists in 514 / 456 ms. It loaded all 38 plugins, returned 5,002 visible sessions, served history, and completed deferred maintenance. These timings predate the CI correctness repairs below; the ≤20-second goal remains unmet.A fresh smoke of the
417d5c306fff46aa5d710b28dd81873630d5435cintegration measured 58.621 s refresh / 42.700 s warm, with first session lists in 925 / 1,435 ms. Both runs loaded 38 plugins, returned 5,002 sessions, served history, and settled deferred maintenance. The warm run misses the one-second first-list target. The 8-core rig reported load averages of 12.86 and 16.22 at launch; without a simultaneous baseline this is current-source functional/timing evidence, not a new before/after performance comparison. Its runtime build passed in 184 s.Current-source phase attribution (refresh / warm, overlapping parent spans):
Published-head CI run 37248312056 exposed deferred recovery inheriting a closed startup snapshot. Recovery now starts under the existing detached context while keeping explicit environment, cancellation, file witnesses, and current Gateway authority. A real snapshot regression fails on the old owner and passes on the correction. The built-CLI SQLite lifecycle proof now passes through the previously failing readiness path.
CI also exposed an inherited concurrent-first-write race: a second transcript lookup lost its registry witness when the first writer registered their selected absent store. The existing registry owner now recognizes that first registration and pins one physical generation across all aliases. It does not retry reads or replay callbacks. Real alias replacement, different-owner, and retirement cases still refuse. A negative control reproduces the alias replacement defect on the intermediate owner; the corrected source passes.
Main now owns the host-broker fork routing and shared Doctor maintenance-lock fixture; this branch removes its duplicated corrections after rebasing. Remaining fixtures follow the production owners: the declaration fixture copies its new static dependency; X uses its existing local barrel and generated sidecar inventory. The maintenance mock stays inside the scheduler suite. Three kernel suites share their identical environment fixture, removing 27 duplicated lines without removing assertions.
Provider blacksmith-testbox, profile openclaw-check, lease
tbx_01m44xj7ewnfqs6005jyjp9csrverified exact source hashes before each command. Pre-rebase correction proof passes 26 files / 499 tests, plus the built-CLI lifecycle test. Commands usednode scripts/run-vitest.mjs <files> --maxWorkers=1; the built-CLI proof used the repository's E2E config and prebuilt dist.The slower Gateway and lifecycle files exercise real server, worker, migration, and shutdown boundaries. The added admission regression itself takes 518 ms and adds no Gateway boot. Its old-owner negative control failed with the intended closed-snapshot reason in 17.293 s including startup; the alias control failed with an incorrectly accepted replacement in 23.235 s.
The runtime build (
node --import ./scripts/tsx.mjs scripts/build-all.mts qaRuntime) passed in 36.7 s. On leasetbx_01m44v5asxr06yxbk872jj95ge, the SDK repair's unchanged ordinary path passed 20 contention repetitions and three original 33-file shard replays (222.40 / 224.05 / 223.97 s; total command 18m 25.939s). Its old-owner replay reproduced the original failure in 244.697 s. The subsequent alias correction was verified by the current focused groups above.Earlier perf-owner proof remains valid for unchanged inputs: 14 files / 225 tests; 20 lease-demand repetitions and three full lease-file replays; ordinary transcript reports, orphan custody/rollback, faithful restart, capture cleanup, and whole-operation zero-host-SQL checks. Four baseline controls failed for incoherent snapshot reads, redundant checkpoint scans, lost prepared ownership metadata, and serialized orphan marking. No assertions, timeouts, expected failures, or baseline exceptions were weakened.
The pre-rebase correction passed the complete staged gate in 38m 32.940s command time and fresh independent review with no actionable P0–P2 findings. Rebase onto
417d5c306fff46aa5d710b28dd81873630d5435cthen integrated main's backlog scheduler and archived-session settlement. The single scheduler retains its shorter-backlog and equal-backlog ordering, and caller cancellation releases its reservations. Archived stale-running sessions settle through the existing worker without reading or appending transcripts; their identity and live execution ownership are revalidated, while recovery/delivery metadata and known run timing remain intact. The existing archive policy now lives with session terminal-state handling and is shared by archive and startup callers.Current integration on blacksmith-testbox / openclaw-check /
tbx_01m453safekgjx9rs51arq8fpzpassed 13 focused files / 269 tests: reconciliation 5/38 in 56.25 s, Gateway recovery 5/37 in 96.42 s, main-session recovery 1/151 in 156.27 s, transcript reports 1/14 in 15.39 s, and faithful subagent restart 1/29 in 52.54 s. The runtime build passed in 39.3 s and built-CLI lifecycle passed in 107.00 s. Combined command time was 9m 47.156s. All 99 staged source hashes were verified before execution.Fresh independent review of the complete integrated candidate finished scoped-clean, with no actionable P0–P2 findings. The exact integrated candidate passed
node scripts/check-changed.mjs --stagedon the same lease in 32m 53.456s (32m 54.102s including orchestration): all selected guards, types, dead-export scans, and lint passed. Existing unrelated line-count warnings remained; no baseline or threshold was changed. The lease was stopped before finalizing the commit, and the resulting commit tree was verified equal to the reviewed/tested tree. Headfb114dbe92044e347dc6fda26b8bb7a8c2647646passed CI run 37265424560 in 713 s elapsed (30,115 summed job wall seconds across 163 jobs, including parallel jobs) and build-artifact validation in 343 s elapsed. The aggregate CI gate passed. The lead’s watcher merged the PR at 2026-10-05 05:06:35 UTC asddf95b6c52db452426f56a62d46962284b2d5f31; no manual merge or auto-merge command was used. The inherited declaration-fixture failure has focused Linux proof; Windows jobs were not selected on the final head, so this is not a fresh Windows execution claim.Remaining gaps
Startup still repeats shared-state lock/checkpoint and canonical admission on the warm path; safely eliminating that duplication requires an ownership handoff. Session projection/materialization remains significant. Prepared-header reuse misses in the WAL-backed fixture, and no identity witness was relaxed. Secrets activation includes required durable policy publication.
The fixture approximates database size and cardinality, not production payload distribution, private plugins, live external accounts, or secret-provider latency. A production deployment and the ≤20-second target remain unverified.