Skip to content

perf(gateway): reuse prepared facts across control-plane reads - #133477

Merged
steipete merged 2 commits into
mainfrom
codex/gateway-stall-followup
Aug 30, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/gateway-stall-followup

Conversation

@steipete

@steipete steipete commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Reduces avoidable work that delays Gateway control requests and the Control UI during concurrent turns. This extends #133429; it does not claim that every observed multi-second tail has a single established cause or is now eliminated.

Why This Change Was Made

The control plane shares an event loop with agent startup and session projection. The fix carries prepared facts to their consumers and removes duplicate work at the owning boundaries:

  • Config resolution copies only the prepared source config, retaining resolution facts and mutation isolation, instead of cloning refresh-only manifests and auth stores. Standalone preparation remains intact.
  • Static HTTP requests select the presentation agent without reading workspace identity. Direct HTML and SPA fallback share one serving path; safe-open descriptor and size flow into the asynchronous reader without a second stat. Containment, link checks, allocation/chunk limits, short reads, EOF and closure remain covered. Reads are bounded by the pinned size, not an atomic-content guarantee.
  • History consumes settled catalogs without rendering unused live model metadata; current startup/metadata still validate generation and readiness. Cursor responses skip unused defaults. Previews read one current canonical entry after each yield instead of materializing and caching whole stores.
  • Lightweight rows skip historical-model resolution. Transcript token/cost policy lives in its existing fallback owner, which consumes the prepared agent/token facts. ACP projection remains bound to the supplied original entry, preventing adoption of a replacement session's runtime.
  • Settings preparation creates one final runtime snapshot, removing the intermediate factories and repeated conversion. Locked file reads, merge precedence, trust policies, runtime-only writes and fresh-manager reload behavior are unchanged.

The benchmark now enforces all measured load-control budgets, saves violations in JSON, and exits nonzero after retaining evidence. Setup subscriptions and warmup remain excluded; handshakes retain their separate budget.

User Impact

Less repeated discovery, copying and projection during concurrent use. No new cache, dependency, configuration, schema, wire protocol, persistent-store, locking or credential-resolution policy. No production Gateway was exercised. Production: 181 added / 243 removed, net -62; benchmark tooling: net +3; tests: +588 / -131, net +457.

Evidence

Built and exercised exact head b1776b9e294b962acec4182138b3441b7c3fa089, rebased on main 7acb95c3ae6bf28aeec76c86987fef8f4e78a6f6.

  • Full node scripts/check-changed.mjs passed: formatting, type checks, changed lint, dead exports, runtime cycles and ownership/storage guards. Runtime and Control UI builds passed.
  • Owner suite: 612 tests passed. After the final row refactor, its four relevant suites passed 342 tests; after moving HTTP identity coverage into its own file, both HTTP suites passed 30 tests. These runs overlap and are not summed as unique coverage.
  • Fresh Codex P0-scoped review found no actionable P0 finding; this is not an all-priority automated review. Manual review traced the changed owners, callers, siblings and dependency contracts.
  • Final three unprofiled runs passed: 96 turns, 384 updates, 3695 history requests, zero operation failures and no budget violations. Final real-browser run also passed, showing session updates and a rendered synthetic reply while load remained active, with no browser errors.
  • The final CPU-profiled run failed the unchanged history budget: max 2904 ms, p99 1485 ms. The final browser history maximum was 1961 ms. All 273 readiness samples in the three-run test and all 102 in the browser run were degraded; event-loop utilization reached 1. Remaining stalls and saturation are not claimed fixed.

The earlier CI failure in the descriptor test was reproduced and repaired without changing the production close path. An intermediate format gate and a file-length lint failure were also fixed; the final full local gate passed. Exact-head CI completed successfully on b1776b9. A fresh landing Codex P0 review also found no actionable P0 finding. The latest ClawSweeper review had no correctness/security finding; its remaining Rank-up move to finish exact-head CI is satisfied. The remaining profiled history failure above remains an open follow-up, not a claim of complete stall resolution.

Owner regressions were observed failing before repair: static requests performed six workspace identity reads; ready/history reads rendered discarded metadata; preview materialized a whole store; five lightweight rows resolved historical models they never consumed. Selected-model/thinking output and the corresponding security/lifecycle contracts remain asserted. The earlier prepared-config, pinned-read and stale-ACP regressions remain covered.

