Repository navigation
perf(gateway): reduce registry allocations during session presentation - #184698
Conversation
Maintain the newest matching live controller in the registry and refresh it when executor or scheduler ownership changes. Remove row-time run scans while preserving generation ordering, partial session identities, foreign control, and durable parent navigation. Release-note context: reduce session-list and Control UI row-presentation allocation without changing controller or parent relationships.
Share the existing execution ownership checks through a state-bound adapter, retain the controller scan negative control, and prepare runtime config before benchmark projection startup.
Match the Team harness 100-row list request while retaining the full 10,800-row fixture and all-row owner workload. This keeps setup within the existing exact-row preparation budget.
|
🦞👀 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: needs maintainer review before merge. What this changesThis PR reduces temporary allocations in session-controller lookup and settled-descendant counting and extends the existing performance probe. Example: Repeatedly list 100 sessions from a 10,800-session synthetic workspace.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this maintainer-authored PR delivers an accepted allocation improvement, with no actionable correctness or security findings and successful exact-head CI. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherGateway session presentation consumes registry rows, session identities, and live execution or scheduler ownership to produce controller relationships and descendant counts. flowchart TD
A[Session list request] --> B[Session presentation]
B --> C[Registry child buckets]
C --> D[Live execution and reservation checks]
D --> E[Controller relationship]
B --> F[Descendant topology]
F --> G[Active descendant count]
E --> H[Session response]
G --> H
Technical reviewBest possible solution: Retain this focused optimization in the existing registry owner with unchanged controller authority, ordering, and descendant-count semantics. Do we have a high-confidence way to reproduce the issue? Source inspection confirms the baseline's temporary lookup and count-map allocations, and the supplied paired measurements exercise them; no target code was run during this read-only review. Is this the best way to solve the issue? The change removes redundant representations and per-read allocations at existing owners, preserves live checks, and avoids a new invalidation lifecycle; new flags are confined to the benchmark. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 797f83a103a6. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +45, Tests +214, Other +267. Total +526 across 9 files. Added test files: 1. View PR surface stats
Review metrics
LabelsLabel changes: No label 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 HistoryReviewed October 26, 2026, 2:59 PM ET / 18:59 UTC (Revision 3). |
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. |
|
The completed final-head evidence is now in the PR body: 174 focused tests on The controller-release regression at sessions-send-communication.test.ts:484 uses the real registry row, a real execution claim, and the new controller query. That query is retained from The delivery authorization owner is unchanged. Its assertTask check still resolves current control at final admission. The performance harness is not a foreign-controller/reassignment delivery trace, and no such trace is claimed. With no concrete authorization defect identified, I am not treating an additional adversarial delivery-race trace as a new requirement for this equivalent registry-read optimization. The production boundary regression, independent selection equivalence, fresh clean P2 source review, and completed Gateway workload are the supplied proof. The measured allocation gains were accepted for the ready PR; the handoff still stops before merge. Please reassess the completed evidence and identify any concrete remaining defect. @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Lane 1871 is repairing restart recovery correctness in |
…penclaw#184698) Row presentation resolved each child session's controller by iterating that child's runs through the registry (iterator, closure and owner tuples per call), and countActiveDescendantRuns walked descendant runs on every list. On Team these were among the top selection-side allocation families (getSubagentRunsForChildSession, resolveSessionChildController, countDescendantRuns). The incremental registry run index (openclaw#183531) now keeps the latest matching controller per child session current through its existing update path, so presentation reads it directly. Descendant reads iterate the prepared buckets without per-call allocation, rebased on openclaw#184566, which already passes prepared descendants into countDescendantRuns. Results are identical; property tests cover status transitions, replacement runs and agent mismatches. Evidence, 11 interleaved pairs on AWS c7i.4xlarge: owner-resolution allocation 8.551 -> 1.645 MB/pass (-80.8%, 11/11), descendant reads 292.1 -> 72.8 KB (-75.1%, 11/11), whole-list allocation 4.446 -> 4.299 MB (-3.3%, 10/11); CPU inconclusive. Team-shape harness (20 measured minutes): handler mean 16.67 -> 16.88 ms, main CPU 12.49% -> 12.55%, GC flat, 40/40 turns, zero RPC errors; no regression under the rule. 174 tests pass. Runtime +45 LOC.
What Problem This Solves
Repeated session presentation allocates temporary objects while resolving child controllers and counting active descendants. A settled profile attributed 3.41 MB per 30 seconds to child-run lookup and 4.73 MB to descendant counting. This targets server allocation. The broader campaign observed 14 intermediate states during a signed-in reload of a dashboard deep link; this change makes no visual or first-paint claim.
Why This Change Was Made
Registry buckets use arrays, and their final element supplies the existing last-published lookup, deleting the separate latest-insertion map. Presentation reads a child bucket directly without the old iterator, per-call predicate, composite lookup key, or parent-comparison array. Live executor/reservation authority, agent ownership, incarnation matching, and generation ordering are preserved. This remains O(runs in the child's bucket), usually a singleton; it does not cache live authority.
Main already supplies prepared descendant arrays, indexed iteration, and shared active-only options (#184566). This branch keeps only the remaining thirteen-line fast return: entirely ended descendant sets return zero without filling a fresh count map with zero entries; unended work retains the existing window-specific count memo and clock semantics. Array replacement is linear in bucket size, and the whole-list measurements include that write cost. No protocol, durable record, configuration, or schema changes.
User Impact
This change preserves controller, parent, and navigation semantics in focused/property tests and reduces allocation on the synthetic workload, with measured allocation savings and the steady-state timing evidence below. No UI files change and no cold-load latency improvement is claimed.
Evidence
Final candidate:
5e2b04c0d31ae8ec4c79099d11009d523b745d1a.Frozen new-main baseline:
d3ce499054a038450b064a317d9a74615457cdd4, including #184566 (4293b683) and the nearby landed selection work. The overlapping descendant changes were dropped before both revisions were installed and fully built. No rebase or source changes occurred after those builds; post-measurement heads, runtime diffs, and benchmark/test hashes were verified.One AWS
c7i.4xlargewas used for both arms throughout: 16 vCPUs (8 Intel Xeon Platinum 8488C cores, two threads/core), 31 GiB RAM, full CPU affinity. This is the authorized alternative dedicated 16-vCPU class. Node 26.12.1 / pnpm 12.15.0. Leasecbx_c9383d0e4689; proof run.The committed
scripts/perf/session-child-owner-measure.tsuses the 10,800-session synthetic fixture, including 4,300 unarchived subagent records, 48 fixed churn roots, and 2,160 requester roots. Each group has eleven alternating AB/BA pairs, run serially on the same box: owner timing, list timing, owner allocation, and list allocation, 88 measured arms total. All completed without discarded or repeated pairs. Four full-size smoke runs, two call censuses, and both allocation-region qualifications passed first. The owner workload presents all 10,800 rows per pass and uses 8,000 updates / 1,000 warmup updates and 240 measured passes (518,400 descendant queries and 2,592,000 owner reads per arm). The production list workload uses 1,200 updates / 200 warmup updates and 36 measured 100-row pages from the full fixture. Whole-list totals include registry maintenance; counts and checksums agree between arms.Targeted allocation uses separate temporal sampling regions after batched writes and index preparation. V8 optimization stays enabled; every sampled byte is counted. The owner region includes argument spreads and CPU bookkeeping, and both regions include sampling-boundary overhead. These are conservative region totals, not exact per-function allocation sizes. No overhead was subtracted. Whole-list allocation uses the unchanged global sampler. The raw region sums and 240 epochs per region were independently audited, as were all sixteen summary rows and all paired deltas; all 284 captured microbenchmark artifact hashes match.
The original 80% regional threshold was withdrawn after review of the complete comparison: the 80.8% / 75.1% targeted reductions (11/11 each), 3.3% whole-list allocation reduction (10/11), and +45 runtime LOC were accepted as a small consistent win. The additional gate is one canonical steady-state real-Gateway timing pass against these same frozen revisions, on one dedicated 16-vCPU AWS box after full installs/builds. Run
--mode timing --minutes 10 --pairs 1with the default 10,800-session / 65-client / 40-plugin workload. This is one AB pair (twenty measured minutes, plus setup/warmup), despite the original approximate forty-minute estimate. Report handler mean, row-selection counters per list, main CPU, GC, loop p99, achieved requests, and completed turns. No secondary regression under the declared IQR/paired rule; a single AB pair cannot establish an eleven-pair significance claim. The baseline and candidate below are medians, with IQRs in brackets; MB means decimal megabytes. Deltas are candidate minus baseline.Whole-list resolution CPU was 17.856 → 18.528 ms/pass (paired median +0.281 ms); total thread CPU including updates was 19.832 → 20.477 ms/pass (paired median +0.272 ms). Both IQRs overlap and both have 8/11 adverse pairs, below the required 9/11. The total median rise is +0.646 ms (3.26%). Under the declared secondary regression rule these are inconclusive, with no demonstrated regression; The regional allocation results were accepted; the completed steady-state harness is reported separately below.
In representative pair 1, descendant-region samples attributed to native
setfell from 53,724,360 to 497,008 bytes across 240 passes. The candidate's dominant remaining attribution is folded intoreadActiveDescendants(16,716,672 bytes). Inlining prevents a defensible finer allocation-site claim from this sample. The retained path handles active/unended work with the existing liveness/retention semantics; the fast return applies only to entirely ended descendants. A finer attribution or a different simplification would be needed for any further optimization. No unmeasured follow-up is included here.All metrics, IQRs, and eleven per-pair deltas
Units follow the metric names: CPU/GC in milliseconds; allocation/retained heap in bytes. Whole-list thread CPU includes update work. Raw threadCpuMs is total measured-arm CPU; the PerList field normalizes it by the measured passes.
Per-pair deltas (candidate − baseline):
owner / timing / resolutionCpuMsPerList: -11.152046, -9.868942, -11.196808, -11.858367, -10.126400, -12.429037, -9.610054, -9.411579, -10.617008, -11.009950, -12.075217
owner / timing / threadCpuMs: -2704.607000, -2382.535000, -2688.510000, -2865.235000, -2433.994000, -3001.459000, -2318.546000, -2274.037000, -2559.052000, -2651.340000, -2930.723000
owner / timing / threadCpuMsPerList: -11.269196, -9.927229, -11.202125, -11.938479, -10.141642, -12.506079, -9.660608, -9.475154, -10.662717, -11.047250, -12.211346
owner / timing / updateCpuMsPerUpdate: +0.000316, +0.001500, +0.002030, -0.000311, +0.001236, -0.000721, +0.000971, +0.000190, +0.000542, +0.001802, -0.001797
owner / timing / gcMsPerList: -0.156943, -0.155766, -0.159569, -0.157344, -0.156237, -0.161696, -0.159136, -0.152616, -0.154423, -0.154537, -0.150530
owner / timing / retainedHeapAfter: -1624520.000000, -1693120.000000, -1353016.000000, -2344192.000000, -1657072.000000, -1641696.000000, -1574472.000000, -1639880.000000, -1653904.000000, -1640088.000000, -1627640.000000
owner / timing / ownerCpuMsPerList: -11.002462, -9.704000, -10.222713, -11.615150, -9.922692, -11.525158, -9.335100, -9.212842, -10.091421, -10.272671, -11.455087
owner / allocation / ownerRegionAllocatedBytesPerList: -6862602.366667, -6860284.433333, -6897185.833333, -6931301.200000, -6873183.233333, -6916564.566667, -6924060.700000, -6902447.466667, -7058835.566667, -6976704.066667, -6978296.500000
owner / allocation / descendantRegionAllocatedBytesPerList: -216457.066667, -230119.100000, -221103.033333, -211934.766667, -222005.000000, -225545.266667, -223067.000000, -213583.466667, -214359.700000, -219912.366667, -218157.466667
list / timing / resolutionCpuMsPerList: +3.545361, +0.245722, -1.682639, -0.080278, +0.750444, -2.988389, +0.281028, +0.862556, +0.267750, +2.002139, +1.657639
list / timing / threadCpuMs: +133.349000, +7.167000, -62.127000, -8.741000, +28.694000, -108.916000, +9.801000, +34.629000, +5.052000, +75.883000, +62.805000
list / timing / threadCpuMsPerList: +3.704139, +0.199083, -1.725750, -0.242806, +0.797056, -3.025444, +0.272250, +0.961917, +0.140333, +2.107861, +1.744583
list / timing / updateCpuMsPerUpdate: -0.002522, +0.001258, -0.007669, -0.001669, +0.000753, -0.002193, +0.000631, -0.001803, -0.002404, +0.004000, +0.002651
list / timing / gcMsPerList: -0.023132, -0.019335, +0.014873, +0.025988, +0.035914, -0.021275, -0.024803, +0.000270, +0.012548, -0.049078, +0.052157
list / timing / retainedHeapAfter: -1467128.000000, -1449928.000000, -1569800.000000, -1574760.000000, -1559320.000000, -1569664.000000, -1679240.000000, -1662440.000000, -1571480.000000, -1711816.000000, -1601216.000000
list / allocation / allocatedBytesPerList: -157260.666667, +44196.666667, -240077.555556, -136003.111111, -130573.777778, -17051.111111, -257268.888889, -86131.555556, -57732.222222, -112433.111111, -224761.777778
Correctness, checks, and uncovered gates
Both frozen revisions completed full dependency installation and full builds. All twelve focused files passed on the final candidate: 174 tests, 640.24 seconds total wall time, each run independently with
pnpm test <file> --maxWorkers=1. The controller equivalence property test compares against the original scan over seeded registry mutations, status transitions, replacement runs, generation/incarnation changes, and agent mismatch. Descendant tests cover nested/cyclic graphs, status/generation/replacement changes, and finite/nonfinite ended timestamps. The iterator regression added by #184566 remains intact.src/gateway/session-child-controller.test.tssrc/gateway/session-utils.navigation-lineage.test.tssrc/gateway/session-row-presentation.test.tssrc/gateway/session-utils-row.materialize.test.tssrc/agents/tools/sessions-send-communication.test.tssrc/agents/subagents/registry/subagent-registry-memory.test.tssrc/agents/subagents/registry/subagent-registry-read.scoped.test.tssrc/agents/subagents/registry/subagent-run-liveness.test.tssrc/agents/subagents/registry/subagent-liveness.owner-integration.test.tssrc/agents/subagents/registry/subagent-registry-queries.test.tssrc/agents/subagents/registry/subagent-child-owner-match.test.tssrc/agents/subagents/registry/subagent-controller-inputs.test.tsComplete changed-file validation (
node scripts/check-changed.mjs --base d3ce499054a038450b064a317d9a74615457cdd4 --head 5e2b04c0d31ae8ec4c79099d11009d523b745d1a --timed) took 1,263.51 seconds. Core types, every core-test typecheck shard, script types, lint, formatting, and guards passed. The dead-export scan failed with twenty findings; the same twenty reproduce on the untouched frozen main, with zero candidate-only findings. No check was skipped to obtain green.A fresh complete-branch independent autoreview, including the full benchmark and registry owner source, is clean through P2. The first review attempt timed out after the full hour; the required retry produced a valid clean verdict. A subsequent conflict-free rebase left all five runtime files and the benchmark byte-identical to that reviewed source.
Steady-state real-Gateway timing
Both frozen revisions were independently installed and fully built again on AWS lease
cbx_ba79d790dc09, onec7i.4xlargein eu-west-2, before an AB setup smoke and the canonical command below. Harness run. The stock image initially lacked npm; that prerequisite was installed before either build or measurement, on the same retained box. No measured pair was discarded or repeated, and no source/rebase changes occurred after building.The harness generates independent synthetic state for each arm: 10,800 sessions, 65 operator clients, four mock-provider turns per round, 40 enabled bundled plugins, 128 MiB synthetic transcripts, one-minute warmup, ten-minute measured duration per arm. One AB pair is twenty measured minutes plus setup, rather than the original approximate forty-minute estimate. The smoke is setup proof only. Timing does not sample allocations or force GC during measurement.
One AB pair: twenty measured minutes, not forty. Absent counter series mean no observed calls, not an improvement. Client list p99 is context; known A/A spread is approximately ±120 ms. This sample count cannot establish an eleven-pair secondary regression.
All row-selection counter kinds present in the captured Prometheus interval:
Counter denominators are the captured
sessions.listrequest-counter deltas, not client latency sample counts. Absent series mean no observed calls, not an improvement.Base: 1173 list requests in the scrape interval; 1183 measured client list completions; 195.294 measured RPCs/minute; 40 completed turns.
Candidate: 1173 list requests in the scrape interval; 1183 measured client list completions; 195.495 measured RPCs/minute; 40 completed turns.
Descriptive within-run minute windows (not independent paired runs):
The captured intervals each contain 1,173 list requests. Counter task labels distinguish direct RPC work from background work: both arms recorded one
agentand onebroadselection attributed tosessions.list;running-candidatewas 8,824 → 8,780 andstorewas 68 → 76, all attributed toother. Thus the normalized background counters are context, not per-RPC call-site counts. The extra eight background store selections are reported, with no consistent-regression claim from one pair. Both arms completed 40 turns and 108 committed timestamp writes, and every measured RPC error count is zero.One AB pair cannot prove the eleven-pair sign-test condition; the minute windows are correlated descriptive samples. Handler mean and main CPU are separate boundaries; client list p99 retains its documented approximately ±120 ms A/A noise context. The acceptance assessment must use the observed results and this sample limitation.
Size, scope, and cleanup
Runtime-only delta: 100 insertions, 55 deletions, +45 LOC across five files. This is within the +60 limit; preserving live authority and incarnation/generation matching in the direct owner query requires the growth. The per-call gateway predicate/scan path and redundant latest-insertion map are deleted. The query-owner delta against new main is only thirteen added lines; #184566's prepared arrays, indexed iteration, shared options, and eliminated duplicate lookup are retained.
Requested non-test/non-doc stat (
git diff --stat origin/main...HEAD -- ':!*.test.ts' ':!*test-support*' ':!docs/*'): 447 insertions, 135 deletions, +312 net, including +267 benchmark LOC. Runtime files:subagent-registry-memory.ts,subagent-child-owner-match.ts,subagent-registry-read.ts,subagent-registry-queries.ts, andsrc/gateway/session-utils-core.ts. Three focused test files and the committed benchmark complete the nine-file diff. No protocol, configuration, schema, or durable-state changes.The allocation-proof lease
cbx_c9383d0e4689and its superseded validation leases are released. Harness leasecbx_ba79d790dc09is confirmed released (i-0ce132000ad022ea5). All confirmed owned leases are released, and the harness cleaned up its isolated Gateways. The older uncertain requestcbx_2e4f981e5370was reconciled on its same AWS route in us-east-1: status and authoritative provider inspection return HTTP 404not_found; no matching lease record is available to release, and no EC2 termination receipt is claimed.This PR replaces closed #184152. Ready status follows the accepted allocation comparison and completed steady-state gate. Exact-head CI status and regression assessment are recorded below before handoff. Stop before merge.
Acceptance and CI
The completed steady-state pass shows no regression under the declared rule: handler mean +0.208 ms (1.25%), CPU +0.054 percentage points (0.43%), GC +0.0023 seconds/minute (0.84%), loop p99 +2.490 ms (6.48%). CPU, GC, and minute-loop-p99 IQRs overlap. The loop movement is below the absolute 10 ms paired-rise threshold; one AB pair cannot establish the multi-pair sign condition. Background selection-count differences are disclosed above, while direct-RPC counts and completed work agree. These are small/noisy secondaries, not demonstrated harm. This is a single timing-pair acceptance result, not a statistical speedup claim.
The measured allocation improvements are accepted under the small-wins bar: owner −80.8% and descendants −75.1% (11/11 each), whole-list allocation −3.3% (10/11), for +45 runtime LOC. The old 80% regional cutoff is withdrawn. Full per-pair allocation and CPU deltas remain above.
Exact-head CI run 40379329976 is green for
5e2b04c0d31ae8ec4c79099d11009d523b745d1a: 73 completed jobs, 46 successful and 27 scoped skips, with no failed jobs.openclaw/ci-gateis successful. There are no red CI jobs requiring main comparison. Three historicalauto-responsecancellations remain outside this successful CI run; no CI workflow was rerun. The earlier changed-file dead-export failure is classified against the identical frozen-main result above.The independent autoreview is clean through P2. The exact-head GitHub code review reports no findings. The updated ClawSweeper review accepts the supplied production-path evidence, reports no actionable findings, and lists no before-merge items. The earlier extra authority-trace request was addressed with the real-registry admission regression and unchanged final-admission owner, as explained in the evidence response; no separate foreign-controller Gateway trace is claimed. One explicit re-review request was posted after updating the evidence.
Ready, open, mergeable, and stopped before merge. No merge or auto-merge.