Skip to content

perf(sessions): reuse topology paths during row selection - #177285

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-session-row-scope-publication-index-20260919
Oct 19, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-session-row-scope-publication-index-20260919

Conversation

@steipete

@steipete steipete commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Session publication and selection repeatedly allocate physical-path arrays and temporary matcher state even though the physical topology is unchanged. A previous 5,000-session stream-start profile attributed substantial allocation to these selectors.

User Impact

Scope, row ordering, federation, alias handling, and publication visibility remain unchanged. Four profiled pairs show 64.5% less allocation in the three named functions and 7.7% less total allocation. Two additional unprofiled pairs show effectively neutral GC and improved list p95. The original 70% allocation target was missed. The owner explicitly accepted the 64.5% reduction, 7.7% lower total allocation, neutral unprofiled GC, and 11.8% lower unprofiled list p95: the measured benefit is sufficient and no regression was shown. Performance is accepted for landing.

Why This Change Was Made

Keep physical-path results with the existing topology owner, including distinct agent-specific and all-agent results. A replacement topology replaces those lists. Unknown path spellings still resolve against current admitted physical identity.

The selector also passes prepared paths directly instead of allocating matcher closures, resolves a store query once, passes the dirty set without copying selection state, allocates child-key and agent-list state only for a parent query, and sizes matching-result arrays from the indexed candidate count before compaction. Existing row indexes remain authoritative; there is no new selection cache or active-run rewrite.

Production delta: +35 lines in one module. The growth prepares immutable agent-specific, all-agent, and fallback path lists once while retaining the existing unknown-alias admission contract; no rows, revisions, or invalidation owners are added.

Evidence

  • Randomized scan-reference equivalence covers keys, session IDs, logical/physical owners, aliases, membership, and ordering (800 query samples).
  • The physical-path sharing regression fails against the original implementation and passes with this change. The same fixture checks alias publication, distinct-store isolation, and replacement on topology publication.
  • All 17 focused tests pass in session-row-selection.test.ts and session-row-projection.publication.test.ts (47.80 seconds including worker compilation on the revised candidate).
  • Changed-file oxfmt/lint and diff whitespace checks pass. Native core typecheck passed on the initial candidate; current-head CI covers the revised candidate under the one-local-typecheck budget.
  • Independent full-diff autoreview of the revised candidate is clean through P2. Current-head CI completed with 43 successful jobs and one underlying X-publication HTTP 503 failure. A local comparison now reproduces the identical failure on the merge base while the reviewed head passes; see the attribution and authorized landing section below.
  • One local focused run stopped before tests because a lint-only comment changed during worker compilation. With the source frozen, the same two files passed all 17 tests.

Measurement acceptance, recorded before runs

Real isolated Gateway, 5,000 retained sessions, 6,000 retained runs, 80 simultaneous synthetic model streams, four clients, each with broad and exact-session subscriptions, three measured bursts after warmup. Four concurrent A/B pairs use matching seeds, separate synthetic states/ports, and alternating 16-core halves under one exclusive measurement lock. Outside load is recorded for context.

The original recorded target is at least 70% less combined allocation attributed to physicalPaths, selectMatchingSessionRows, and selectSessionRowEntries, with no increase in total GC per burst. Report full-module allocation too, so moving allocation between helper frames cannot satisfy the criterion. Report total MB per observed publication and list p95/p99; compare paired B-minus-A differences. Sampling includes concurrent work and is not exclusive publication cost.

One-publication diagnosis

With 5,002 resident rows, a stored session-entry publication makes two indexed matching calls: one visits a single row, the other visits none. It calls physicalPaths once and does not call selectSessionRowEntries. A runtime publication visits one row through one keyed match. Current main does not scan all retained rows on these publication paths.

A separate nominal 500 ms asynchronous presentation window contains 10 entry selections, each visiting one row, 32 matching calls visiting 21 rows total, zero dirty-row visits, and 75 physical-path calls. These are window counts, not a per-publication claim. Startup and initial subscription selection are recorded separately. The real-Gateway diagnostic used one synthetic stream and no concurrent list polls; instrumented timing is not acceptance evidence.