Final CPU evidence agrees with the owner regressions: discarded public model rendering beneath history/startup fell from 139 samples / 171.2 weighted ms to zero; historical-model resolution beneath ordinary list rows and history/startup also had zero final samples. The remaining eight historical-model samples were all within the intended transcript-usage fallback. Baseline and final runs issued 950 and 1205 history requests respectively. Zero samples alone do not prove zero calls; the regressions independently check invocations. Unequal workloads do not establish an overall speedup percentage.

Within the final shared history/startup handler, synchronous timeline emission accounts for 5.120 seconds of weighted inclusive samples, including 3.363 seconds at native writeBuffer. These are sampled intervals, not exact syscall durations. The timeline owner still appends each enabled event synchronously. There is no common V8/harness clock anchor, so this cost is not causally assigned to the worst history request.

Observed maxima in milliseconds; runs from this refactor pass are retained, including failures. “Pre-refactor” is 8e2b93ee (latest-main rebase plus the earlier patch); “intermediate” is before the final lightweight-row change. Same workload and limits throughout; browser and CPU instrumentation are identified separately.

Runtime / measurement UI HTTP Readiness sessions.list History Budget
Pre-refactor, early / 3 runs 718 567 406 725 PASS
Pre-refactor, early CPU / 1 run 838 695 427 837 PASS
Intermediate refactor / 3 runs 3559 2293 4469 4134 FAIL
Intermediate refactor CPU / 1 run 2766 2350 2535 2647 FAIL
Pre-refactor, adjacent / 1 run 1987 1399 1415 1984 PASS
Intermediate refactor, adjacent / 1 run 1264 813 426 1262 PASS
Final b1776b9 / 3 runs 1279 879 746 1280 PASS
Final b1776b9 CPU / 1 run 1047 847 535 2904 FAIL
Pre-refactor, browser / 1 run 3156 2660 2660 2735 FAIL
Final b1776b9, browser / 1 run 1929 1271 949 1961 PASS

All listed operation-failure counters were zero; a failed latency gate still counts as a failure. The adjacent old/new runs used exact runtime source and the same workload, but the earlier old-source baseline itself moved from about 10 seconds to 43 seconds per turn batch. Variation remains unexplained; it is not attributed to host noise or declared a product defect. Event-loop saturation remains; no memory leak has been established.

Reproduction (fresh HOME/state/config, mock provider and loopback ports; task proof also directs logging to its owned artifacts):

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-followup.json --json

Two test-fixture repairs are included: descriptor closure is observed at the real native close instead of probing a reusable numeric descriptor after an await; the abort/idempotency smoke uses the shared prepared-runtime RPC fixture with its unchanged 2000 ms response budget. The latter failed twice in full-file order and in isolation, then passed in isolation and in the full file. These test repairs are not offered as production stall causes.

Named follow-up: batch diagnostics timeline writes without losing trace completeness. The retained synchronous timeline sink accounts for substantial native I/O in the profile. First correlate emission with an over-budget request using a common clock. A batching design also needs explicit emission visibility, bounded overflow, immediate-exit/graceful-flush contracts and a benchmark artifact boundary after owned shutdown. This PR does not disable the timeline, weaken its evidence, or change those contracts.

Browser proof

Real built Gateway and Control UI, a synthetic streaming provider, fresh HOME/state/config, loopback only. The before run failed the latency gate while still rendering the reply; the final run passed. Screenshots show the reply while the turn is still busy; the final recording continues through completion. This is a responsiveness check, not a visual redesign or a controlled overall speedup claim. Captures were inspected for secrets and unrelated data.

Before this refactor (8e2b93ee):

Before: synthetic reply under concurrent load

After (b1776b9e):

After: synthetic reply under concurrent load

Final browser recording:

gateway-refactor-after.webm

@clawsweeper

clawsweeper Bot commented Aug 30, 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 app: web-ui App: web-ui gateway Gateway runtime scripts Repository scripts commands Command implementations agents Agent runtime and tooling size: L maintainer Maintainer-authored PR labels Aug 30, 2026
@steipete
steipete marked this pull request as ready for review August 30, 2026 19:30
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: 🎥 video Contributor real behavior proof includes video or recording evidence. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 30, 2026
@clawsweeper

