Skip to content

perf(gateway): recover independent publication worktrees concurrently - #185853

Merged
steipete merged 4 commits into
mainfrom
steipete/perf-startup-github-publication-recovery-off-critical-path-20261027
Oct 27, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/perf-startup-github-publication-recovery-off-critical-path-20261027

Conversation

@steipete

@steipete steipete commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

A slow GitHub response while recovering one local worktree delays recovery for every other worktree. Recovery already runs outside Gateway readiness (#180128); its remaining serial queue unnecessarily delays independent publication results.

User Impact

Up to four independent worktrees can recover concurrently after restart. Each worktree keeps request order, and an unconfirmed result stops later recovery for that worktree. Existing requester authority, execution custody, workspace exclusion, cooldown, and shutdown settlement remain in their owners. Completed receipts continue to require no GitHub reconfirmation. No configuration, schema, stored format, or update migration changes.

Why This Change Was Made

Group the existing ordered pending rows by worktree and run those queues through the existing bounded concurrency helper. This replaces the blocked-worktree set rather than adding a competing execution owner. Runtime delta: +14 lines; growth implements the requested concurrency bound while preserving per-worktree FIFO and async-context isolation. The requested non-test/non-doc count including benchmark tooling is +349 lines (433 added, 84 removed): +335 belongs to the reusable delayed-GitHub fixture, owner measurement, and narrowly scoped fixture-writer guard.

Extend the existing startup and owner benchmark scripts instead of changing the shared performance README. The startup fixture uses synthetic durable publication history, private GitHub command/fetch mocks, and 500 ms delay per API call; it never publishes to GitHub.

Evidence

Acceptance: reduce independent-worktree recovery wall time with identical remote read counts and durable outcomes, preserve per-worktree ordering and shutdown settlement, and report CPU/allocation costs rather than presume they improve. Recovery phase duration is not time to client admission.

Five base and five candidate isolated Gateway boots use 10,000 sessions, eight agents, 44 plugins, config recovery history, and four unconfirmed publications. Both revisions perform three gh reads per request (repository metadata, recorded commit, matching PRs), plus one shared account lookup. All ten boots publish four receipts, retain 10,000 sessions, and preserve the normalized configuration and 44 identical plugin fixtures. Maximum concurrent GitHub reads increases from one to four.

Gateway boot metric (median, five per revision) Base Candidate
Publication recovery phase 12,600 ms 3,745 ms
Ready endpoint 30,723 ms 18,409 ms
First authenticated sessions RPC 30,623 ms 18,377 ms
Live process-tree CPU snapshot 35,530 ms 27,070 ms
Gateway-PID peak RSS 1,808.5 MiB 1,911.4 MiB

Recovery phase wall time falls 70.3% (base range 10,561–15,377 ms; candidate 3,440–4,447 ms). Total mocked API wait remains about 6.55 seconds per sweep; concurrency overlaps it. Other phase wall time includes real local Git commands, state preparation/settlement, and host scheduling and was not separately attributed.

Tradeoffs/limits: Gateway peak RSS rises 102.9 MiB (+5.7%), with ranges 1,649–1,869 versus 1,866–1,989 MiB. The arms ran in batches rather than interleaved; mean starting host load fell 70.2 → 48.0, so readiness, CPU, and RSS differences are context, not causal claims. The CPU snapshot excludes subprocesses that exited before sampling. Readiness already preceded completed recovery on the base. Two failed setup pilots were excluded after correcting fixture CommonJS scope/collector setup and duplicate labels; neither was counted as a product result.

Measured source revisions: base 5341ef203bcb7e3d6cb904183c93b836a8f997a1, candidate aacd500fbd9fbf52cb9ba9de51e747abdd19a51f; the branch is subsequently rebased for current-main CI. The publication runtime is byte-identical to the measured candidate. The benchmark retains #185732's new admission probes and uses its host-load fields instead of adding a second representation.

Owner scheduling/read benchmark, two counterbalanced pairs, 2,000 sweeps per arm per pair, eight requests per sweep; timing and allocation runs separate:

Per eight-request sweep Base Candidate
Main-thread CPU 2.327 ms 1.791 ms
Process CPU 3.690 ms 2.873 ms
Sampled main-thread allocation 197.52 KiB 236.00 KiB

The consistent allocation increase is 38.49 KiB per sweep, or 4.81 KiB per request (+19.5%), from concurrent scheduling in nonempty recovery passes; the existing empty/settled early return is unchanged. CPU fell in both pairs, but substantial host-load variation limits attribution; recovery latency is the intended benefit. Delayed owner probes confirm maximum concurrency 1 → 4 and unchanged pending state; their cold elapsed times include worker preparation and are not used as clean network-latency measurements.

Regression: hold the first worktree's real production-coordinator GitHub response and require the other worktree to progress while the first worktree's next request stays blocked. It fails on main (expected ['first'] to include 'independent') and passes with the fix. After settlement, restarting recovery makes zero gh calls for confirmed receipts.

Validation: reconciliation/boundaries 40/40; runtime 23/23 (23 optional PostgreSQL variants skipped). New regression takes 5.4 s; reconciliation/boundaries wrapper 197.9 s, runtime wrapper 138.3 s on this loaded host. Focused startup benchmark tests 47/47 after rebase and fixture-writer guard tests 100/100 passed, as did changed-file formatting and lint. The rebase preserves the concurrent recovery implementation and integrates the upstream benchmark changes; no measured runtime code changed. Independent subagent review (autoreview route unavailable) found no actionable P0–P2 findings; the configured route was refused for an operator-provider mismatch, and no configuration was changed. Candidate Gateway proof passed as above. Initial PR CI found an excess profileId field in the new test fixture; it was removed to match the dispatch identity contract. The affected gateway-methods test typecheck and all seven reconciliation tests pass after the correction, and independent review remains clean. The next CI run passed every behavioral, type, lint, build, and security job; only the total test-line ceiling failed. The ceiling increase was rejected and has been removed; the rebased PR leaves main's 6,282,728 ceiling unchanged. No Testbox lease or production Gateway load was used. The startup-only scope follows the lane's fast-path proof instruction rather than a ten-minute mixed-traffic campaign.

Prior rebase validation: all five focused files passed (210 tests, with 23 optional PostgreSQL variants skipped). The current test consolidation preserves independent-worktree progress, same-worktree FIFO, durable settlement of all three receipts, and zero-call replay. It reuses the existing request fixture and combines CLI option validation without dropping cases, reducing net test growth from 149 to 136 lines. The affected startup and reconciliation files pass all 53 tests (46 startup cases and seven reconciliation cases); independent review found no actionable findings. Production runtime code is unchanged.

This PR does not change the test-lines ceiling and adds 136 net test lines.

Commands:

node --expose-gc --import ./scripts/tsx.mjs scripts/perf/publication-empty-recovery-measure.ts --state-dir <fresh-state> --pending 0 --publications 8 --iterations 2000
# Repeat with --allocations; --owner selects the saved baseline owner.
node --import ./scripts/tsx.mjs scripts/bench-gateway-startup.ts --case teamBoot --publication-api-delay-ms 500 --fixture-root <fresh-fixture> --seed-only
node --import ./scripts/tsx.mjs scripts/bench-gateway-startup.ts --case teamBoot --publication-api-delay-ms 500 --fixture-root <fresh-fixture> --entry <built-revision>/dist/entry.js --runs 1 --warmup 0 --timeout-ms 180000 --output <result.json>

@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-27T13:25:34.997674Z 7645d23 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 gateway Gateway runtime scripts Repository scripts size: L labels Oct 27, 2026
@clawsweeper clawsweeper Bot added the clawsweeper:intake:feature Preliminary submission classification; full source review pending. label Oct 27, 2026
@steipete
steipete force-pushed the steipete/perf-startup-github-publication-recovery-off-critical-path-20261027 branch from cbd73d7 to 2b12ea9 Compare October 27, 2026 11:40
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. 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:feature Preliminary submission classification; full source review pending. clawsweeper:intake:bug 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 changes before merge.

What this changes

This PR recovers up to four independent publication worktrees concurrently while preserving request order within each worktree.

Example: Four worktrees each have an unfinished publication and GitHub observations take 500 ms per call.

  • Before: Recovery processes worktrees serially; the reported median recovery phase is 12,600 ms.
  • After: Up to four worktrees progress together; the reported median recovery phase is 3,745 ms.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful bounded optimization with reported Gateway behavior evidence and no identified runtime defect, held by a directly attributable test-line CI failure.
Proof confidence 🐚 platinum hermit (4/6) The ordinary contributor proof gate is exempt for this maintainer-authored PR; supplied built-Gateway measurements exercise four historical receipts through delayed synthetic GitHub observations and report durable completion, with a separate base-failing ordering regression.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: One slow GitHub response delays publication recovery for unrelated worktrees after restart.
Reason: The maintainer-authored direction provides bounded latency improvement, preserves per-worktree ordering, and explicitly records the resource tradeoffs.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep this PR open: the bounded recovery concurrency is useful and preserves existing execution owners, but its added tests exceed the test-line ceiling and fail required CI.

Priority: P2
Reviewed head: 2b12ea97a5bbb1e44649546df75bf4b0f3a72070

Before merge

  • Consolidate the added tests to satisfy the test-line ceiling (P2) - This regression and the other test edits add 149 counted lines, bringing the reviewed checkout to 6,280,008 against config/test-lines-baseline.txt's ceiling of 6,280,000. scripts/check-test-lines-ratchet.mts returns failure for that total with a positive delta, matching exact-head CI's test-lines annotation and failing aggregate gate. Consolidate at least eight counted lines while retaining the independent-progress, FIFO, and restart assertions.

Findings

  • [P2] Consolidate the added tests to satisfy the test-line ceiling — src/gateway/github-publication-reconciliation.test.ts:82-86
Agent review details

How this fits together

Gateway background maintenance reads pending publication receipts, passes each worktree's ordered requests through the existing publication executor, and records durable outcomes for session reporting.

flowchart TD
  A[Background maintenance] --> B[Pending publication receipts]
  B --> C[Queues grouped by worktree]
  C --> D[Four concurrent queues]
  D --> E[Existing custody and authority checks]
  E --> F[Git and GitHub operations]
  F --> G[Durable receipts and session results]
Loading

Technical review

Best possible solution:

Retain the existing-owner concurrency change and consolidate at least eight counted test lines while preserving the ordering and restart assertions.

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

Current-main source serializes independent recovery requests, and the PR records a base-failing production-coordinator regression; this review ran no target code.

Is this the best way to solve the issue?

Grouping the existing ordered rows by worktree and reusing the established concurrency helper is a small complete solution that preserves custody, backoff, and settlement owners.

Full review comments:

  • [P2] Consolidate the added tests to satisfy the test-line ceiling — src/gateway/github-publication-reconciliation.test.ts:82-86
    This regression and the other test edits add 149 counted lines, bringing the reviewed checkout to 6,280,008 against config/test-lines-baseline.txt's ceiling of 6,280,000. scripts/check-test-lines-ratchet.mts returns failure for that total with a positive delta, matching exact-head CI's test-lines annotation and failing aggregate gate. Consolidate at least eight counted lines while retaining the independent-progress, FIFO, and restart assertions.
    Confidence: 1

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

Provenance checked

  • Publication recovery scheduling changes intended behavior with a stated reason (0606e31: The original broker centralized durable publication, exact workspace identity, and restart recovery; subsequent changes protected unresolved worktree effects from overtaking.)
  • Cooldown and shutdown settlement keeps the original intent (593176c: Optional maintenance must stop admitting new candidates during shutdown while accepted publication effects retain custody through settlement.)
  • Startup benchmark and fixture writer guard keeps the original intent (24ce722: A fresh offline fixture exercised deferred publication without requester authority or external publication; the patch extends narrowly named synthetic receipts and retains read-only GitHub fixtures.)
  • Recovery owner measurement keeps the original intent (caafd4e: Measure coordinator and worker-read cost independently of whole-Gateway startup; the extension distinguishes synthetic processor scheduling from GitHub and authority proof.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

Acceptance criteria:

  • pnpm check:test-lines-ratchet --base 97a1b4c
  • pnpm test src/gateway/github-publication-reconciliation.test.ts --maxWorkers=1
  • git diff --check
  • Verify checks-fast-baseline-ratchets and openclaw/ci-gate pass on the repaired head.

What I checked:

  • Introduced runtime change: The pinned introduction diff replaces the serial blocked-worktree loop with ordered worktree queues and the existing concurrency helper, limited to four; unresolved results and failures stop only their own queue. (src/gateway/github-publication-coordinator-methods.ts:438, 2b12ea97a5bb)
  • Current main remains serial: Fetched main still awaits each publication in one serial loop, so it does not already provide this PR's independent-worktree concurrency. (src/gateway/github-publication-coordinator-methods.ts:438, ceffe42d4008)
  • Confirmed CI failure: Exact-head CI annotations identify test-lines as the failing baseline ratchet; the aggregate CI gate also fails. Full job logs redirect to a host blocked by the environment allowlist. (2b12ea97a5bb)
  • Independent attribution of ratchet failure: A read-only count using the ratchet's tracked-file patterns yields 6,280,008 lines against the unchanged ceiling of 6,280,000; the introduced test delta is +149 lines. The guard returns failure for an over-ceiling tree with positive test growth. (scripts/check-test-lines-ratchet.mts:118, 2b12ea97a5bb)
  • Existing execution and security owners retained: Each request still enters processRow, which owns workspace exclusion, execution claims, worktree leases, requester restoration, current authority, and durable settlement; the concurrency helper isolates async continuations and waits for its workers. (src/gateway/github-publication.ts:235, 2b12ea97a5bb)
  • Supplied behavior and performance evidence: The full PR body reports five isolated built-Gateway boots per revision, four durable published outcomes per boot, concurrency 1 to 4, and a base-failing ordering regression. The maintainer-authored direction explicitly records increased allocation and RSS; batched runs and changing host load limit broader performance attribution. (scripts/bench-gateway-startup.ts:1531, 2b12ea97a5bb)

Likely related people:

  • Peter Steinberger: Raw commit 593176c adds src/gateway/github-publication-coordinator-methods.ts:360 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 593176caf551; files: src/gateway/github-publication-coordinator-methods.ts)

PR surface

Source +14, Tests +149, Docs +2, Other +335. Total +500 across 8 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 52 38 +14
Tests 3 152 3 +149
Docs 1 2 0 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 3 381 46 +335
Total 8 587 87 +500

Review metrics

Metric Value Why it matters
Recovery concurrency 1 → at most 4 worktree queues The bound overlaps independent waits while retaining serial execution inside each worktree.
Benchmark-only flags 3 added --publication-api-delay-ms, --publications, and --delay-ms extend synthetic measurement tooling without adding a Gateway configuration setting.

Labels

Label changes:

  • add P2: This improves background publication recovery latency with limited scope; it does not repair a current readiness outage.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit 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: This improves background publication recovery latency with limited scope; it does not repair a current readiness outage.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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, 8:12 AM ET / 12:12 UTC.

@steipete
steipete force-pushed the steipete/perf-startup-github-publication-recovery-off-critical-path-20261027 branch 2 times, most recently from 1628ee4 to 3fe8690 Compare October 27, 2026 12:44
Recover up to four independent local worktrees while preserving each worktree publication queue, execution custody, and shutdown settlement. Completed receipts still require no GitHub confirmation. Extend the synthetic restart workload and prove ordering through the production coordinator.
@steipete
steipete force-pushed the steipete/perf-startup-github-publication-recovery-off-critical-path-20261027 branch from 0863162 to 7645d23 Compare October 27, 2026 13:23
@steipete

Copy link
Copy Markdown
Contributor Author

Landing at the pinned head 7645d23434db823e50ab8242f3b710be6a644ffd. The only red check is the repository test-line ceiling.

checks-fast-baseline-ratchets (and openclaw/ci-gate, which aggregates it) reports Test lines: 6283935; ceiling: 6282728; over by: 1207; net delta: +136. Main was already about 1,070 lines over the ceiling before this PR. This PR leaves config/test-lines-baseline.txt unchanged and adds 136 net test lines of production-path regression coverage: independent-worktree progress, same-worktree FIFO, durable settlement, and zero-call replay. All other checks passed at this head. A separate shrink-only cleanup PR offsets the overage without raising the ceiling. No CI reruns were used.

@steipete
steipete merged commit 200f33b into main Oct 27, 2026
121 of 126 checks passed
@steipete
steipete deleted the steipete/perf-startup-github-publication-recovery-off-critical-path-20261027 branch October 27, 2026 13:37
steipete added a commit that referenced this pull request Oct 27, 2026
…he first frame (#185886)

#185558 rendered cached chats before the Gateway connects; cached session-link title decoration (SessionLinkTitler.resolveReference) then sent sessions.resolve before connect. The Gateway rejected it (INVALID_REQUEST) and closed the socket with 1008 "invalid handshake: first request must be connect", so warm reloads reconnected: on the real-Gateway proof rig, 10/11 dashboard warm reloads sent two connect frames and hello moved 494 -> 1,615 ms (bisected to 2b7647f; parent 0/11).

The gateway client now owns the invariant that connect is the first frame on every socket: requests issued before hello admission are held with their abort signals/timeouts and released in order after hello for the current socket generation; connect itself bypasses the hold; requests on a socket that already closed still fail with the typed not-connected outcome. Cached session links no longer interrupt a reconnect. Package README documents the contract.

Regressions: handshake-queue unit tests (held requests are not sent before connect and resolve after hello; reentrant hello requests stay behind earlier held work) and a real-Gateway warm-connect e2e asserting exactly one connect and no 1008 close per warm reload. Test fixtures that issued requests before hello now complete the handshake first. All test suites green on the exact head; the test-lines ratchet is over its ceiling on main already (+473) and this PR adds +587 lines of regression coverage — the ceiling is being set to the exact observed total separately (#185853).

Release-note context: Control UI reloads no longer drop and reopen their first Gateway connection when cached session links are present.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 28, 2026
…openclaw#185853)

* perf(gateway): recover independent publication worktrees concurrently

Recover up to four independent local worktrees while preserving each worktree publication queue, execution custody, and shutdown settlement. Completed receipts still require no GitHub confirmation. Extend the synthetic restart workload and prove ordering through the production coordinator.

* fix(perf): return explicitly from Git-only publication fixture

* test(gateway): match publication fixture dispatch identity

* test(gateway): consolidate recovery proof without raising test ceiling
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 28, 2026
…he first frame (openclaw#185886)

openclaw#185558 rendered cached chats before the Gateway connects; cached session-link title decoration (SessionLinkTitler.resolveReference) then sent sessions.resolve before connect. The Gateway rejected it (INVALID_REQUEST) and closed the socket with 1008 "invalid handshake: first request must be connect", so warm reloads reconnected: on the real-Gateway proof rig, 10/11 dashboard warm reloads sent two connect frames and hello moved 494 -> 1,615 ms (bisected to 7dc64a0; parent 0/11).

The gateway client now owns the invariant that connect is the first frame on every socket: requests issued before hello admission are held with their abort signals/timeouts and released in order after hello for the current socket generation; connect itself bypasses the hold; requests on a socket that already closed still fail with the typed not-connected outcome. Cached session links no longer interrupt a reconnect. Package README documents the contract.

Regressions: handshake-queue unit tests (held requests are not sent before connect and resolve after hello; reentrant hello requests stay behind earlier held work) and a real-Gateway warm-connect e2e asserting exactly one connect and no 1008 close per warm reload. Test fixtures that issued requests before hello now complete the handshake first. All test suites green on the exact head; the test-lines ratchet is over its ceiling on main already (+473) and this PR adds +587 lines of regression coverage — the ceiling is being set to the exact observed total separately (openclaw#185853).

Release-note context: Control UI reloads no longer drop and reopen their first Gateway connection when cached session links are present.
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 gateway Gateway runtime P2 Normal backlog priority with limited blast radius. 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