Skip to content

perf(gateway): prepare numeric session list sort keys - #184775

Merged
steipete merged 2 commits into
mainfrom
steipete/coldload-list-sort-comparator
Oct 26, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/coldload-list-sort-comparator

Conversation

@steipete

@steipete steipete commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Reduces session-list sorting allocation during a signed-in dashboard deep-link reload. Historical campaign evidence recorded 14 visible states and roughly 15 seconds to settle; this experiment measures the shared server list path with synthetic data.

The measured sort-owner allocation reduction is 11.8%, better in 9/11 pairs, for +3 runtime lines. The lead accepted this consistent small win under the campaign landing bar, replacing the original arbitrary 50% target. Whole-list allocation is flat and CPU is inconclusive, with no established adverse result. This PR is ready for review; the campaign lead will merge it.

Why This Change Was Made

The comparator repeatedly reads/normalizes numeric clocks and returns numeric differences that V8 can box. Inside sortAndLimitSessionEntries, it creates no key tuples or closures per comparison; callers already supply entry pairs. Activity ordering derives both entries' activity clocks on every comparison. Pin eligibility/key parsing was already prepared once per pinned entry by #183967.

The candidate prepares numeric timestamp/pin keys once per synchronous sort, sorts stable indices through the existing bounded selector, and returns the original entry pairs. It deletes the lazy pin set and its optional comparator callback. Direct pair comparison remains for incremental indexes. The shared selector must treat numeric index zero as a valid first/worst entry.

User Impact

Session lists retain their exact ordering and entry identities while deriving timestamp and pin keys once per entry instead of on every comparison. The measured reduction is confined to the sort family; no end-to-end reload speedup is claimed.

Evidence

Measured baseline 2988b14f22e6ed38eb4b5d35f745f2cdb5a40aef; measured candidate 0148f82f002b4795c17f12a4b6e3a0bb2711a41f. Supersedes the closed measurement experiment #184624 (GitHub refused to reopen it after the branch rewrite). The PR was subsequently rebased cleanly onto main. The only post-measurement sorting edit uses the equivalent typed Array<number>(length) factory spelling to satisfy lint; preparation, ordering, and allocation strategy are unchanged. Final head: cbbf3efa631d3c9a4970b9b1ad19d0405064b478, based on c00af62f03e6ab9929234a998693f53341a4e126. Intervening main commits did not change any touched file. Performance measurements were not rerun after these mechanical changes.

AWS Crabbox cbx_d1529c6edffe, one fixed c7a.4xlarge, released after use. Observed 16 available CPUs with no CPU/memory cgroup limit, 31,378 MiB total RAM, Node 26.12.1. All runs were serial. Eleven counterbalanced pairs used the existing synthetic 10,800-session Team-shape fixture and registry, an identified operator, owner-first/involving-me/recency queries, and limit 200. There were 630 measured lists and 42 warmup lists per run, with 33 registry updates before each list. Timing and allocation sampling ran separately.

Original acceptance declared before measurement: V8 sampled sort-owner allocation at least 50% lower in at least 9/11 pairs, whole-workload allocation lower, and no established CPU regression; then the ten-minute AB/BA server stress gate. Typed-array backing payload is excluded from V8 heap sampling and reported separately. After reviewing the results, the lead accepted the consistent 11.8% sort-family reduction in place of the original 50% threshold and directed proceeding with exact-head CI and P2 review. The long server-stress gate has not been run.

Metric per list Baseline median [IQR] Candidate median [IQR] Better pairs Pairs with ≥50% reduction
Sort-owner heap, KiB 12.002 [11.593, 12.380] 10.591 [10.364, 10.773] 9/11 0/11
Comparator-attributed heap, KiB 5.183 [4.777, 5.564] 0.000 [0.000, 0.000] 11/11 11/11
Whole-workload heap, MiB 10.4017 [10.3856, 10.4097] 10.4034 [10.3972, 10.4135] 3/11 n/a
Untraced list CPU, ms 19.192 [18.809, 19.319] 19.127 [19.096, 19.321] 4/11 n/a