clawsweeper Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 30, 2026, 6:51 PM ET / 22:51 UTC.

ClawSweeper review

What this changes

The PR reduces repeated Gateway control-plane work by reusing prepared configuration, model, session, and static-file facts, while making all measured control-request budgets enforceable in the concurrency benchmark.

Merge readiness

⚠️ Ready for maintainer review - 1 item remains

No blocking correctness or security defect was found in the exact-head refactor. This remains open for normal maintainer review because it is maintainer-authored, carries the protected maintainer label, and exact-head CI is still incomplete.

Priority: P2
Reviewed head: b1776b9e294b962acec4182138b3441b7c3fa089

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A substantial but coherent owner-boundary performance refactor with focused regressions and supplied real browser evidence.
Proof confidence 🐚 platinum hermit (4/6) ✨ media proof bonus Sufficient (recording): The supplied exact-head built-Gateway Control UI browser run and recording exercise the changed HTTP, projection, and concurrent-turn paths and show a rendered synthetic reply while load is active; the separately disclosed profiled history-budget failure limits the performance claim but does not negate the demonstrated after-fix behavior.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (recording): The supplied exact-head built-Gateway Control UI browser run and recording exercise the changed HTTP, projection, and concurrent-turn paths and show a rendered synthetic reply while load is active; the separately disclosed profiled history-budget failure limits the performance claim but does not negate the demonstrated after-fix behavior.
Evidence reviewed 6 items Exact introduced implementation: The pinned PR delta changes the Control UI reader to consume the safe-open descriptor and captured size, preserving descriptor closure while avoiding a second metadata read.
Caller and lifecycle boundary: Only chat.history requests the ready projection; the runtime returns settled catalogs without materializing live metadata, while current startup reads still materialize metadata and retain freshness checks.
Regression coverage: The added tests cover pinned-file truncation, short reads, descriptor closure, ready-versus-current metadata behavior, and all six measured control-probe budget families.
Findings None None.
Security None None.

How this fits together

Gateway control requests read prepared configuration and model data, session state, and Control UI assets before returning chat metadata, session projections, or HTTP responses. This refactor keeps those reads at their existing owners while avoiding redundant discovery on the request path.

flowchart LR
A[Gateway control requests] --> B[Prepared configuration and model facts]
D[Session state and UI files] --> C[Gateway request handlers]
B --> C
C --> E[Chat metadata and session projections]
C --> F[Control UI HTTP responses]
E --> G[Control UI clients]
F --> G
Loading

Before merge

  • Complete next step (P2) - No mechanical repair is identified; the maintainer-authored, protected-label PR should complete ordinary exact-head maintainer and CI review.
Agent review details

Security

None.

PR surface

Source -57, Tests +452, Other +3. Total +398 across 31 files.

View PR surface stats
Area Files Added Removed Net
Source 15 187 244 -57
Tests 15 586 134 +452
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 47 44 +3
Total 31 820 422 +398

Review metrics

Metric Value Why it matters
Production versus test delta production -62; benchmark tooling +3; tests and test support +457 The performance refactor is net-negative in production while adding targeted owner-boundary regression coverage.

Stored data model

Persistent data-model change detected: serialized state: src/gateway/control-ui-static.ts, unknown-data-model-change: src/gateway/control-ui-static.ts, unknown-data-model-change: src/gateway/server-methods/chat-metadata-runtime.ts, vector/embedding metadata: src/gateway/server-methods/chat-metadata-runtime.ts, vector/embedding metadata: src/gateway/server-methods/chat-startup-projection-contract.ts. Confirm migration or upgrade compatibility proof before merge.

Technical review

Best possible solution:

Keep the owner-boundary refactor and land it only after a maintainer reviews the exact head with completed required checks.

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

Not applicable as a conventional issue reproduction; the supplied exact-head benchmark and built-Gateway browser run exercise the changed control-plane paths.

Is this the best way to solve the issue?

