Skip to content

perf(gateway): reuse session row publication encoding - #166591

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-allocation-hot-sites-20260919
Oct 7, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-allocation-hot-sites-20260919

Conversation

@steipete

@steipete steipete commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Session list and event publications deep-clone every new recipient row and then independently encode it for delivery, allocating a second large row graph including fields JSON omits.

User Impact

Lower allocation and CPU cost when session rows change. Wire output, recipient authorization, snapshot isolation, and revision invalidation remain unchanged. No config or schema changes.

Why This Change Was Made

Create the immutable publication from its canonical JSON bytes and retain those same bytes for delivery. This removes the structured-clone pass from cached row publication. Uncached internal snapshots retain their own-undefined field semantics; model-redacted copies retain separate encodings.

Production LOC: +4/-1 (net +3). The extra lines preserve the existing immutable-publication contract: nested inputs belong to mutable producers, so freezing the source row would be unsafe. This replaces one copy/encode sequence without adding a cache, helper, or parallel path.

Evidence

A 60.18-second live-only Gateway heap sample (32 KiB interval, both collected-object flags false) contained 7.6 MiB of surviving sampled allocations. Top named core sites included worker reply deserialization (1.8 MiB), session-row structured cloning (0.8 MiB), and row JSON encoding (0.8 MiB). This ranks survivors at capture end, not gross allocation rate.

An isolated Ubuntu rig on Node 26.8.1 measured the before/after publication copy plus encoding using actual materialized synthetic rows (135 own fields). Each variant ran three 10,000-operation samples after warmup. Allocation sampling included minor- and major-collected objects at a 4 KiB interval; timing was measured separately without profiling. Median results:

Row Sampled bytes/op before → after Reduction Time/op before → after
Ordinary, 1,424 wire bytes 38,116 → 17,825 53.2% 47.7 → 17.3 µs
Long preview, 18,344 wire bytes 103,199 → 83,637 19.0% 129.3 → 65.2 µs
Nested participants/children, 2,385 wire bytes 57,328 → 34,945 39.0% 82.7 → 53.1 µs

Every sample checked identical encoded bytes and snapshot JSON. This is boundary microbenchmark evidence, not a claim of whole-RPC or production RSS improvement.

Validation completed with the reviewed production bytes unchanged throughout:

  • Independent Codex review: scoped-clean through P2 for the production change and all three assertion adaptations.
  • Provider blacksmith-testbox, lease tbx_01m4b42yb2hg931csdwykz1myb: owner/sibling proof covered 63 cases across 11 files. The initial 52/53 run exposed one own-undefined assertion; its corrected file passed 26/26, and three additional event/model-policy files passed 10/10. pnpm test src/gateway/server-methods/sessions-read-cache.test.ts --maxWorkers=1 took 83.81s runner wall time (80.76s Vitest).
  • The native changed-file gate ran for 31m11.7s: repository guards, formatting, core types, and 26/27 test type graphs passed. The sole failure was an unrelated terminal-font fixture passing a removed signal argument. Main already fixed that exact line in 1d10375ee563bfaa203e9aad7fe88275adedd3a6; this branch rebased onto main without copying that fix into its own commits.
  • Fresh blacksmith-testbox lease tbx_01m4b6qqwp6w0n3dw8bdg4fq7t: current core types plus UI-components/Gateway-methods/Gateway-root test type graphs passed. Every remaining command from the changed-check plan passed, including export checks, targeted lint (0 warnings/errors), schema/storage/import/webhook/pairing guards. Final list/event smoke: 27/27 passed, 89.72s runner wall time. The combined completion command exited 0 in 8m37.4s.
  • Provider aws, lease cbx_36dd7d25f599, run run_ec1b88c9092d150e6a94cf517acf9707: the two final assertion corrections plus six publication/list siblings passed 60/60 cases across eight files in 166.79s. The test-only check-changed gate passed, including the owning Gateway type graph and lint. The combined command exited 0 in 7m18.2s. A transient coordinator error while saving the receipt was reconciled through crabbox receipt; the recovered signed receipt confirms exit 0. All leases are released or expired.

