Skip to content

perf(sessions): reduce preparation waits across sessions - #160183

Merged
steipete merged 5 commits into
mainfrom
perf/l162-store-lane-holds
Sep 28, 2026
Merged

steipete merged 5 commits into
mainfrom
perf/l162-store-lane-holds

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes long response-start waits when many Control UI sessions prepare replies on one Gateway: one session can hold the shared store lane while waiting for the SQLite broker and physical writer.

User Impact

Independent existing sessions can prepare concurrently. Same-session ordering, live admission checks, and placement settlement remain protected. No configuration, protocol, schema, durability, retention, or update migration changes are required.

The measured first-delta improvement comes with a tradeoff: event-loop p99 increased, and ACK-to-provider p50 changed little. Remaining main-thread stalls still need work.

Why This Change Was Made

The existing queue owner now accepts complete conflict-key sets, preserves FIFO between overlapping waiters, and treats an unkeyed task as a full-store barrier. Barriers wait for earlier accepted work and exclude later writers. Cancellation removes waiting work only; active work retains settlement and caller context. Reentrancy requires complete held-key coverage.

Only audited canonical reply admission, qualified chat admission, and eligible existing-session initialization opt in. Creation hooks, parent forks, legacy-main retirement, rollovers, unscoped validators, migration, and placement retain store-wide exclusion. A creation observed after waiting retries before invoking its hooks. The initializer's shared result type moved to a type-only module to satisfy its existing line-growth ratchet; both consumers moved with it.

Related: #159632 changes admission worker custody; #159527 cleans up the reply owners. Their current diffs were inspected and reconciled with these call sites. Neither implements keyed store scheduling; the claim lifecycle and cleanup logic are unchanged here.

Evidence

Same isolated AWS c7a.8xlarge, Gateway pinned with taskset -c 0-3, four driver processes, Node 26.9.0, pnpm 12.5.1. Each invocation used 100 WebSocket clients / 50 active sessions, three sequential turns per client, 40 mock chunks/second, seed 1, and fresh synthetic state. Queue/broker observation was enabled in both variants. Baseline: c849a831a17fd4508684a5cda94e688b0c00c7eb. No real provider or browser contexts were used.

Steady-state latency means turns 2 and 3, 100 observations per complete run. CPU covers the entire fixed 150-turn workload; lower elapsed time therefore does not inflate the CPU win. Percentiles are independent and must not be added.

Interleaved run ACK → provider p50 / p99 (s) Send → first delta p50 / p95 (s) Main CPU / load wall (s) ELD p99 / max (ms) Blocks >100 ms
A1 baseline 11.913 / 15.593 15.974 / 19.007 83.652 / 88.284 59.57 / 282.07 3
B1 candidate 12.015 / 13.094 12.935 / 13.732 75.565 / 76.687 80.35 / 352.06 11
A2 baseline 11.582 / 16.877 16.105 / 18.166 84.278 / 89.155 60.16 / 406.85 4
B2 candidate 11.133 / 16.633 12.248 / 16.986 78.157 / 80.467 71.43 / 253.36 7
A3 baseline 12.495 / 16.974 16.760 / 18.249 85.594 / 89.369 62.95 / 327.68 12
B3 candidate, correlation limitation 13.326 / 15.529 14.245 / 16.190¹ 81.044 / 120.023¹ 67.70 / 300.42¹ 12

The first two complete pairs delivered 150/150 replies with no integrity errors. Their median first-delta p50 fell 21.5%, while total main-thread CPU fell 8.5%. ACK-to-provider p50 was essentially unchanged. Main-thread busy percentage rose from 94.53–94.75% to 97.13–98.54%; this is a latency/CPU-cost improvement with worse event-loop tails, not a claim that the demo stall objective is solved.