Decision rule

The standing task instruction treats numeric targets as goals: a meaningful measured win may land below the numeric target if there is no material regression. A result below 70% will be reported as missing the original target, not as meeting it.

Exploratory candidate and revised campaign

The first candidate completed two swapped-core pairs (three bursts per side). Named-owner allocation fell 53.5% and whole-module allocation fell 50.2%, but total allocation rose 3.1% and full-burst GC rose 5.3%. It was not accepted. The remaining runs were stopped before admission; no successful sample was dropped.

The revised candidate additionally sizes selection arrays directly and defers the parent-only agent list. Four fresh paired measurements completed; all 24 successful cohorts are retained. Initial launcher setup failed before readiness and produced no samples; both runtime layouts were then verified identical.

Frozen benchmark baseline is 4a74bc62b4c1ea81a182ae87e20ee1b4c48c0459; each candidate is that baseline plus only the scoped production change. The revised artifact uses module hash e2f2304b3519a954c6a3bed58b2970ca18b559380a51a0a7a091dc88f3b0bbe9; final source 17f0e336efdbaf9e6920e63602e8bb28c6dc757c2d78c23423b4657204ca851b adds only the explanatory lint comment. The PR is rebased onto 7e47eab3124ab525d6043d1c9343cad2109dfce4. Main's intervening dependency and workload changes are deliberately absent from both benchmark artifacts; these are frozen-patch measurements, not measurements of the full rebased tree.

Four-pair profiled result

All values below are means across simultaneous pairs; each side has three bursts per pair. Every burst reached 80 streams and recorded 640 session.message + sessions.changed events at the first observer during the allocation window (not summed deliveries across all four clients), plus 1,049 full-cohort source events. Decimal MB per observed event divides the whole allocation window, including concurrent diagnostic/list work, by 640; it is not exclusive publication-body cost.

Metric Baseline A Candidate B Change
physicalPaths, MB/observed event 0.3299 0.0045 −98.6%
selectMatchingSessionRows, MB/observed event 0.2493 0.1151 −53.8%
selectSessionRowEntries, MB/observed event 0.2405 0.1711 −28.9%
Three named functions, MB/observed event 0.8198 0.2908 −64.5%
Entire scope module, MB/observed event 0.9159 0.3633 −60.3%
Total, MB/observed event 12.3642 11.4116 −7.7%
Whole-burst GC, ms 1689.7 1627.3 −3.7%
Mean pair-pooled list p95, ms 39.79 43.50 +9.3%
Mean pair-pooled list p99, ms 360.97 215.18 −40.4%

The named functions allocate 524.65 → 186.10 MB/burst; total allocation is 7913.09 → 7303.42 MB/burst. Whole-burst GC paired differences (B minus A) are −519.36, +382.74, +52.18, and −165.50 ms. List p95 paired differences are +0.24, +14.65, +4.06, and −4.10 ms. The 70% target was missed. Mean GC improved, while its mixed signs and higher profiled p95 motivated the bounded unprofiled follow-up below.

Two additional, predeclared unprofiled swapped-core pairs tested that specific latency/GC uncertainty with identical frozen artifacts and workload. They do not replace or discard the profiled results. The production source was unchanged.

Bounded unprofiled follow-up

All twelve successful cohorts are retained, with 1,049 source events and 80 peak streams in every burst. Only allocation sampling and trace-GC logging were disabled; ordinary diagnostics remained enabled.

Metric Baseline A Candidate B Change
Whole-burst GC, ms 1532.72 1529.94 −0.2% (neutral)
Mean pair-pooled list p95, ms 33.70 29.73 −11.8%
Mean pair-pooled list p99, ms 78.85 55.68 −29.4%
Main-thread CPU, ms/burst 18847.61 18671.39 −0.9%

