Skip to content

perf(gateway): avoid redundant active-run projection scans - #185224

Merged
steipete merged 3 commits into
mainfrom
steipete/perf-visible-active-run-projector-20261026
Oct 27, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/perf-visible-active-run-projector-20261026

Conversation

@steipete

@steipete steipete commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Session-list page preparation repeats RPC-source filtering and allocation, while lifecycle-event routing rebuilds the entire source inventory to find one run.

User Impact

Lower active-run projection overhead with unchanged session visibility, queued/running state, terminal persistence, and Gateway isolation. No configuration or storage changes.

Why This Change Was Made

Use the controller owner's existing run-ID index for scoped event lookup. Collect scoped correlation references during the same pass that collects visible active runs, keeping hidden/queued references before visibility filtering. Build fresh RPC snapshots directly instead of allocating intermediate arrays per source.

The source registry already owns insertion/removal. No new cache or invalidation mechanism is needed. A registration-only projection cache would be incorrect because claims, session identity, abort state, and terminal visibility can change while a source remains registered. Production delta: 16 additions / 17 deletions (net −1 line).

A focused CI repair also preserves module-owned event observers across Gateway fixture resets. Initial setup previously removed the eager agent.wait listener while its module still considered it installed. The test runner continues to clear subscriptions between files.

Evidence

Both work-count regressions fail on baseline 1a6c4fb4de3ced4c5954a0d06a43fdbb279f7e19 and pass with this change:

  • A lifecycle-start event performs 2 → 0 full RPC-registry enumerations.
  • Preparing a projector for 34 sources performs 68 → 34 Gateway-scope reads.

Owner measurements use 34 real synthetic controller reservations/registered queued sources in an unbound Gateway scope, 65 rotating caller offsets, and 50-row pages (34 active, 16 idle). These are caller offsets, not WebSocket clients. Five counterbalanced AB/BA pairs, 3,000 iterations per arm per pair (15,000 per arm), with timing and sampled-allocation passes separated. Setup, work-count instrumentation, warmup, and cleanup are excluded. Reported values are arm means; allocation sampling includes objects collected by minor and major GC.

Owner workload Main-thread CPU before → after Sampled allocation before → after
50-row active-run page 69.506 → 64.573 µs/page (−7.10%) 228,280 → 212,875 B/page (−6.75%)
Scoped event source lookup 2.859 → 0.139 µs/lookup (-95.13%) 15,263 → 521 B/lookup (-96.58%)

Local Mac 1-minute host load, mean (range) across each arm: page: base 49.45 (38.36–62.23), candidate 48.68 (35.57–63.28); event: base 31.98 (28.74–36.15), candidate 30.63 (27.95–33.52). Every paired CPU/allocation delta favored the candidate.

The event microbenchmark compares the former snapshot/filter call contract with getRpcSourceForGateway; the subscription regression exercises actual lifecycle-event routing. The page microbenchmark calls the actual projector and replays the saved baseline owner modules at their original module URLs. Measured candidate: 34e373ae910d63279061fe3f0ad9f9a0bc8d30e6, followed by a patch-identical rebase onto 50b9e88fd3c3c038efecdd77ae53f1a1a704e6c2. The runtime patch is unchanged; subsequent CI repairs affect only benchmark iterator typing and test-fixture listener lifetime. PR CI runs the final pushed head.

Predeclared acceptance: equivalent outputs, elimination of redundant scans/scope reads, lower CPU/allocation with modest production deletion, and no valid adverse evidence. This is the approved deletion fast path: no whole-Gateway stress run, RPC latency/loop percentiles, or GC-rate claim. Production-scale transport behavior is outside these owner measurements.

Reproduce with node --expose-gc --import ./scripts/tsx.mjs scripts/perf/active-run-projector-measure.ts --state-dir .local/active-run-measure-unique --workload page --iterations 3000 (use a fresh state directory each time). Use --workload event, --allocation, and baseline --owner-dir / --event-lookup scan as documented in the script header. The shared performance README is unchanged.

Validation: 104 focused tests passed across session-active-runs.test.ts, server-runtime-subscriptions.test.ts, and session-controller.rpc-sources.test.ts (192.73 s including cold worker preparation; Gateway tests 41.59 s). The 29 eager-import/PR-wrapper closure tests passed (56.11 s). Export-name collision guard, changed-file lint, formatting, and diff checks passed. Independent subagent review (autoreview route unavailable): scoped-clean, no actionable P0/P1/P2 findings; the helper refused its provider selector before inference, and operator configuration was unchanged. PR CI provides broad validation.

Initial CI found a benchmark iterator return-type mismatch and a lifecycle-test timeout. The iterator now explicitly returns undefined, matching MapIterator; tsconfig.scripts.json passes. The lifecycle timeout (agent.wait returned status: "timeout" instead of "ok" at line 518) reproduced identically on unchanged base 50b9e88fd3c3c038efecdd77ae53f1a1a704e6c2 and the PR head. Preserving the module observer fixes the existing server.chat.gateway-server-chat-lifecycle.test.ts regression; it and test-helpers.server-state-reset.test.ts pass all 7 tests with unchanged timeout/assertion contracts. Both small repairs passed independent review, formatting, and scoped lint.

Final head: 72b66631c7cbf80f73092c6aa5f047d057c20165, rebased onto 49aa6fca9a21fb21e31adb6c6e372451ba097b6a. Exact-head CI completed successfully, including all three PostgreSQL conformance shards; the required CI gate is green. GitHub Codex review completed on this exact head with no findings. The PR remains ready and unmerged for maintainer handoff.

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

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime scripts Repository scripts size: M labels Oct 27, 2026
@steipete
steipete marked this pull request as ready for review October 27, 2026 00:06
@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-27T00:30:55.816946Z 72b6663 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.

@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: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed 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 maintainer review before merge.

What this changes

This PR replaces full-registry lifecycle lookups with indexed lookup and combines active-run projection passes.

Example: Prepare a session-list page with 34 registered RPC sources.

  • Before: Projector preparation checks Gateway scope 68 times.
  • After: Projector preparation checks Gateway scope 34 times while retaining queued and hidden correlation references.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, owner-preserving optimization supported by bounded measurements and reported regressions; broad validation remains unresolved.
Proof confidence 🦐 gold shrimp (3/6) The maintainer-authored proof exemption applies; supplied evidence exercises the production projector and source registry in a bounded synthetic owner workload, without claiming shipped Gateway transport coverage.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Preparing session activity pages and routing lifecycle events spend avoidable main-thread CPU and allocation.
Reason: The maintainer-authored direction removes measured waste without changing configuration, persistence, visibility, or lifecycle ownership.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it removes demonstrable redundant work using existing owners, with no actionable introduced defect found; two exact-head CI failures remain unattributed.

Priority: P2
Reviewed head: 48f8b8a6b6aea5fb8a4834ded10ce0720cc210d9

Before merge

None.

Findings

None.

Agent review details

How this fits together

The session controller owns RPC sources; Gateway lifecycle subscriptions and session presenters consume them to route events and report session activity.

flowchart LR
  A[Controller reservations] --> B[RPC source registry]
  B --> C[Run ID lookup]
  C --> D[Lifecycle subscriptions]
  B --> E[Scoped active run projector]
  E --> F[Session list and snapshots]
Loading

Technical review

Best possible solution:

Retain the existing controller index and combined projection pass, then resolve the CI failure attribution before landing.

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

Source inspection establishes duplicate scope checks and full-registry event scans on current main; the PR reports baseline-failing work-count checks, but this review ran no target code.

Is this the best way to solve the issue?

The patch follows the smallest complete fix: preserve scoped visibility and correlation while reusing the existing run-ID index and removing intermediate allocations.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 07e6f334c2ea.

Provenance checked

  • Controller-owned RPC sources and scoped lifecycle lookup keeps the original intent (36e277d: The session-controller cutover established one owner for source identity, turns, queues, cancellation, and settlement.)
  • Prepared active-run projection keeps the original intent (06c7cec: Session filtering needed prepared activity metadata before server pagination while preserving visibility.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source -1, Tests +40, Other +226. Total +265 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 16 17 -1
Tests 2 41 1 +40
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 226 0 +226
Total 6 283 18 +265

Review metrics

Metric Value Why it matters
Production versus test delta Production +16/−17; tests +41/−1 The runtime optimization removes a net line; added tests cover redundant work and projector scope isolation.

Labels

Label changes:

  • add P2: This is a bounded Gateway CPU and allocation improvement without an established urgent user-facing regression.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: This is a bounded Gateway CPU and allocation improvement without an established urgent user-facing regression.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

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

  • Inspect the script-types diagnostic and lifecycle timeout to establish whether either exact-head failure is caused by this patch.

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 26, 2026, 8:23 PM ET / October 27, 2026, 00:23 UTC.

Reuse the controller-owned run ID index for lifecycle event lookup, retain scoped correlation refs during active-run collection, and flatten fresh RPC snapshots without intermediate arrays. Gateway visibility and live run state remain caller scoped.
@steipete
steipete force-pushed the steipete/perf-visible-active-run-projector-20261026 branch from 48f8b8a to 72b6663 Compare October 27, 2026 00:27
@steipete
steipete merged commit 8e85d1e into main Oct 27, 2026
137 of 139 checks passed
@steipete
steipete deleted the steipete/perf-visible-active-run-projector-20261026 branch October 27, 2026 00:54
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 27, 2026
…185224)

* perf(gateway): avoid redundant active-run projection scans

Reuse the controller-owned run ID index for lifecycle event lookup, retain scoped correlation refs during active-run collection, and flatten fresh RPC snapshots without intermediate arrays. Gateway visibility and live run state remain caller scoped.

* perf(gateway): type active-run benchmark iterator completion

* test(gateway): preserve module observers across fixture resets
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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: M 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