Shared-store waiting per steady turn fell from p50 6.280–6.299 s to 0.590–0.948 s; its median fraction of ACK-to-provider time fell from 54.5–55.8% to 4.8–9.3%. Time-weighted shared queue depth fell from 15.39–15.44 to 1.27–2.32. Initialization queue wait p50 fell from 2.597–2.772 s to 14.0–26.5 ms. Individual initialization holds increased from 393–410 ms to 669–759 ms, but those holds now overlap across distinct keys. Their measured nested-queue waits were 367–378 ms before and 646–727 ms after; the remaining 29–30 ms before / 11–13 ms after is a residual wall-time bound, not exclusive CPU attribution. Admission hold p50 was 1.04–1.06 ms before / 2.39–2.55 ms after; admission queue wait p50 fell from 868–968 ms to 25.9–29.3 ms.

¹ B3 retained 149/150 harness-correlated replies, with one pending input and an unattributed terminal execution. Server input→execution correlation proves that execution delivered 66 text deltas and a text-bearing final, 33.334 ms before the input's empty final. The harness cannot retrospectively adopt an already-terminal execution. All 12 empty-input cases across the candidate runs have explicit execution mappings and completed text replies; these cases occurred 4/150 per candidate and 0/150 in these baselines. The frequency shift and durable transcript coverage remain limitations. B3's idle deadline tail excludes it from aggregate CPU/throughput claims. The original result is retained; streaming framing and harness correlation were not changed. An SSH ownership-renewal failure during that run was reconciled through the native Crabbox owner before further commands; all harness Gateway children exited and synthetic state was removed.

Validation:

  • node scripts/run-vitest.mjs src/shared/store-writer-queue.test.ts --maxWorkers=1: 17 passed, 24.11 s wall on AWS. The disjoint-progress regression fails against the original queue at the expected ordering assertion.
  • node scripts/run-vitest.mjs src/sessions/session-lifecycle-admission.test.ts --maxWorkers=1: 31 passed, 11.09 s wall.
  • node scripts/run-vitest.mjs src/gateway/server-worker-placement-move-barrier.test.ts --maxWorkers=1: 10 passed, 21.59 s wall.
  • Existing initialization-conflict and store-writer sibling files: 14 passed across two shards, 22.96 s wall.
  • Both builds passed: baseline 6m45.5s, runtime candidate 6m46.1s. The later extraction changes type-only imports/declarations; runtime behavior is unchanged.
  • node scripts/check-changed.mjs: passed in 772.90 s wall on the exact committed source tree; changed-core lint reported 0 warnings and 0 errors. The initial line-growth rejection was fixed through the type extraction above.
  • Harness protocol contract tests passed for baseline and candidate. No hosted workflow was dispatched or rerun for proof.
  • Local stale TypeScript dependencies initially prevented test collection. One frozen/prefer-offline install repaired them; local queue/admission/placement suites subsequently passed. The reproducible AWS costs above exclude this host's saturation.
  • Deslop completed; independent Codex autoreview is scoped-clean through P2, with no accepted/actionable findings.
  • Production +155 / −48 = +107 LOC; tests +316 LOC; docs +9 LOC. Production growth implements conflict tracking, full-store barriers, reentrancy coverage, and safe caller selection.

Release-note context: reduce cross-session response preparation waits on shared Gateways while retaining same-session and placement lifecycle ordering.

@clawsweeper

clawsweeper Bot commented Sep 28, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: L labels Sep 28, 2026
@steipete
steipete marked this pull request as ready for review September 28, 2026 05:56
@steipete
steipete enabled auto-merge (squash) September 28, 2026 06:04
@clawsweeper

clawsweeper Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 28, 2026, 9:03 AM ET / 13:03 UTC (Revision 5).

ClawSweeper review

What this changes

The branch lets independent existing sessions prepare replies concurrently through a keyed store queue while preserving ordering for overlapping sessions and store-wide operations.

Merge readiness

⛔ Blocked before merge - 3 items remain

Current main still serializes session store work, so this PR remains useful. Its Gateway load evidence supports the improvement, but the measured event-loop tail regression still needs an explicit Gateway owner decision.

