Skip to content

perf(presence): compact repeated roster identities - #177471

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-presence-delta-size-and-rate-20260919
Oct 19, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-presence-delta-size-and-rate-20260919

Conversation

@steipete

@steipete steipete commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Presence deltas already send changed fields and coalesce publications for 200 ms, but each delta repeats the complete roster order using long connection/device identities. The same identities also prefix every changed row. Activity updates can affect multiple connections belonging to the same person, multiplying that overhead.

User Impact

Presence keeps its existing timing, ordering, recipient filtering, field-patch semantics, and client protocol while sending smaller deltas. The presence owner now assigns compact opaque row keys, preserves them through updates, and assigns fresh keys after removal or expiry. No new capability, cache, configuration, or protocol version is introduced.

Evidence and Measurement

A real Gateway WebSocket replay uses 42 synthetic operator connections (40 delta readers, two legacy readers), four node beacons, and five phases: viewer switches/leaves, activity, typing, node heartbeat, and mixed bursts. A and B run concurrently under the exclusive measurement lock on separate 16-core halves, with identical workloads and separate synthetic state. The next pair swaps the halves. Each measurement window is about 200 seconds; byte counts include the serialized event envelope, excluding WebSocket/TLS framing. The baseline loads the old presence owner into the same source/dependency environment; the hook asserts that it was used.

The predeclared target was at least 60% fewer total presence bytes. Both concurrent pairs, including the swapped-core pair, produced identical event-byte counts: 49.9% fewer delta bytes and 38.6% fewer total presence bytes (1.63× smaller), with identical frame counts. The total target is not met, principally because legacy snapshots remain unchanged. The current change delivers a meaningful reduction with four additional runtime lines; native-client delta support remains the next opportunity.

Both valid pairs Baseline A Candidate B Paired B − A
Total presence bytes/socket 113,344 69,584 −43,760
Total presence bytes/socket/min, pair 1 33,973 20,857 −13,116
Total presence bytes/socket/min, swapped pair 33,971 20,855 −13,115
Delta bytes/frame 6,572 3,290 −3,282
Legacy bytes/frame 38,567 38,567 0
Presence frames across 42 sockets 588 588 0
Presence frames/min/socket 4.196 4.196 ≈0

CPU over each 200-second window was 4,632 → 4,467 ms (paired −165 ms) and 4,870 → 4,937 ms (paired +67 ms); there is no consistent CPU improvement or regression. Final RSS was 2,571,730,944 → 2,627,780,608 B (paired +56,049,664 B) and 2,553,868,288 → 2,554,572,800 B (paired +704,512 B). These short runs do not establish a steady-state memory change. Host CPU busy averages on the two halves were 6.11%/5.98% in pair 1 and 9.56%/8.76% in the swapped pair, recorded with mpstat for context.

Replay command on each side: node --import ./scripts/tsx.mjs scripts/perf/presence-churn-measure.ts --scenario traffic --clients 42 --rounds 4 --interval-ms 10000 --state-dir <fresh-isolated-state> --port <isolated-loopback-port> --start-at <shared-deadline-ms> --output <report.json>. A additionally uses --presence-owner src/infra/system-presence.baseline.ts, containing the owner from 8b78b230a1c109fe6456964e59cb0eeefe63b7e5; B uses this PR's owner. Pair 1 assigns A/B to CPUs 96–111/112–127, then swaps them, with the shared exclusive lock held around each pair.

The focused 24-row, single-field size regression is red on the old owner: 2,334 B → 295 B (full snapshot: 19,624 B).

Cause breakdown

Both pairs have identical changed fields on both sides and identical per-phase byte counts. Per-delta means by replay phase:

Cause Frames across 40 delta readers Baseline bytes/frame Candidate bytes/frame
Viewer switch/leave 160 7,416.5 3,900.5
Activity 40 7,490 3,974
Typing phase 40 7,449 3,933
Node heartbeat 160 4,346.25 1,668.25
Mixed burst 160 7,506 3,971

The roster-order component falls from 1,118,320 B to 112,560 B; upserts fall from 2,455,720 B to 1,623,560 B. The changed values are timestamps/activity, watched sessions, and node text/input age. Profiles, avatars, and static device fields are already omitted from updates. Typing has its own event; presence emitted during that phase reflects activity publication, not retransmitted typing data. Shared-person activity fans out to connections, explaining why this synthetic cohort's baseline deltas are larger than the observed production average.

Legacy clients and resets

Handshake metadata in the reported 15-minute window contains exactly 39 Control UI connections, matching the 39 reported resets. This supports first-post-hello initialization as the cause, rather than periodic reset churn. The replay excludes setup and final verification from measured traffic and requires zero recovery; it does not claim to eliminate initial resets.