Sort-owner allocation decreased 11.8% by the medians, with 0/11 pairs clearing 50%. Comparator-attributed samples disappeared, but preparation/index costs consumed the expected saving. Whole-workload allocation was flat (+0.017% by medians); CPU was inconclusive with mixed pair signs and overlapping IQRs. These small secondary shifts are not classified as regressions. Whole-workload bytes include the registry updates; heap families overlap.

Per-pair deltas (candidate minus baseline)
Pair Sort-owner bytes/list Whole-workload bytes/list List CPU ms/list
1 -1606.7 -19444.9 +1.369
2 -1543.6 -35065.4 -0.065
3 -1850.8 +18108.3 -0.308
4 -1447.5 +41167.5 +0.374
5 -1963.4 -2904.4 +0.201
6 +1009.7 +4639.4 +1.084
7 -4304.4 +43213.7 +0.265
8 -2173.9 +25543.0 +0.153
9 +798.8 +31043.7 -0.447
10 -2993.8 +7370.7 +0.107
11 -1224.2 +3138.7 -0.168

Median paired deltas: sort-owner −1,606.7 bytes/list; whole workload +7,370.7 bytes/list; list CPU +0.153 ms/list. Differences between medians and medians of paired differences are reported separately.

The isolated ordering benchmark used exported projection rows; its random label means projection export order here, which is already updatedAt-ordered. For 10,800 rows and limit 200, that order made 11,945 updatedAt comparisons and 13,630 activity/interaction comparisons; reverse order made 10,799. With existing pins, backing-inclusive allocation was 484,961 → 531,408 bytes/sort for updatedAt (+9.6%) and 893,589 → 707,229 for activity (−20.9%). The candidate adds 16 backing bytes per entry visit for updatedAt or 8 for other modes, plus JavaScript index/result arrays. None of these backing-inclusive cells cleared 50% in 9/11 pairs.

The allocation probe attributes timestamp-mode allocation to numeric boxing rather than per-comparison tuples/strings. In the supporting source-order probe, activity comparator self samples were about 877,416 bytes/sort (~64 bytes/comparison), and lastInteractionAt about 445,181 (~33 bytes/comparison). Candidate activity preparation still sampled about 517,897 bytes/sort under sessionActivityTimestamp, before indices and backing payload. These are sampled, JIT-context-dependent figures.

Reproduction limit and comparison counts

A separate count-only probe retained the original owner and instrumented its comparator. It recorded these cold scope misses in the same synthetic fixture:

Query, limit 200 Sort calls Entry visits across partition/final sorts Comparisons Candidate backing payload, bytes
Unarchived sidebar 129 11,520 47,173 184,320
All-session sidebar 129 19,440 82,523 311,040
Owner-first 130 12,054 48,562 192,864
Involving me 129 1,388 5,827 22,208
Seven-day recency 129 9,028 36,411 144,448

Entry visits count repeated visits, not unique sessions. After warming, the short measured cycle of 21 request shapes made zero sort-owner calls and zero comparisons despite registry churn. The full 630-list runs captured some sort work, but this workload underrepresents the live hotspot. A follow-up needs matched entry-metadata/timestamp invalidation or cold-scope traffic for a representative follow-up comparison. The live effect may be larger because the warm fixture reuses cached selections, but that is unproven; the isolated updatedAt result also shows that not every workload improves. No additional optimization is included in this PR.