Whole-burst GC paired deltas were +381.01 and −386.58 ms; the nearly cancelling result is neutral, not a claimed GC improvement. List p95 improved in both swapped pairs: 31.63 → 30.27 ms and 35.76 → 29.18 ms. Across 462 list samples per side, descriptive overall pooled p95 was 35.20 → 29.36 ms and p99 was 72.98 → 68.59 ms; the paired values above remain the decision metric.

Owner acceptance: accepted for landing for the consistent allocation reduction and improved unprofiled p95, with neutral GC and no demonstrated regression. Explicitly missed target: 64.5% versus the original 70%. No further benchmark tuning or additional pairs were used.

CI attribution and authorized landing

CI run 39248612042, attempts 1 and 2, failed only in checks-node-changed and the dependent aggregate gate. The repeated case was src/gateway/x-publication-owner-composition.e2e.test.ts:919: anonymous public read returned HTTP 503 instead of 200, “This conversation is temporarily unavailable. Please retry.” Attempt 2 was the single owner-authorized failed-job rerun; no additional rerun was requested.

The owner requested a local behavioral comparison and authorized one nice -n 10 pnpm install --frozen-lockfile in the existing worktree to resolve stale dependencies. It succeeded without tracked changes. Only the failing test file was run, first on the PR head, then on its merge base with current main, using the same dependencies and one worker:

nice -n 10 env OPENCLAW_E2E_SKIP_BUILD=1 node scripts/run-vitest.mjs \
  src/gateway/x-publication-owner-composition.e2e.test.ts --maxWorkers=1

This is the suite's in-process source-composition proof. The supported skip option avoids the unrelated shared E2E distribution build; the test's compiled-worker preparation, source verification, and production-path assertions remained active.

Revision Actual test result Vitest duration
PR head 632be72b66ddc0b5342e9886df0686be6ff57505 1 test passed, including anonymous public read 107.95 s
Merge base 7e47eab3124ab525d6043d1c9343cad2109dfce4 1 test failed with the identical HTTP 503 at line 919 56.17 s

The failing test, package manifest, and lockfile are unchanged between those revisions. The base reproduces the exact CI failure without this PR's code; the reviewed head passes locally. This establishes an inherited/environmental failure for the owner's explicitly authorized exception. It does not claim the flaky failure is fixed or that the failed CI run is green. Performance remains explicitly accepted. No production or test change was needed after review.

Earlier local setup failures executed zero tests and are excluded from this comparison. The only Testbox allocation (blacksmith-testbox, tbx_01m5a2rtx3aymrphdp1prffhxm) queued and was stopped without running tests; its run is cancelled and remote settlement is complete. No benchmark-host dependencies were installed.

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

@steipete
steipete marked this pull request as ready for review October 19, 2026 11:32
@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-19T12:01:51.276319Z 632be72 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.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M labels Oct 19, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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. labels Oct 19, 2026
@clawsweeper

clawsweeper Bot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR reuses topology-owned physical-path lists and removes temporary allocations during session row selection.

Example: Repeated session selection on a Gateway with 5,000 retained sessions.

  • Before: Each physicalPaths lookup allocates a new result array even when topology is unchanged.
  • After: Known paths reuse agent-specific or all-agent arrays until topology replacement.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Source review, independent scan-reference coverage, publication regression coverage, and exact-head CI support correctness; the optimization's measured benefit is not yet established.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor-proof gate; its supplied Gateway diagnosis records indexed publication work, while its separate performance acceptance hold remains binding.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Repeated session selection creates avoidable temporary allocation on large Gateway rosters.
Reason: The maintainer-authored direction targets source-visible repeated work while preserving selection contracts; every production hunk serves that optimization.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep open: this is a focused, maintainer-directed optimization with no actionable correctness findings, and the author has explicitly paused landing pending measurement acceptance.

Priority: P2
Reviewed head: 1c943cbce2b45dfe58384a0f9968cec8628e9a93