Priority: P2
Reviewed head: 726fc1742f3b97562f399d2df81fab09cd6203f2
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch has useful boundary coverage and credible Gateway load evidence, with one measured performance tradeoff awaiting owner judgment.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The changed store queue and Gateway admission paths were exercised in reported paired loads with real Gateway WebSocket clients and a mock provider; two complete candidate runs delivered 150/150 replies and improved first-delta latency. The third run has a disclosed correlation gap, and no browser or real-provider result is claimed. The diff changes no stored-data contract.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The changed store queue and Gateway admission paths were exercised in reported paired loads with real Gateway WebSocket clients and a mock provider; two complete candidate runs delivered 150/150 replies and improved first-delta latency. The third run has a disclosed correlation gap, and no browser or real-provider result is claimed. The diff changes no stored-data contract.
Evidence reviewed 9 items Current main lacks keyed scheduling: The fetched main revision drains one pending store writer at a time; the central concurrency change is still absent.
Introduced queue behavior: The pinned diff adds concurrent disjoint-key execution, overlapping-key FIFO selection, and full-store barriers.
Bounded caller opt-in: Reply initialization uses a keyed lane only for a qualified existing session and retries if it discovers creation after waiting.
Findings None None.
Security None None.

How this fits together

Gateway chat sends and channel replies pass through session admission and shared store coordination before reply preparation. The prepared reply then streams back to the client.

flowchart LR
A[Chat send] --> B[Gateway admission]
B --> C[Session store queue]
C --> D[SQLite writer]
D --> E[Reply preparation]
E --> F[Streamed response]
Loading

Decision needed

Question Recommendation
Does the measured first-delta gain justify the higher Gateway event-loop p99 and more long stalls under this load? Accept the measured tradeoff: Explicitly accept the observed event-loop tail cost in exchange for faster first reply output.

Why: The paired runs measure competing user-facing outcomes, and the repository defines no threshold that resolves their balance automatically.

Before merge

  • Resolve merge risk (P1) - In the two complete paired loads, event-loop p99 rose from about 60 ms to 71–80 ms and stalls over 100 ms rose from 3–4 to 7–11; a Gateway owner has not explicitly accepted the effect on other traffic.
  • Complete next step (P2) - Obtain explicit Gateway owner acceptance of the measured event-loop tail increase, or reduce it and remeasure before merge.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
Agent review details

Security

None.

PR surface

Source +107, Tests +316, Docs +9. Total +432 across 13 files.

View PR surface stats
Area Files Added Removed Net
Source 9 155 48 +107
Tests 3 316 0 +316
Docs 1 9 0 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 13 480 48 +432

Review metrics

Metric Value Why it matters
Production versus test growth production +107 net LOC; tests +316 LOC The stated production growth implements conflict tracking and barriers, with tests for ordering and cancellation.
Paired Gateway load first-delta p50 −21.5%; event-loop p99 about +12–21 ms Both measured outcomes matter to the Gateway owner's performance decision.

Merge-risk options

Maintainer options:

  1. Accept the load envelope (recommended)
    A Gateway owner can explicitly accept the measured event-loop tail cost in exchange for faster first reply output.
  2. Reduce scheduling pressure
    Constrain keyed dispatch and repeat the paired workload to check both first-delta and event-loop tails.

Technical review

Best possible solution:

Retain one keyed queue with complete conflict identities and full-store barriers under an owner-approved Gateway concurrency envelope.

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

Yes: the PR specifies a paired Gateway and WebSocket workload, while current main retains the serial queue. This read-only review did not rerun the workload.

Is this the best way to solve the issue?

Yes at the ownership boundary: the shared queue is the narrow place to schedule independent sessions while retaining full-store barriers. The acceptable event-loop cost remains a maintainer choice.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded Gateway performance improvement with a measured but non-emergency responsiveness tradeoff.
  • merge-risk: 🚨 availability: Concurrent keyed preparation measurably increases long event-loop delays under the reported load.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The changed store queue and Gateway admission paths were exercised in reported paired loads with real Gateway WebSocket clients and a mock provider; two complete candidate runs delivered 150/150 replies and improved first-delta latency. The third run has a disclosed correlation gap, and no browser or real-provider result is claimed. The diff changes no stored-data contract.
  • proof: sufficient: Contributor real behavior proof is sufficient. The changed store queue and Gateway admission paths were exercised in reported paired loads with real Gateway WebSocket clients and a mock provider; two complete candidate runs delivered 150/150 replies and improved first-delta latency. The third run has a disclosed correlation gap, and no browser or real-provider result is claimed. The diff changes no stored-data contract.