Native macOS 2026.10.3 is present in the legacy cohort. ChatSessionSidebarPeople.receivePresence decodes a full presence array and has no delta reducer, so advertising presence-deltas alone would break it. Generic backend/CLI clients also lack that capability. The legacy wire format is unchanged. A slower legacy cap would add latency without demonstrated benefit at the observed cadence; reducing that traffic requires a native-client delta implementation. Node host statistics use a separate event and are outside this presence replay.

Change Size and Tradeoffs

Runtime production code is +5/−1 lines (net +4). The counter and existing-row key lookup preserve the public opaque-key stability contract while preventing identity reuse after removal; there is no parallel owner or identity cache. The larger diff extends the existing benchmark driver, adds regression coverage to existing test files, and documents the existing opaque-key contract. The requested production stat excluding tests/docs is scripts/perf/presence-churn-measure.ts: +387/−92; src/infra/system-presence.ts: +5/−1 (the benchmark is not runtime code).

Proof and Limitations

  • Focused tests passed: src/infra/system-presence.test.ts, src/gateway/presence-delivery.test.ts, and src/gateway/server.auth.presence-deltas.test.ts. The transport file covers reconnect and backpressure recovery. CI also passed the related client-presence, activity, publication-window, session-viewer-presence, and presence-audience tests (job 118180226319, job 118180226406).
  • Changed-file format/lint, git diff --check, and one targeted pnpm tsgo:core (tsrs) passed. Broad proof is PR CI; no Testbox lease was allocated.
  • Two independent Codex autoreviews found no actionable P0–P2 findings: the production/test change and the subsequent replay setup correction.
  • An initial paired attempt is excluded: the driver bound its observer after awaiting hello, allowing a synchronous hello/reset receive batch to drop the reset. Binding before connect fixes the harness. A 42-client smoke and all four accepted A/B runs pass exact roster comparison for all 42 sockets (40 using the actual UI reducer) with zero recovery requests and a verified final session departure. The strict assertion remains enabled.
  • The source was rebased before pushing; affected presence owners, consumers, and replay inputs are unchanged between the measured base and the final rebase. The sandbox reuses existing dependency directories; unrelated package-version differences are not CI proof. Synthetic shared-owner identities have no external profile/avatar provider. This proves the actual UI reducer over real WebSockets, not a rendered browser UI.

Exact-head CI run 39287586311 has one substantive failure: checks-fast-baseline-ratchets, plus its downstream aggregate gate. Its error is src/infra/openclaw-process-census.missing-command.test.ts:12: ./container-environment.js under First-party mock factories must preserve real exports or explain isolation; mock-exports failed (exit 1). The identical signature fails on unchanged main in run 39282913747. The automatic table labels this "new" against older scheduled-main run 39278710829; the newer main-push run above reproduces the exact signature. Both source files are identical between that failing main baseline and this PR. All other scheduled checks, including dependency/security review, passed or were skipped by CI. No unrelated source was changed and no CI rerun was requested. This qualifies for the explicitly authorized inherited-failure landing exception; CI is not being reported green.

@clawsweeper

clawsweeper Bot commented Oct 19, 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 scripts Repository scripts size: L labels Oct 19, 2026
@steipete
steipete marked this pull request as ready for review October 19, 2026 16:20
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 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-19T16:24:11.674188Z 791fb93 Draft marked ready
ℹ️ 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:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 19, 2026
@clawsweeper

clawsweeper Bot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR assigns compact, stable presence row IDs and extends the existing Gateway traffic benchmark.

Example: A 24-row roster sends a delta for one changed field with long connection identities.

  • Before: The PR reports a 2,334-byte delta.
  • After: The PR reports a 295-byte delta while preserving the roster.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The implementation is focused and appears correct, but the performance evidence currently covers only serialization.
Proof confidence 🦪 silver shellfish (2/6) This maintainer-authored PR is outside the ordinary contributor-proof gate; its supplied evidence establishes only focused serialization size, while the declared real Gateway traffic comparison and reducer correctness results remain pending.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Presence updates repeatedly transmit long roster identities, increasing traffic for connected Control UI clients.
Reason: The direction is maintainer-owned, the runtime change is small, and it preserves the existing opaque-key and legacy-client contracts.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR makes a focused, useful optimization absent from current main; no concrete introduced defect was found.

Priority: P2
Reviewed head: 791fb939fd07dfaed18faa5173f5ba3c902ffb2d

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The recorded baseline/candidate Gateway traffic replay remains pending, and executed red-on-base/green-on-head evidence for the changed regressions is not supplied.
Agent review details

