Skip to content

perf(gateway): avoid expanding audience scopes on cache hits - #184829

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-broadcast-frame-field-audience-key-20261026
Oct 26, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-broadcast-frame-field-audience-key-20261026

Conversation

@steipete

@steipete steipete commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Session-event audience-key cache hits still copy connection scopes into a newly grown facts array for every recipient, after the key itself has already been cached.

User Impact

Lower allocation during session-event fanout, with unchanged key bytes, visibility decisions, live authority inputs, and invalidation. No configuration or migration is required.

Why This Change Was Made

Compare the existing retained snapshot against fixed facts and live scope values directly; append scopes to a new snapshot only on a miss. This preserves the existing revision/viewer cache owner and every scope value, including the distinction between absent and empty scopes. It introduces no additional cache or lifetime.

Production delta: +6 lines (11 additions, 5 removals). The small growth separates live scope comparison from miss-only snapshot construction while preserving the existing authority contract. The author simplification pass retained only this change and one regression; broadcaster serialization already shares projection payloads and is untouched.

Evidence

The earlier sharing-key reuse change (#184201, 24fa04ed3f78) is an ancestor of evidence build e8764a3f; this removes residual work rather than repeating that fix. Baseline for the measurements is c00af62f03e6ab9929234a998693f53341a4e126.

Acceptance: unchanged key/authorization digest, lower owner allocation, no controlled material CPU regression. Existing committed workload: scripts/perf/session-sharing-key-measure.ts, with 65 interleaved clients, eight identities, 40 plugin entries, 10,000 synthetic session targets, and sharing-revision changes every 100 events. Each arm runs 3,000 events / 195,000 lookups, after 200 warmup events. Node v26.12.1, macOS; timing and sampled allocation are separate passes.

Metric, mean per arm Base Candidate Delta
Sampled allocation, five alternating pairs 572.59 MB 519.69 MB −9.24%
Main-thread CPU, six alternating pairs 145.005 ms 148.895 ms +2.68%, inconclusive
Main-thread CPU, median 145.312 ms 138.319 ms −4.81%, context
Scope expansions per warm lookup 1 0 removed

All output digests match. Allocation improves in every pair (−8.08% to −10.24%). Timing pairs are −2.57%, −4.45%, +36.41%, −8.44%, −7.83%, +1.58%; the sixth pair was the predeclared extra pair after mixed signs. No sample was excluded. The signed absolute CPU mean is +3.890 ms per 195,000 lookups, below the 20% adverse threshold; this is an allocation win, not a CPU speedup claim. Host one-minute load ranged 11.47–22.40 on baseline timing arms and 11.54–23.21 on candidate timing arms; allocation arms ranged 20.70–25.33 and 21.71–23.92 respectively.

Reproduce with node --expose-gc --import ./scripts/tsx.mjs scripts/perf/session-sharing-key-measure.ts; use --allocations for the separate allocation pass and --owner src/gateway/.session-sharing-read-base.ts for the saved baseline module. The script header documents this workflow; no shared perf README changes.

  • New interleaved audience-key regression fails on main: three scope expansions during three cache hits; passes on candidate. It also checks same-array scope replacement, independent viewers, and absent versus empty scopes.
  • session-sharing.prepared.test.ts: 3/3 passed, 0.52 s test time, 38.89 s wrapper wall time (compiler setup dominates). CI confirms the same three tests passed in 0.625 s (18 ms regression, 529 ms profile lifecycle, 78 ms prepared authorization). Existing merge-alias, role-policy, identity-detachment, and no-SQL checks remain green.
  • session-sharing.events.test.ts, session-row-presentation.test.ts, server-broadcast.serialization.test.ts: 25/25 passed; 74.78 s wrapper wall time. Includes live revocation, recipient isolation, exact wire/sequence behavior, and real WebSocket compression coverage.
  • Changed-file oxfmt, changed-file oxlint, and git diff --check passed.
  • Independent subagent review (autoreview route unavailable): no actionable P0–P2 findings. The configured review route mismatch was not bypassed or reconfigured.

Scope/gaps: this follows the authorized duplicate-work fast path. No whole-Gateway load/stress campaign, GC/loop/list latency claim, or Team mutation. CI run 40366493863 passed on exact head 89beb13d7ddcfedb7e3ab9460b12ea5f38b39312 (35m28s including runner queues; no reruns). Build artifacts, selected Node/UI tests, type checks, lint, boundary checks, and baseline ratchets passed. The GitHub Codex review also completed on that head with no findings. This PR is ready for the coordinating maintainer to review and merge; this lane does not self-merge.

@clawsweeper

clawsweeper Bot commented Oct 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 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-26T17:14:31.347859Z 89beb13 PR opened
ℹ️ 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.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: XS labels Oct 26, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro 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. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 26, 2026
@clawsweeper

clawsweeper Bot commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR copies connection scopes into retained audience-key facts only on cache misses.

Example: Alice retains scopes ["operator.read"] across three session events under the same sharing revision.

  • Before: Each warm lookup expands the scopes into a new facts array.
  • After: Warm lookups compare live scope values directly and return the same audience key.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, source-supported optimization with credible owner-level measurements; performance evidence remains limited to an in-process workload.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its reported macOS benchmark exercises the production sharing-key owner and supports the bounded allocation claim, without claiming Gateway load coverage.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Streaming session-event fanout performs avoidable allocation for recipients whose audience keys are already cached.
Reason: The existing feature owner proposes a narrow optimization with measured allocation savings and unchanged identity, authorization, and invalidation contracts.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR removes measurable allocation work with a focused change, and no actionable correctness or security defect was found.

Priority: P2
Reviewed head: 89beb13d7ddcfedb7e3ab9460b12ea5f38b39312

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied measurements exercise the sharing-key owner directly; no shipped Gateway fanout allocation measurement is supplied.
Agent review details

How this fits together

The Gateway sharing preparer turns current recipient identity, policy, scopes, and publication revision into an audience key used to share session-event presentation work.

flowchart LR
  A[Session event] --> B[Current recipient sharing facts]
  B --> C[Revision and viewer key cache]
  C --> D[Audience presentation]
  D --> E[WebSocket broadcast]
Loading

Technical review

Best possible solution:

Retain this focused optimization within the existing revision-and-viewer cache owner.

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

The pinned base expands connection scopes before checking for a retained-key hit, establishing the unnecessary work directly in source; no target code was executed during this review.

Is this the best way to solve the issue?

The patch is the smallest complete fix: compare live scopes against the existing snapshot and construct the expanded snapshot only when replacing it.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Revision-bound sharing-key reuse keeps the original intent (24fa04e: Retain serialized audience keys while preparing current sharing policy and comparing current viewer facts on every call.)
  • Canonical scope serialization keeps the original intent (4d94a9f: Share equivalent identity/query views while preserving current permissions and independent publication lifetimes.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Pinned change preserves cache identity: The introduced diff retains every fixed fact, compares scope length and individual live values, preserves absent versus empty scopes, and snapshots scopes only after a miss. (src/gateway/session-sharing-read.ts:404, 89beb13d7ddc)
  • Reported performance evidence has a bounded scope: The PR reports 9.24% lower sampled allocation and matching output digests; CPU results are explicitly inconclusive. The committed benchmark invokes the production sharing preparer directly and expressly excludes Gateway load measurement. (scripts/perf/session-sharing-key-measure.ts:1, 89beb13d7ddc)
  • Existing ownership and intent are preserved: The merged predecessor perf(gateway): reuse sharing keys across session deltas #184201 introduced revision-bound, weakly held serialized keys while deliberately retaining current sharing preparation; this PR removes residual scope-copying work within that same owner. (src/gateway/session-sharing-read.ts:335, 24fa04ed3f78)
  • Live recipient preparation remains outside retained key reuse: Session-event projection prepares each recipient before audience lookup and clears audience payloads when access or projection revisions change; the PR changes neither this ordering nor delivery authorization. (src/gateway/session-event-projection.ts:142, 89beb13d7ddc)
  • Regression covers the removed work and scope invalidation: The added test interleaves viewers, detects scope iteration on warm hits, changes a scope in place, and distinguishes empty from absent scopes; the PR reports failure on base and success on candidate. (src/gateway/session-sharing.prepared.test.ts:19, 89beb13d7ddc)
  • Current merge and check state: GitHub reports the reviewed head mergeable, with the aggregate CI gate pending; dependency and security-sensitive classification statuses pass. Queued checks establish no diff-caused failure. (89beb13d7ddc)

Likely related people:

  • Peter Steinberger: Raw commit 24fa04e adds src/gateway/session-sharing-read.ts:335 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 24fa04ed3f78; files: src/gateway/session-sharing-read.ts)
  • Vincent Koc: Raw commit da27b33 adds src/gateway/session-sharing-read.ts:164 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: da27b336c0e9; files: src/gateway/session-sharing-read.ts)

PR surface

Source +6, Tests +27. Total +33 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 11 5 +6
Tests 1 27 0 +27
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 38 5 +33

Review metrics

Metric Value Why it matters
Production versus test LOC Production +11/-5; tests +27/-0 The small production increase separates live comparison from miss-only snapshots; one focused regression protects allocation work and scope invalidation.

Labels

Label changes:

  • add P2: A measured allocation improvement in session-event fanout has useful but limited user impact.
  • 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: A measured allocation improvement in session-event fanout has useful but limited user impact.
  • 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.

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, 1:27 PM ET / 17:27 UTC.

@steipete
steipete merged commit a1fb899 into main Oct 26, 2026
143 of 144 checks passed
@steipete
steipete deleted the steipete/perf-broadcast-frame-field-audience-key-20261026 branch October 26, 2026 17:52
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 27, 2026
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. size: XS 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