Skip to content

improve: reduce CPU spent broadcasting session activity - #159182

Merged
steipete merged 5 commits into
mainfrom
codex/session-broadcast-projection-20260926
Sep 27, 2026
Merged

steipete merged 5 commits into
mainfrom
codex/session-broadcast-projection-20260926

Conversation

@steipete

@steipete steipete commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Broadcasting session activity spends unnecessary Gateway CPU resolving the same agent identity and allocating status arrays for each child and recipient.

User Impact

Session activity broadcasts use less CPU while preserving payloads, visibility, and current run state. No schema, migration, configuration, or operator change is required.

Why This Change Was Made

The run registry owns snapshot acquisition; its existing projection module calculates progress. The broadcaster resolves the first encoded agent once, reuses its normalized identity prefix, merges statuses directly, and stops when a running producer cannot be outranked. Exact session keys, explicit/default agent selection, ownerless adoption, and status precedence remain unchanged. This adds no cache.

The remaining fixture repairs make session-group and cron cleanup await the existing scoped database owner before removing state. Fixture producers return canonical paths so cleanup selects the same resources that callers opened. Sibling stores remain available. The Gateway reseed repair and shared state-directory helper from the earlier candidate are now on main through #159197 and #159281, so those four files are absent from this diff.

Evidence

The real sessions.changed broadcaster, with 256 synthetic child sessions and 16 recipients, used 35.7% less main-thread CPU: 102.071 ms to 65.662 ms per 20 broadcasts after warmup, across four interleaved samples. Payloads, recipient frames, and zero-SQL behavior matched. This measures that synthetic flow, not overall production latency; temporary measurement code was removed.

Projection and Gateway presentation proof passed 33 cases; 94 task-progress cases passed before the behavior-preserving extraction. The added projection case took 1 ms locally; hosted Bun rounded it to 0 ms. The focused file took 1.478 s locally. Production types, all 25 test type graphs, repository guards, dead-export scans, and independent P0–P2 review passed for the unchanged production change.

Cron cleanup's regression holds a real mutation-worker lifetime and verifies revocation, settlement before removal, closed case-owned handles, and an unaffected sibling store. Both original and async-close-only alias controls fail by removing state before revocation. The final four-case harness passes under an aliased temp root in 28.354 s wrapper wall; the new case took 1.125 s. The original 14-case reaper file passes in 23.256 s. All three session-group cases pass under an aliased temp root in 31.916 s; earlier hosted case times were 449/448/1,809 ms. Owning types, lint, formatting, and diff checks pass.

The six remaining files are byte-identical to the independently reviewed candidate. Integration onto aad795bf preserves the four already-landed files exactly. Main's dependency/cache generation changed through ede3447b and selected-job packing through 24100ea4, and fresh integrated-head CI 36297441897 passed with 146 successful and 21 skipped checks. ClawSweeper reviewed the exact integrated head with no findings. Neither integration nor this passing run is claimed to fix the unresolved Bun crash below.

Previous CI failures and bounded investigation

Earlier CI encountered an intermittent private-completion timeout and cron cleanup ENOTEMPTY. Queued-write and scoped cleanup defects were independently demonstrated and repaired. Passing replays do not establish the exact cause of either intermittent hosted failure.

Prior-head CI 36287547770 stopped when the checksum-pinned Bun runtime segfaulted after spawning Vitest workers and before reporting a fast-test case. Earlier groups passed 831 Gateway Node, 178 Gateway Bun, 1,230 security, and 82 Node fast cases. The tested merge was 7f4a797a2e55b5cbafc1237537db5e8cc57c2aae. The triggering import or case remains unproven; downstream jobs were cancelled and that CI gate remains failed.

One bounded isolated replay used the exact merge, pinned Bun 1.4.3-canary.1+ddfce5d01 executable, and original 704-file envelope with two workers. The crash did not reproduce: 8,577 Bun cases passed and three were skipped. The complete envelope exited 1 because a Node cleanup case failed. The diagnostic subreaper deferred reaping orphaned children, contaminating the process-group cleanup observation; no captured PID-to-group mapping establishes exact attribution. Preceding job groups and the original protected transform-cache seed were omitted. Matching symbols were unavailable in the checked release assets, exact-head workflow artifacts, and local debug locations; all 17 known crash PCs remain unsymbolized. This replay establishes neither a crash fix nor a passing complete gate.

@clawsweeper

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

@steipete
steipete marked this pull request as ready for review September 26, 2026 21:18
@clawsweeper clawsweeper Bot added 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 26, 2026
@clawsweeper

clawsweeper Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 27, 2026, 2:22 AM ET / 06:22 UTC (Revision 12).

ClawSweeper review

What this changes

The branch reduces work when the Gateway calculates session activity and makes cron and session-group test fixtures drain their scoped database resources before cleanup.

Merge readiness

✅ Ready for maintainer review

Current main still uses the allocation-heavy activity resolver, and the merged related PRs do not contain this optimization. The pinned patch has no supported blocking finding, so this remains a useful landing candidate.