How this fits together

The presence owner receives connection and activity updates, maintains ephemeral rows, and supplies opaque identities to recipient-projected Gateway deltas consumed by the Control UI.

flowchart LR
  A[Connection and activity updates] --> B[Presence owner]
  B --> C[Recipient projection]
  C --> D[Presence delivery]
  D --> E[WebSocket clients]
  E --> F[Control UI presence reducer]
Loading

Technical review

Best possible solution:

Retain compact IDs in the existing presence owner and evaluate the recorded traffic acceptance rule before landing.

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

Current main embeds full internal identities in keys repeated by every delta's order array; the PR supplies a focused size comparison, but this review executed no target code.

Is this the best way to solve the issue?

The smallest complete change is to allocate short IDs in setPresence, preserve them while rows exist, and allocate fresh IDs after deletion; the patch follows that boundary without adding a competing owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Presence wire identities keeps the original intent (fa335db: Supply stable opaque row identities for recipient-specific deltas without adding fields to legacy rows.)
  • Field patches and protocol examples keeps the original intent (35dba3e: Keep heartbeat and activity updates compact by sending changed fields rather than whole rows.)
  • Real Gateway churn measurement keeps the original intent (4a74bc6: Measure redundant viewer publications through real WebSockets while preserving positive controls.)

Testing

Proof path: unit tests only.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit fa335db adds src/infra/system-presence.ts:30 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: fa335db99b7b; files: src/infra/system-presence.ts)
  • lzhan011: Raw commit 4bbdedb adds src/infra/system-presence.ts:50 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 4bbdedbb9b94; files: src/infra/system-presence.ts)

PR surface

Source +4, Tests +10, Docs +2, Other +289. Total +305 across 5 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 5 1 +4
Tests 2 16 6 +10
Docs 1 5 3 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 1 381 92 +289
Total 5 407 102 +305

Review metrics

Metric Value Why it matters
Benchmark controls 2 benchmark-only options --scenario and --presence-owner select the traffic workload and baseline implementation; neither changes Gateway configuration or user defaults.

Labels

Label changes:

  • add P2: This reduces recurring presence payload overhead without evidence of an urgent availability or delivery failure.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish 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 reduces recurring presence payload overhead without evidence of an urgent availability or delivery failure.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish 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.

  • Attach the already-declared Gateway replay results showing traffic savings, unchanged publication frequency, reducer correctness, and CPU/RSS context.

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 19, 2026, 12:36 PM ET / 16:36 UTC.

Keep opaque wire identities short and stable across live row updates, assigning new IDs after removal. Retain existing field patches, ordering, coalescing, and legacy snapshots. Extend the real WebSocket replay with traffic breakdown and UI reducer correctness checks.
@steipete
steipete force-pushed the steipete/perf-micro-presence-delta-size-and-rate-20260919 branch from 791fb93 to 6dd8e17 Compare October 19, 2026 16:41
@steipete
steipete merged commit 5995b47 into main Oct 19, 2026
119 of 122 checks passed
@steipete
steipete deleted the steipete/perf-micro-presence-delta-size-and-rate-20260919 branch October 19, 2026 17:02
@steipete

Copy link
Copy Markdown
Contributor Author

The completed real-Gateway evidence is now in the PR body: two concurrent A/B pairs with swapped core halves produced identical byte counts, 49.9% fewer delta bytes and 38.6% fewer total presence bytes. All 42 rosters matched in every accepted run, with zero recovery requests and unchanged frame counts. This closes the pending replay-proof gap noted in the advisory review. The 60% total target was missed; legacy snapshots remain unchanged.

Landed as 5995b47698462a30af120eff3f51ac29b091a678, from reviewed head 6dd8e1701f5dc4c288d99260120e01302bf02cb4 under the authorized pre-existing-failure exception. PR CI 39287586311 failed only checks-fast-baseline-ratchets and its aggregate gate: src/infra/openclaw-process-census.missing-command.test.ts:12: ./container-environment.js, mock-exports failed (exit 1). The exact signature also fails on unchanged main in run 39282913747. The failing test and direct subject are identical on both heads. The automatic table used an older passing scheduled-main run; the newer main-push failure supplies the attribution. All other scheduled checks and dependency/security review passed or were skipped. CI was not rerun or described as green.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 20, 2026
* perf(presence): compact repeated roster identities

Keep opaque wire identities short and stable across live row updates, assigning new IDs after removal. Retain existing field patches, ordering, coalescing, and legacy snapshots. Extend the real WebSocket replay with traffic breakdown and UI reducer correctness checks.

* test(perf): bind presence observers before handshake delivery
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 P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts 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