Evidence

What I checked:

  • Current main lacks keyed scheduling: The fetched main revision drains one pending store writer at a time; the central concurrency change is still absent. (src/shared/store-writer-queue.ts:156, 6d6ea35f7616)
  • Introduced queue behavior: The pinned diff adds concurrent disjoint-key execution, overlapping-key FIFO selection, and full-store barriers. (src/shared/store-writer-queue.ts:159, 726fc1742f3b)
  • Bounded caller opt-in: Reply initialization uses a keyed lane only for a qualified existing session and retries if it discovers creation after waiting. (src/auto-reply/reply/session.ts:403, 726fc1742f3b)
  • Admission and placement boundaries: Final session admission validation remains inside the store writer; placement moves retain an unkeyed barrier. (src/sessions/session-lifecycle-admission.ts:653, 726fc1742f3b)
  • Ordering regression coverage: Added tests exercise disjoint progress, overlapping FIFO order, full-store barriers, cancellation, and reentrancy; the PR body reports the focused suites passing. (src/shared/store-writer-queue.test.ts:256, 726fc1742f3b)
  • Gateway load proof and tradeoff: The PR body reports paired runs through a real Gateway with WebSocket clients and a mock provider. Two complete candidate runs delivered 150/150 replies each, with median first-delta p50 down 21.5%; event-loop p99 rose from about 60 ms to 71–80 ms, and stalls over 100 ms rose from 3–4 to 7–11. A third run discloses a harness correlation limitation.

Likely related people:

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

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 (4 earlier review cycles)
  • reviewed 2026-09-28T06:04:59.311Z sha ebfe5d8 :: blocked before merge. :: none
  • reviewed 2026-09-28T07:26:48.036Z sha dbe10a6 :: blocked before merge. :: none
  • reviewed 2026-09-28T10:01:31.709Z sha 27ed9bf :: blocked before merge. :: none
  • reviewed 2026-09-28T11:10:33.475Z sha c30dc25 :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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. labels Sep 28, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Admin-merging: the red checks on head 726fc17 were each checked, and none reproduces as a regression from this change.

  • checks-node-changed-4, test/e2e/qa-lab/runtime/channel-progress-presentation.e2e.test.ts: CI hit an overall 120-second timeout, not an ordering assertion. It was replayed on one AWS box with Node 24.19.0 and two CPUs per run, 5/5 full-file runs and 80/80 tests on this head and on its merge base b95394a. The CI-failing case passed five times on each ref with near-identical medians (76.120 s head vs 76.049 s base). Passing replays do not prove the CI timeout is fixed; it is recorded as unreproduced.
  • Earlier on this PR, bot.create-telegram-bot.history.test.ts hit grammY's 10-second webhook deadline in CI. The history file passed 60/60 and its nine-file shard 351/351 on both head and base. That fixture injects its reply resolver and does not go through the keyed session-init path.
  • checks-ui-e2e (4/9) session-progress-widget and checks-ui-e2e (2/9) config-controls-visual are mocked-Gateway UI tests that do not reach the server store queue; the progress-widget failure also appeared on perf(gateway): throttle sidebar narration updates #160002.
  • openclaw/ci-gate aggregates the above.

164 other checks passed. On the merged tree, the queue/admission/placement/session-init suites (72 tests) pass, the changed-lane gate passes with zero lint findings, and Codex autoreview is clean through P2. The PR body has the pinned 100/50 A/B: shared-lane wait p50 6.29 s → 0.77 s, first delta p50 −21.5%, main CPU −8.5%.

@steipete
steipete merged commit 71a5516 into main Sep 28, 2026
232 of 237 checks passed
@steipete
steipete deleted the perf/l162-store-lane-holds branch September 28, 2026 17:37
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 29, 2026
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 merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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. size: L 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