Before merge

  • Complete next step - Complete the already-declared paired Gateway measurements and retain this optimization only if allocation, GC, and latency results meet the recorded acceptance rule.

Findings

None.

Agent review details

How this fits together

The Gateway's resident session projection receives admitted store topology and committed publications, selects indexed rows, and supplies session lists, exact reads, and publication targets.

flowchart TD
  A[Admitted store topology] --> B[Session topology owner]
  B --> C[Prepared physical paths]
  D[Queries and publications] --> E[Indexed row selection]
  C --> E
  E --> F[Session projection consumers]
Loading

Technical review

Best possible solution:

Keep path reuse within the existing topology owner and land it only when the recorded performance acceptance rule is met.

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

The base source visibly creates physical-path arrays and matcher closures per selection; the supplied Gateway diagnosis confirms these selectors execute, but this read-only review ran no target code.

Is this the best way to solve the issue?

The implementation follows the existing topology lifecycle, separates agent-specific and broad results, retains unknown-alias admission, and removes the superseded matcher closures without adding a competing owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Store scope matching and indexed candidate selection keeps the original intent (36537b2: Prepare scope paths once per synchronous selection while preserving acquisition order and logical and physical ownership.)
  • Agent-aware topology paths and admitted aliases keeps the original intent (e39ce04: Reuse admission-owned physical identity across symlink spellings without filesystem or database probes.)
  • Metadata-prepared entry selection keeps the original intent (1b896e6: Select current metadata before materializing requested display rows and avoid redundant dirty-row acquisition.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit e39ce04 adds src/gateway/session-row-scope.ts:352 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: e39ce04c8197; files: src/gateway/session-row-scope.ts)

PR surface

Source +32, Tests +118. Total +150 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 66 34 +32
Tests 2 119 1 +118
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 185 35 +150

Labels

Label changes:

  • add P2: This targets temporary allocation during session selection on large rosters, with no established outage or 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: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: This targets temporary allocation during session selection on large rosters, with no established outage or urgent user-facing regression.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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, 7:49 AM ET / 11:49 UTC.

Prepare immutable agent-aware physical path lists with the existing topology owner. Remove transient scope matcher closures, duplicate path resolution, metadata-only state copies, and unused child-key sets while preserving indexed selection and unknown-alias admission.
@steipete
steipete force-pushed the steipete/perf-micro-session-row-scope-publication-index-20260919 branch from 1c943cb to 632be72 Compare October 19, 2026 11:58
@steipete
steipete merged commit 7367ec7 into main Oct 19, 2026
258 of 264 checks passed
@steipete
steipete deleted the steipete/perf-micro-session-row-scope-publication-index-20260919 branch October 19, 2026 13:03
@steipete

Copy link
Copy Markdown
Contributor Author

Merged as 7367ec7 under the owner's authorized inherited/environmental CI exception.

After the authorized frozen-lockfile dependency refresh, the single X-publication composition test passed on PR head 632be72b66ddc0b5342e9886df0686be6ff57505. The identical command and dependencies on merge base 7e47eab3124ab525d6043d1c9343cad2109dfce4 reproduced the exact CI failure: HTTP 503 instead of 200 at src/gateway/x-publication-owner-composition.e2e.test.ts:919. This is actual test execution on both revisions; earlier setup failures are not counted as evidence. The failure therefore exists without this PR's changes. CI attempts 1 and 2 remain failed; no additional rerun was requested.

The owner accepted the performance result: named allocation −64.5% (70% target missed), total allocation −7.7%, neutral unprofiled GC, and list p95 −11.8%. The independent review was clean, and no executable changes followed it. Full qualification and commands are in the PR body.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 20, 2026
…77285)

* perf(sessions): reuse topology paths during row selection

Prepare immutable agent-aware physical path lists with the existing topology owner. Remove transient scope matcher closures, duplicate path resolution, metadata-only state copies, and unused child-key sets while preserving indexed selection and unknown-alias admission.

* perf(sessions): size scoped selection results once
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: M 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