Yes. The patch reuses already-prepared facts at the configuration, metadata, session, and static-file owners instead of adding a cache or changing public configuration.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against ee0d376e0fe9.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The supplied exact-head built-Gateway Control UI browser run and recording exercise the changed HTTP, projection, and concurrent-turn paths and show a rendered synthetic reply while load is active; the separately disclosed profiled history-budget failure limits the performance claim but does not negate the demonstrated after-fix behavior.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • remove rating: 🦞 diamond lobster: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P2: This is a bounded Gateway responsiveness improvement with meaningful but non-emergency operator impact.
  • 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. Sufficient (recording): The supplied exact-head built-Gateway Control UI browser run and recording exercise the changed HTTP, projection, and concurrent-turn paths and show a rendered synthetic reply while load is active; the separately disclosed profiled history-budget failure limits the performance claim but does not negate the demonstrated after-fix behavior.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied exact-head built-Gateway Control UI browser run and recording exercise the changed HTTP, projection, and concurrent-turn paths and show a rendered synthetic reply while load is active; the separately disclosed profiled history-budget failure limits the performance claim but does not negate the demonstrated after-fix behavior.
  • proof: 🎥 video: Contributor real behavior proof includes video or recording evidence. The supplied exact-head built-Gateway Control UI browser run and recording exercise the changed HTTP, projection, and concurrent-turn paths and show a rendered synthetic reply while load is active; the separately disclosed profiled history-budget failure limits the performance claim but does not negate the demonstrated after-fix behavior.

Evidence

What I checked:

  • Exact introduced implementation: The pinned PR delta changes the Control UI reader to consume the safe-open descriptor and captured size, preserving descriptor closure while avoiding a second metadata read. (src/gateway/control-ui-static.ts:376, b1776b9e294b)
  • Caller and lifecycle boundary: Only chat.history requests the ready projection; the runtime returns settled catalogs without materializing live metadata, while current startup reads still materialize metadata and retain freshness checks. (src/gateway/server-methods/chat-history-handler.ts:300, b1776b9e294b)
  • Regression coverage: The added tests cover pinned-file truncation, short reads, descriptor closure, ready-versus-current metadata behavior, and all six measured control-probe budget families. (src/gateway/control-ui-static.test.ts:32, b1776b9e294b)
  • Current-main necessity check: Fetched current main still has the prior descriptor reader, while the host-verified test merge applies this PR’s 31-file delta to its pinned main parent; the work is neither already implemented nor superseded. (src/gateway/control-ui-static.ts:376, ee0d376e0fe9)
  • Merged area history: Recent merged Gateway performance work includes prepared display projections and the preceding control-plane stall repair; both support routing this follow-up to the same area owner. (src/gateway/session-utils-store-lookup.ts:452, 8243cc8a361c)
  • Supplied real behavior evidence: The PR body supplies exact-head built-Gateway browser evidence and a recording showing a synthetic reply during concurrent load; it also candidly retains the failed CPU-profiled history-budget run rather than claiming all stalls are fixed. (b1776b9e294b)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Let exact-head required CI complete before the maintainer landing decision.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-08-30T19:36:47.530Z sha d1a5b28 :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the codex/gateway-stall-followup branch from d1a5b28 to b1776b9 Compare August 30, 2026 22:36
@steipete steipete changed the title fix(gateway): avoid redundant work during concurrent turns perf(gateway): reuse prepared facts across control-plane reads Aug 30, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The scope expanded after the prior review. Current head b1776b9 consolidates settings preparation, HTML serving, prepared metadata, previews and lightweight rows; production is net -62 lines. The body now includes final owner/gate proof, before/after browser evidence and all retained latency failures. Three final unprofiled runs and the final browser run passed the unchanged budgets, but the final CPU-profiled history maximum was 2904 ms. No claim that all stalls are resolved; no merge requested.

@clawsweeper

clawsweeper Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. labels Aug 30, 2026
@steipete
steipete merged commit 5c7b30f into main Aug 30, 2026
255 checks passed
@steipete
steipete deleted the codex/gateway-stall-followup branch August 30, 2026 23:39
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 31, 2026
…law#133477)

* fix(gateway): avoid redundant work during concurrent turns

* refactor(gateway): reduce repeated control-plane work
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui commands Command implementations gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: 🎥 video Contributor real behavior proof includes video or recording evidence. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: XL 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