The first CI run had 34 successful jobs and two failing test shards (plus the aggregate gate). Both failures were caused by this change: cached-row own-undefined expectations in the foreground and recovery tests. The follow-up commit checks the same values and preserves array membership, current sharing/metadata, preview recovery, and all uncached snapshot assertions. These are not inherited failures. The correction adds no cases, fixture boots, or waits. The first CI measured 12.02s for the foreground file's two-file Node group and 14.17s for the recovery file. Corrected-head CI passed on 80d64546ed2576d0cc88e8ee5569da5da3f362c0: 37 successful jobs and 637 seconds from first job start to final job completion. The PR merged as ebc4e6de603c5c1ce55086f13565e21feb1c297d.

Remote command scope

The native full gate used node scripts/check-changed.mjs -- src/gateway/session-row-presentation.ts src/gateway/server-methods/sessions-read-cache.test.ts. After rebasing, retained passing checks were reused; current core types, core-test-ui-components, core-test-gateway-methods, core-test-gateway-root, and all remaining native-plan commands completed separately.

Final correction proof:

node scripts/run-vitest.mjs src/gateway/session-row-projection.foreground.test.ts src/gateway/session-row-projection.recovery.test.ts src/gateway/session-row-projection.backfill.test.ts src/gateway/session-list-serialization.test.ts src/gateway/session-row-event-parity.test.ts src/gateway/session-row-event-trees.test.ts src/gateway/server.sessions.list-changed.test.ts src/gateway/server.sessions.placement-projection.test.ts
node scripts/check-changed.mjs -- src/gateway/session-row-projection.foreground.test.ts src/gateway/session-row-projection.recovery.test.ts

No new module, export, or test file was added. No post-deployment throughput, GC, or RSS improvement is claimed.

Build immutable cached session rows from their canonical JSON and retain
those bytes for list and event delivery. This removes the structured-clone
pass while keeping mutable producer state isolated and redacted views
separately encoded.

Synthetic materialized-row measurements reduce sampled allocation per
publication by 19-53%. Preserve uncached own-undefined semantics and check
absent derived titles by value in the existing preview regression.
@clawsweeper

clawsweeper Bot commented Oct 7, 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 size: XS labels Oct 7, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 Oct 7, 2026
@clawsweeper

clawsweeper Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed October 7, 2026, 9:49 AM ET / 13:49 UTC (Revision 3).

ClawSweeper review

What this changes

The Gateway creates immutable cached session rows from their JSON encoding, reuses those bytes for delivery, and adjusts a preview assertion for omitted undefined fields.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⛔ Needs changes before merge - 2 items remain

The optimization remains useful and is absent from current main. The pinned head still breaks two existing test files; the author acknowledges those failures and is preparing corrections.

Priority: P2
Reviewed head: c1c5c23770eeb4cc099a3441d65ae371b253d612

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The production optimization is focused and supported, but the pinned patch still leaves two incompatible test files.
Proof confidence 🌊 off-meta tidepool Not applicable: Repository State identifies a MEMBER-authored internal optimization, so ordinary external-contributor proof is exempt. The body supplies scoped publication measurements and boundary validation; no material authority or stored-data contract changes require an additional proof gate.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Repository State identifies a MEMBER-authored internal optimization, so ordinary external-contributor proof is exempt. The body supplies scoped publication measurements and boundary validation; no material authority or stored-data contract changes require an additional proof gate.
Evidence reviewed 10 items Pinned introduced change: The introduced production change replaces structured cloning with JSON encoding, parsing, freezing, and registration of the same encoded bytes. The uncached path and separately projected model views remain intact.
Current main still needs the optimization: Comparison with fetched main shows that main still uses structuredClone for this publication. No same-repository merged fixing PR was established, so implementation closure is unsupported.
Foreground assertion remains incompatible: The foreground list test requires lastMessagePreview to exist as an own property with value undefined. The introduced JSON round trip omits that property, while the test's membership-revocation and current-summary assertions remain meaningful.
Findings 1 actionable finding [P2] Update the remaining cached-row undefined assertions
Security None None.

How this fits together

The Gateway presents session metadata for session lists and events. It applies current recipient visibility and model restrictions before delivering immutable rows to connected clients.