Correctness, review, and remaining gates

  • Initial/final canonical output hashes matched in all 22 timing/allocation pairs.
  • Measured-head corepack pnpm test src/gateway/session-list-order.test.ts --maxWorkers=1: 7/7, 9.90 s wall.
  • Measured-head corepack pnpm test src/shared/sort-and-limit.test.ts --maxWorkers=1: 10/10, 2.19 s wall.
  • Final-head local focused tests also passed via node scripts/run-vitest.mjs <file> --maxWorkers=1: ordering 7/7 (3.80 s wrapper wall), shared selector 10/10 (1.36 s wrapper wall).
  • The activity-key work regression is red on baseline (6,694 reads for 513 entries) and green on candidate (513). The numeric-zero contract also fails with the old shared helper. Randomized ordering covers ties, missing clocks, pin eligibility, bounded/full windows, stability, and input/entry identity.
  • Codex autoreview is scoped-clean through P2 for the full rebased patch and the one-word lint correction. The final rebase is patch-identical over unchanged touched files.
  • Initial ready-PR CI run had one PR-caused failure: unicorn/no-new-array on the preallocated index array. All other selected product checks passed. The corrected spelling matches existing typed Array factory usage in the repository and the upstream rule's permitted cases. Final exact-head CI run and openclaw/ci-gate passed on cbbf3efa631d3c9a4970b9b1ad19d0405064b478: 65 passed / 54 skipped / no failed or pending checks. No inherited reds remain to classify.
  • The ten-minute AB/BA server stress gate was not run; the lead directed proceeding with the existing measurements, exact-head CI, and P2 review; no server handler, GC, loop-p99, or completed-turn improvement is claimed.

Runtime delta: +3 lines. The requested non-test diff is +190/−101 (+89), including +86 benchmark lines; tests add 60 lines. The small runtime growth carries typed keys and preserves the numeric-index-zero contract. No UI, config, protocol, schema, or persistent-record change.

@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:05:04.081165Z cbbf3ef 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 scripts Repository scripts size: M labels Oct 26, 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: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. 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 prepares numeric session ordering keys once per sort and extends the existing performance benchmarks.

Example: Select 200 activity-ordered sessions from 513 entries.

  • Before: The supplied baseline regression records 6,694 activity-key reads.
  • After: The supplied candidate records 513 reads with the same ordering.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, source-consistent optimization with accepted owner-level measurements, limited representative-flow evidence, and pending exact-head CI.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; supplied paired measurements exercise listProjectedSessions with synthetic operator queries on Node 26.12.1 and report lower sampled sort-owner allocation with matching canonical outputs, while whole-Gateway improvement remains unproven.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Large session inventories incur repeated clock derivation and allocation while preparing dashboard session lists.
Reason: The feature owner's recorded decision accepts the modest measured allocation reduction and its limited scope without claiming faster dashboard reloads.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: the feature owner accepted the measured allocation improvement, and review found no actionable correctness or security defect; exact-head CI remains pending.

Priority: P2
Reviewed head: af139a8b6d2ec2429913bc1743848dd36eea8cbf

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: No shipped Gateway reload result is supplied; the owner explicitly waived the remaining server-stress gate.
Agent review details

How this fits together

Gateway list selection passes filtered session entries to the ordering owner, which returns ordered original references for paging through the shared bounded selector.

flowchart TD
 A[Session list request] --> B[Projection and visibility filters]
 B --> C[Session ordering owner]
 C --> D[Sort-local numeric keys]
 D --> E[Shared bounded selector]
 E --> F[Original session references]
 F --> G[Paged response]
Loading

Technical review

Best possible solution:

Retain the focused sort-local preparation and existing selection owners under the accepted allocation tradeoff and normal exact-head CI gates.

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

Current-main source repeats activity-clock derivation during comparisons, and the supplied red-on-base regression quantifies that work; this read-only review ran no target code.

Is this the best way to solve the issue?

Sort-local preparation is a small change within existing owners, preserves direct incremental comparison, and avoids the retained state of the earlier reverted design.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Gateway ordering preparation changes intended behavior with a stated reason (e256b65: Prepare pin eligibility lazily within one synchronous sort to avoid repeated parsing without retained snapshots or cross-request state.)
  • Shared bounded selection keeps the original intent (05e4e17: Consolidate stable bounded selection while leaving ordering policy with callers; subsequent changes reduced comparison work.)
  • Prepared-list benchmark keeps the original intent (6df9874: Measure the production prepared-list owner under synthetic registry churn without claiming transport or model coverage.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Introduced implementation: The pinned introduction replaces the lazy eligibility set with synchronous numeric-key preparation, retains direct pair comparison for incremental consumers, and fixes truthiness checks so numeric index zero participates correctly. (src/gateway/session-list-order.ts:40, af139a8b6d2e)
  • Current-main behavior: Fetched main still derives clocks during comparisons and prepares pin eligibility with a sort-local set; this PR's numeric preparation is not already implemented there. (src/gateway/session-list-order.ts:47, 91fa755ffd6d)
  • Accepted performance tradeoff: The full maintainer-authored PR body accepts an 11.8% sampled sort-owner allocation reduction, better in 9/11 pairs, with flat whole-workload allocation and inconclusive CPU; it explicitly waives the original 50% threshold and remaining server-stress gate. (af139a8b6d2e)
  • Earlier revert considered: revert(gateway): restore sessions.list filtering and ordering before #179211 and #180067 #180166 reverted broader retained ordering machinery after owner-level gains failed to establish production gains; this PR confines preparation to each synchronous call and explicitly limits its performance claim. (42fa30f48422)
  • Superseded experiment: experiment(control-ui): prepared session sort keys [superseded by #184775] #184624 is the closed measurement experiment explicitly superseded by this PR; its earlier review predates the supplied measurements and accepted landing bar.
  • Exact-head checks: The CI gate remains pending, with queued checks and no observed failed correctness check; security-sensitive and dependency-review statuses pass. (af139a8b6d2e)

Likely related people:

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

PR surface

Source +3, Tests +60, Other +86. Total +149 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 31 28 +3
Tests 2 60 0 +60
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 2 159 73 +86
Total 6 250 101 +149

Review metrics

Metric Value Why it matters
Runtime versus test growth Runtime +31/-28 lines; tests +60/-0 lines The small runtime increase replaces the eligibility set with numeric preparation; tests exercise ordering equivalence, reduced clock reads, and numeric zero.

Root-cause cluster

Relationship: canonical
Canonical: #184775
Summary: This PR explicitly replaces the closed measurement experiment for the same numeric-key optimization.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add P2: This is a bounded session-list performance improvement without an established 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: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: This is a bounded session-list performance improvement without an established urgent user-facing regression.
  • 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, 12:07 PM ET / 16:07 UTC.

Compute timestamp and pin keys once per synchronous sort and select stable numeric indices. Preserve direct pair comparison for incremental selection indexes. Extend the synthetic Team-shape benchmark to attribute sort allocation across identified operator list scopes.
@steipete
steipete force-pushed the steipete/coldload-list-sort-comparator branch from af139a8 to cbbf3ef Compare October 26, 2026 17:03
@steipete
steipete merged commit 5c9141c into main Oct 26, 2026
138 checks passed
@steipete
steipete deleted the steipete/coldload-list-sort-comparator branch October 26, 2026 17:44
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 27, 2026
…4775)

sortAndLimitSessionEntries used compareSessionEntryPairs as its comparator, which derived pin and timestamp facts on every comparison and allocated a lazily built pinnable set and closure for each list.

The sort now computes each entry's timestamp and effective pin once per list into typed arrays, sorts indices, and maps back. Ordering, including ties, pins and activity sorting, is unchanged. compareSessionEntryPairs loses its optional pinnable callback.

Evidence, 11 interleaved pairs: sort-path allocation 12,291 -> 10,845 bytes/list (-11.8%, 9/11 better); whole-list allocation flat; CPU inconclusive. The warm benchmark reuses cached selections, so the live effect is likely larger but unproven. 17 focused tests pass. Runtime +3 LOC.
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. scripts Repository scripts 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