Priority: P2
Reviewed head: b8cd89f77cf574d18afb9d49330d1b54c08e1fd8

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The bounded optimization has direct broadcaster measurements, focused lifecycle coverage, and successful exact-head CI, with no supported blocking defect.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body reports an after-change run through the production sessions.changed broadcaster in a local synthetic 256-child, 16-recipient setup, with lower measured CPU and matching frames and payloads; focused tests and exact-head CI supplement that observation. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body reports an after-change run through the production sessions.changed broadcaster in a local synthetic 256-child, 16-recipient setup, with lower measured CPU and matching frames and payloads; focused tests and exact-head CI supplement that observation. No stored-data contract changes.
Evidence reviewed 8 items Pinned production change: The resolver reuses one normalized agent prefix and merges statuses directly, returning early when running has the highest precedence.
Current-main necessity: Fetched main still builds per-key status arrays and reduces them after resolving agent identity; the branch's hot-path change is absent.
Gateway consumer: The session activity presenter consumes the projected state when constructing active-run facts for a session snapshot.
Findings None None.
Security None None.

How this fits together

The Gateway combines live agent-run contexts with session rows and sends activity snapshots to subscribed clients. The affected tests create SQLite-backed fixtures and release their resources before removing temporary directories.

flowchart LR
  A[Agent run contexts] --> B[Run projection index]
  B --> C[Progress resolver]
  D[Session row] --> E[Session snapshot]
  C --> E
  E --> F[Session change broadcast]
  F --> G[Subscribed clients]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +33, Tests +130. Total +163 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 2 65 32 +33
Tests 4 140 10 +130
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 205 42 +163

Review metrics

Metric Value Why it matters
Production and test growth production net +33; tests net +127; test support net +3 The production growth is concentrated in the resolver and is supported by the reported CPU measurement and focused regression coverage.
Broadcaster CPU sample 102.071 to 65.662 ms per 20 broadcasts The measured 35.7% reduction covers a synthetic 256-child, 16-recipient run through the production broadcaster.

Technical review

Best possible solution:

Keep run liveness in the registry and calculate presentation status in the existing projection owner, with scoped fixture cleanup that preserves unrelated stores.

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

Yes for the performance concern: current main visibly allocates status arrays in the resolver, and the PR body gives a concrete broadcaster benchmark. This read-only review did not rerun it.

Is this the best way to solve the issue?

Yes: the change uses the existing projection owner and preserves the registry call contract without adding a cache, configuration, or protocol field.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded Gateway performance improvement with limited user-visible blast radius.
  • 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 PR body reports an after-change run through the production sessions.changed broadcaster in a local synthetic 256-child, 16-recipient setup, with lower measured CPU and matching frames and payloads; focused tests and exact-head CI supplement that observation. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body reports an after-change run through the production sessions.changed broadcaster in a local synthetic 256-child, 16-recipient setup, with lower measured CPU and matching frames and payloads; focused tests and exact-head CI supplement that observation. No stored-data contract changes.

Evidence

What I checked:

  • Pinned production change: The resolver reuses one normalized agent prefix and merges statuses directly, returning early when running has the highest precedence. (src/infra/agent-run-projection.ts:43, b8cd89f77cf5)
  • Current-main necessity: Fetched main still builds per-key status arrays and reduces them after resolving agent identity; the branch's hot-path change is absent. (src/infra/agent-run-registry.ts:605, 168ebc5b6708)
  • Gateway consumer: The session activity presenter consumes the projected state when constructing active-run facts for a session snapshot. (src/gateway/server-methods/session-active-runs.ts:247, b8cd89f77cf5)
  • Scoped fixture lifecycle: Cron cleanup now awaits the existing database lifecycle owner before removing the case directory; the owner revokes and drains pending resources within the supplied root. (src/cron/service.test-harness.ts:50, b8cd89f77cf5)
  • Real behavior proof: The captured PR body reports a local run through the real sessions.changed broadcaster with 256 synthetic child sessions and 16 recipients: main-thread CPU fell from 102.071 to 65.662 ms per 20 broadcasts, while payloads, recipient frames, and zero-SQL behavior matched. (b8cd89f77cf5)
  • Exact-head CI: The reported integrated-head GitHub Actions run completed successfully for the pinned PR head; this does not establish the cause of the earlier intermittent Bun crash. (b8cd89f77cf5)

Likely related people:

  • steipete: 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 (11 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-26T22:56:35.957Z sha 902226a :: needs maintainer review before merge. :: none
  • reviewed 2026-09-26T23:18:47.868Z sha 902226a :: blocked before merge. :: none
  • reviewed 2026-09-27T00:18:06.416Z sha eadd716 :: blocked before merge. :: none
  • reviewed 2026-09-27T00:41:10.996Z sha fa16f18 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-27T02:12:35.430Z sha f865bd8 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-27T02:41:56.212Z sha f865bd8 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-27T03:46:13.004Z sha f865bd8 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-27T05:38:09.259Z sha b8cd89f :: needs maintainer review before merge. :: none

@steipete
steipete enabled auto-merge (squash) September 26, 2026 21:58
@steipete
steipete disabled auto-merge September 26, 2026 22:08
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M and removed size: S labels Sep 26, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. labels Sep 27, 2026
@steipete
steipete force-pushed the codex/session-broadcast-projection-20260926 branch from f865bd8 to b8cd89f Compare September 27, 2026 05:31
@steipete
steipete merged commit e1e4e69 into main Sep 27, 2026
233 checks passed
@steipete
steipete deleted the codex/session-broadcast-projection-20260926 branch September 27, 2026 06:34
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 28, 2026
)

* perf(gateway): reduce session activity broadcast CPU

* refactor: keep projected run state merger private

* test: simplify projected run context fixture

* test(gateway): await scoped session-group cleanup

* test(cron): settle scoped fixture databases before cleanup

Retire case-owned native resources before removing canonical fixture roots. Preserve sibling stores and accepted queued work. Include the shared state-dir helper repair from upstream d4970fb.
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. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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