flowchart TD
  A[Session metadata] --> B[Resident session projection]
  B --> C[Recipient presentation]
  D[Current visibility and model policy] --> C
  C --> E[Immutable JSON publication]
  E --> F[Session list responses]
  E --> G[Session events]
Loading

Before merge

  • Update the remaining cached-row undefined assertions (P2) - The JSON round trip removes own properties whose values are undefined. The pinned head still requires those properties in session-row-projection.foreground.test.ts:408 and the initial/healed list assertions in session-row-projection.recovery.test.ts:128-161, causing the two CI failures acknowledged in the updated PR body. Apply the same value-based treatment used in the changed read-cache test, preserving key, preview, membership, summary, and persistence checks. Keep uncached snapshot assertions intact. The reported staged corrections are not yet present in this head.
  • Complete next step (P2) - Push the prepared foreground and recovery assertion corrections, then validate those tests and the affected publication/list siblings on the updated head.

Findings

  • [P2] Update the remaining cached-row undefined assertions — src/gateway/session-row-presentation.ts:426-427
Agent review details

Security

None.

PR surface

Source +3, Tests -1. Total +2 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 4 1 +3
Tests 1 3 4 -1
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 7 5 +2

Review metrics

None.

Technical review

Best possible solution:

Retain the shared JSON publication and make cached-row tests verify absent values without requiring properties that the wire format omits.

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

Yes, from source: cached publication drops undefined properties while the foreground and recovery tests require them to exist. The captured CI report confirms those failures; this read-only review did not execute tests.

Is this the best way to solve the issue?

Yes. Reusing the publication's canonical bytes is a narrow optimization; correcting cached-row assertions preserves the meaningful recovery and authorization coverage.

Full review comments:

  • [P2] Update the remaining cached-row undefined assertions — src/gateway/session-row-presentation.ts:426-427
    The JSON round trip removes own properties whose values are undefined. The pinned head still requires those properties in session-row-projection.foreground.test.ts:408 and the initial/healed list assertions in session-row-projection.recovery.test.ts:128-161, causing the two CI failures acknowledged in the updated PR body. Apply the same value-based treatment used in the changed read-cache test, preserving key, preview, membership, summary, and persistence checks. Keep uncached snapshot assertions intact. The reported staged corrections are not yet present in this head.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: Repository State identifies a MEMBER-authored internal optimization, so ordinary external-contributor proof is exempt. The body supplies scoped publication measurements and boundary validation; no material authority or stored-data contract changes require an additional proof gate.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: ⏳ waiting on author.

Label justifications:

  • P2: This is a bounded Gateway allocation improvement with test maintenance remaining and no established urgent user-facing regression.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: Repository State identifies a MEMBER-authored internal optimization, so ordinary external-contributor proof is exempt. The body supplies scoped publication measurements and boundary validation; no material authority or stored-data contract changes require an additional proof gate.

Evidence

What I checked:

Likely related people:

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

Rank-up moves

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

  • Push the prepared assertion corrections and verify the foreground, recovery, and publication/list sibling tests on the resulting head.

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 (2 earlier review cycles)
  • reviewed 2026-10-07T13:02:35.123Z sha c1c5c23 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-07T13:19:27.558Z sha c1c5c23 :: needs maintainer review before merge. :: none

@steipete
steipete marked this pull request as ready for review October 7, 2026 13:13
@steipete
steipete enabled auto-merge (squash) October 7, 2026 13:14
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed 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 Oct 7, 2026
@steipete
steipete merged commit ebc4e6d into main Oct 7, 2026
119 checks passed
@steipete
steipete deleted the steipete/perf-micro-allocation-hot-sites-20260919 branch October 7, 2026 14:04
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 8, 2026
* perf(gateway): reuse session row publication encoding

Build immutable cached session rows from their canonical JSON and retain
those bytes for list and event delivery. This removes the structured-clone
pass while keeping mutable producer state isolated and redacted views
separately encoded.

Synthetic materialized-row measurements reduce sampled allocation per
publication by 19-53%. Preserve uncached own-undefined semantics and check
absent derived titles by value in the existing preview regression.

* test(gateway): check optional cached row values
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: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant