Repository navigation
perf(gateway): prepare numeric session list sort keys - #184775
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex review: needs maintainer review before merge. What this changesThis PR prepares numeric session ordering keys once per sort and extends the existing performance benchmarks. Example: Select 200 activity-ordered sessions from 513 entries.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherGateway 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]
Technical reviewBest 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
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +3, Tests +60, Other +86. Total +149 across 6 files. Added test files: 0. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment 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.
af139a8 to
cbbf3ef
Compare
…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.
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 candidate0148f82f002b4795c17f12a4b6e3a0bb2711a41f. 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 typedArray<number>(length)factory spelling to satisfy lint; preparation, ordering, and allocation strategy are unchanged. Final head:cbbf3efa631d3c9a4970b9b1ad19d0405064b478, based onc00af62f03e6ab9929234a998693f53341a4e126. Intervening main commits did not change any touched file. Performance measurements were not rerun after these mechanical changes.AWS Crabbox
cbx_d1529c6edffe, one fixedc7a.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.
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)
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
randomlabel 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:
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
corepack pnpm test src/gateway/session-list-order.test.ts --maxWorkers=1: 7/7, 9.90 s wall.corepack pnpm test src/shared/sort-and-limit.test.ts --maxWorkers=1: 10/10, 2.19 s wall.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).unicorn/no-new-arrayon 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 andopenclaw/ci-gatepassed oncbbf3efa631d3c9a4970b9b1ad19d0405064b478: 65 passed / 54 skipped / no failed or pending checks. No inherited reds remain to classify.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.