Skip to content

fix(gateway): reduce control-plane stalls during concurrent turns - #133683

Merged
steipete merged 3 commits into
mainfrom
codex/gateway-stall-attribution
Aug 31, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/gateway-stall-attribution

Conversation

@steipete

@steipete steipete commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Related: #133477

What Problem This Solves

Resolves avoidable Gateway control-plane stalls during bursts of concurrent agent turns, particularly with diagnostic timeline recording enabled. Readiness, Control UI requests, and session history can wait while synchronous work delays WebSocket dispatch. This is a measured latency improvement, not a claim that every saturation tail or a memory leak is fixed.

Why This Change Was Made

Profiling separated time waiting before the Gateway message callback from time inside the RPC handler. It identified repeated diagnostic file operations, duplicate session-store path validation, and buffered WebSocket messages dispatched without yielding. These are cumulative costs, not one universal cause of every slow sample.

The repair stays with the owners of that work:

  • The diagnostic writer serializes events at emission and retains one bounded 64 KiB UTF-8 batch. It appends on the next event-loop turn, at capacity/path changes, or at normal exit. Oversized individual events retain direct writes. The existing safe-file helper still owns filesystem validation; no retained descriptor, retry queue, or new persistence layer is added.
  • Gateway transport uses the existing ws option to yield between buffered messages while preserving frame order and validation.
  • Runtime session discovery validates the SQLite artifact once. Doctor retains legacy-file discovery; custom/shared stores, retired agents, containment checks, and unreadable-registry behavior remain covered.
  • The benchmark keeps the active timeline intact, reads it after clean shutdown, and selects the measured emission window. Missing, malformed, incomplete, and failed-write evidence is rejected rather than becoming a false zero. Result validation follows Gateway cleanup, and outer cleanup retains ownership of the mock process and temporary state.

Production delta is +52 lines: bounded batching and explicit exit draining require a lifecycle owner; duplicate session validation and the redundant timeline-options helper are removed. Tests add 345 net lines, benchmark support 34, and documentation 6. Most benchmark diff churn is indentation from separating cleanup and result validation. No new config keys, environment variables, schema, or persistent-store semantics.

User Impact

Concurrent turns leave more opportunity for control requests to run. Diagnostic events may become visible on the next event-loop turn rather than immediately. In-process readers can explicitly flush; external readers should inspect the final artifact after normal exit. Output remains best-effort: forced termination and filesystem failures can lose pending output. The existing file helper's separately reproduced short-write handling remains a dependency follow-up, not a claimed fix here.

Evidence

Current head: a5f72bc4172e4fc457bdd6ad2db5651953e799a6. Runtime/browser proof was captured at 840024d41357ae0940d0c6033f513d847eabdf6f, rebased onto c753bbd1ced5395fb42c113cdabda5d69bdb75d4; the final commit changes only the secret-owner isolation test. A full hash comparison confirms runtime/build/dependency parity. Both implementation commits were patch-identical across rebase. The native wrapper required the refresh; no guard was bypassed, and runtime/UI were rebuilt afterward.

All runtime proof used synthetic data, fresh isolated HOME/state, and owned loopback ports. No production Gateway was exercised. Workload: 32 turns, 48 seed sessions, 128 updates/four clients, three history clients with five-request bursts, six subscribers, visible observation, 100 ms cadence, and 1000 ms mock stream delay. Limits stayed 2000 ms for control/handshake and 120000 ms for completion.

Observed maximum Final commit, 3 runs Real Control UI under the same load
sessions.list 748.1 ms 1541.8 ms
history 596.0 ms 722.2 ms
Control UI HTTP 395.6 ms 300.3 ms
readiness 162.2 ms 193.0 ms
fresh handshake 33.9 ms 68.6 ms

All final runs passed every budget with zero operation failures and zero measured plugin metadata rescans. Three repeats completed 96 turns, 384 updates, and 1205 history samples. The real browser connected, showed live session updates, and rendered the synthetic streaming reply without page errors. Full captures were inspected; the first capture caught a transitional blank render, while subsequent captures show the updates and reply. All 35,152 source/build/dependency hashes matched after both proofs.

Before rebase, the WebSocket-only attempt failed sessions.list at 2116.7 ms. The combined change passed three runs (list 891.7 ms/history 645.2 ms) and a browser run (list 1950.9 ms). A complete lightweight native-write trace recorded 5236 events in 353 appends, with 127.3 ms total append occupancy during 10.4 s of load; it passed the unchanged budget with zero trace losses. Counts cover complete load-window batches, not final shutdown writes. The slowest list request still waited about 1356 ms before dispatch and spent 12 ms inside its handler.

These sequential local runs are not a randomized throughput comparison, and intervening main changes also affect baseline cost. Event-loop utilization still reaches 1 and readiness frequently reports degraded health. No universal latency or memory-leak claim follows.

Validation:

  • 226 distinct focused tests across 22 files passed before rebase. Deterministic pre-fix failures cover 64 per-event opens versus one batch, duplicate path validation, buffered-message starvation, and missing/incomplete timeline evidence.
  • Rebased owner checks passed, including the timeline writer, runtime transport, existing-store discovery, run-loop shutdown, benchmark parser, and real chat timeline correlation. Additional main-interaction checks passed: six durable browser-input admission cases, three delete/archive/recover ordering cases, four current-session history receipt cases, and two durable-admission abort cases.
  • pnpm build sourcePerformance and pnpm ui:build passed after rebase. Fresh Codex autoreviews passed their configured P0-only scope; this is not an all-priority review claim.
  • The initial changed gate passed types, guards, and core lint but failed two explicit throws inside finally. Cleanup was restructured; the targeted changed gate then passed on Testbox run 33347056069, wrapper exit 0 and lease stopped. The first full CI run 33347261488 exposed the test-ordering defect described below; exact-head CI run 33347957849 is SUCCESS. Fresh PR rollup: 196 successful checks, 39 skips, one neutral, no failures; merge state CLEAN.
  • CI also exposed a deterministic test-ordering race in secret-owner recovery, reproduced locally. The existing channel manager acknowledges startup handoff before invoking the plugin on a later turn (documented by its existing sibling test and commit 16e5d6692dc). WebSocket fairness exposes that legal ordering. The fixture now awaits per-account plugin-start signals after start/reload ACKs, preserving every exact count, order, token-isolation, and lifetime assertion without retries or timeout changes. All 14 isolation tests, three handoff-contract tests, typed lint, and fresh P0 review pass.
  • A CPU-profile attempt is retained as failed measurement evidence: post-load clock calibration took 1347 ms, exceeding its unchanged 1000 ms diagnostic cap, and threw during shutdown. The strict harness rejected the result; no benchmark summary was accepted. The successful lightweight append trace does not erase that failure. An earlier partial CPU trace also failed its calibration cap; only independently reconciled transport intervals were used.

Reproduction:

node scripts/bench-gateway-concurrency.ts --entry dist/entry.js --runs 3 --warmup 0 --concurrency 32 --session-count 48 --session-updates 128 --session-update-clients 4 --history-clients 3 --history-burst 5 --subscribers 6 --visible-observer --stream-chunk-delay-ms 1000 --cadence-ms 100 --timeout-ms 120000 --max-control-ms 2000 --max-handshake-ms 2000 --output .artifacts/gateway-mixed-32.json --json

Local proof additionally redirected Gateway logs into the task artifact directory. Browser proof used the same benchmark with the real built Control UI and a fresh browser context. Its first pre-rebase recorder invocation omitted the repository TypeScript loader and failed before starting a Gateway; the corrected invocations passed.

Named follow-ups: residual session-preparation/transaction work; duplicate Git revision preparation for unborn session workspaces; cold health-check package loading; the file-helper short-write defect; and the separately discovered model-alias raw-to-prepared ownership inconsistency. None is claimed fixed by this PR. Material SQLite redesign remains outside this change.

Latest ClawSweeper comment checked before landing: acknowledgement only, with no published Rank-up moves to apply. Fresh independent Codex reviews and exact-head CI are complete; no ClawSweeper approval is claimed.

@steipete
steipete requested a review from a team as a code owner August 31, 2026 01:09
@clawsweeper

clawsweeper Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime cli CLI command changes scripts Repository scripts agents Agent runtime and tooling size: L maintainer Maintainer-authored PR size: XL and removed size: L labels Aug 31, 2026
@steipete
steipete force-pushed the codex/gateway-stall-attribution branch from 61f5a19 to 840024d Compare August 31, 2026 01:19
@steipete
steipete merged commit c60db01 into main Aug 31, 2026
242 checks passed
@steipete
steipete deleted the codex/gateway-stall-attribution branch August 31, 2026 01:56
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 31, 2026
…enclaw#133683)

* fix(gateway): reduce control-plane stalls during concurrent turns

* fix(bench): validate timeline evidence after gateway cleanup

* test(gateway): await account startup after lifecycle handoff
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling cli CLI command changes docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR scripts Repository scripts size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant