Repository navigation
perf(infra): consolidate per-turn async context stores - #181780
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. |
|
fb28241 to
5d7d6a1
Compare
|
Codex review: needs maintainer review before merge. What this changesThis PR consolidates independent async-context stores into symbol-keyed fields in one shared carrier. Example: The exact-head synthetic Gateway workload completes 480 foreground turns per side.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review The final pair resolves the previous performance hold under the recorded maintainer amendment; no actionable code findings remain, and this PR should stay open for the lead. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherGateway, agent, session, and infrastructure owners place their existing scope values into async context; nested callbacks retrieve those same values while lifecycle and authorization decisions remain with their owners. flowchart TD
A[Gateway and agent turns] --> B[Existing scope owners]
B --> C[Symbol keyed context fields]
C --> D[Shared native async storage]
D --> E[Nested and detached callbacks]
E --> F[Existing lifecycle and authority checks]
Technical reviewBest possible solution: Preserve the scoped consolidation and its explicit measurement limits for the lead’s final landing assessment. Do we have a high-confidence way to reproduce the issue? The baseline store layout and supplied Gateway census establish repeated native-frame copying; this is a performance improvement rather than a functional bug. Is this the best way to solve the issue? One shared carrier removes repeated native entries while existing owners retain their values, nesting, cleanup, and authority checks. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 6118d10381a2. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +30, Tests +121, Docs +68, Other +224. Total +443 across 32 files. Added test files: 1. View PR surface stats
Review metrics
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 HistoryReview history (2 earlier review cycles)
Reviewed October 23, 2026, 4:07 PM ET / 20:07 UTC (Revision 3). |
5d7d6a1 to
15da14e
Compare
15da14e to
5cd8132
Compare
|
@clawsweeper re-review The PR body now contains the completed Gateway evidence and sample counts for head Performance acceptance remains HOLD: pair 2 recorded a maximum major-GC pause of 1,194.272 ms against a 731.486 ms limit. The event occurred inside the measurement window; its cause is unproven. Mean allocation, promotion, total GC per turn, and event-loop p99 improved, but those averages do not override the maximum-pause safeguard. The body also records incomplete dynamic-work accounting, measured-versus-published revisions, and the discarded pair. Keep this PR unmerged for the lead's assessment. No further benchmark rerun is planned; the synthetic sandbox is cleaned up and raw evidence is preserved. |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review The authorized final acceptance pair is complete on exact head Performance acceptance PASSES under the October 23 maintainer ruling: pair 3's candidate maximum major-GC pause is 85.283 ms, below its 197.800 ms limit. Across all three pairs, mean paired allocation is −12.34%, promotion −33.91%, total GC/turn −11.41%, and loop p99 −4.86%; every core metric improves in every pair. Fixed work and reset counts match. The final body includes all three paired tables with sample counts, 1 Hz PSI and timestamped journal evidence, the smaller pair-3 dynamic-work difference, and the retained pair-2 1,194.272 ms outlier. That earlier pause remains unexplained; host interference is plausible but unproven. The supplemental pair observed no major pause above twice either side's pair-1 maximum. Exact-head CI remains green, and the sandbox has been cleaned up after evidence verification. Keep this PR open and unmerged for the lead's final assessment. No fourth pair was run. |
|
🦞👀 Re-review progress:
|
* perf(infra): consolidate per-turn async context stores * fix(perf): report unavailable native frame attribution * perf(infra): fold remaining request scopes into async context * fix(infra): satisfy async-context probe CI checks * chore(perf): document native receiver handling in probe lint
Absorb openclaw/openclaw main at 9629838 (967 commits past 7ab6453) into P ea81534. 39 textual conflicts, resolved upstream-first; every ours/combined resolution keeps a continuation or carried-fleet symbol and is listed with its reason in the lane's table.tsv / RESOLUTION.md. Schema: upstream took agent schema 32-34 (PostgreSQL-only vector decoder, binary vector projection, index ordering; SQLite advances metadata only) and state 32. The continuation recipient-authority step moves from 32 to 35, above upstream's steps; on SQLite a P-era 32 database is upstream's 32 plus the authority table, which the idempotent step admits. Ports into upstream's new owners: - agent-runner-result-complete.ts deleted upstream (openclaw#181917, inlined into agent-runner-result.ts); the continuation delta moves onto the inlined block. - subagent registry activation returns AgentRecoveryProgress (openclaw#181428); the continuation activation latch follows progress.settled. - announce reply-instruction / params moved by the fork receive upstream's requesterOrigin (openclaw#182124) and onAccepted (openclaw#182285). - diagnostic trace context moved to the shared AsyncContext carrier (openclaw#181780); the fork's test reset clears only its own field. Generated files regenerated with their generators (postgres schema, config doc baseline). Refs karmaterminal/openclaw-bootstrap#1727 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Performance acceptance: PASSED under the maintainer's October 23 three-pair ruling below. Pair 3 measures the exact published head, satisfies the maximum-major-pause envelope, and all four core metrics improve in every pair. Pair 2's unexplained outlier remains in the evidence. CI and code review are green; keep this PR open and unmerged for the lead.
What Problem This Solves
Agent turns carry many independent async-context stores, so every native frame copy repeatedly copies the same per-turn entries.
User Impact
No intended behavior change. This consolidates internal context storage while preserving each owner's nesting, cleanup, revocation, and detached-work behavior. Across three valid Gateway pairs, mean paired changes are allocation −12.34%, promotion −33.91%, total GC per turn −11.41%, and event-loop p99 −4.86%. The second pair recorded a 1,194 ms major-GC pause against a 731 ms limit; the authorized final pair recorded an 85.283 ms candidate maximum against a 197.800 ms limit. Acceptance passes under the amended rule, with outlier causality and production-scale benefit still unproven.
Why This Change Was Made
Thirty-two stores across twenty-four owners now use fields in one shallow-frozen record. Child scopes share unchanged values by reference. Captured callbacks still restore only the fields they own; native
runand the single-copy runner preserve their different restoration semantics. The two async-work carriers and agent-event execution carrier remain separate because released runtime callbacks explicitly interoperate with them. The main-thread monitor also remains native because its stop path uses nativedisable()semantics. Plugin invocation and re-entry layers are unchanged.Evidence
Acceptance rule, set before measurement: on Node 26.12.1, compare source-entry synthetic Gateways with 5,000 sessions, 6,000 retained runs, tool calls, subagents, and mixed RPCs. Count native stores per copied frame first; measure collected-object allocation per scope entry, then two concurrent pairs on swapped interleaved 16-CPU sets. Require matching completed rounds and session resets. Evaluate allocation, promotion, total GC per turn, and event-loop p99 from paired deltas. Reject a mean adverse delta of at least 20%, or at least 10% adverse in both pairs. Opposite signs or baselines differing by more than 5x are inconclusive and require a third pair for gating metrics. Tail gates require 1,000 p99 samples / 200 p95 samples; major GC tails are context below 50 collections. GC pause-percentile changes below 1 ms absolute paired-mean delta are context; reduced collections with non-increasing total GC also qualify, while the maximum-pause limit remains max(50 ms, twice the baseline maximum). Guard-interrupted runs are discarded.
Target: at most six native stores per copied frame and at least 60% less native frame-copy allocation, without adverse promotion. Targets are not substitutes for the acceptance rule.
Acceptance amendment, October 23, before pair 3: run exactly one additional valid pair on published head
5cd8132a45055767ad97cbbbf2c359636f177fefagainst its merge-base6cc605dfe2044a2d2649dea02458e7982739d493, with baseline on even CPUs and candidate on odd CPUs (opposite pair 2). Preserve the workload and shared guard; sample cgroup and host memory/IO PSI every second and collect timestamped production main-thread-stall events read-only. Acceptance passes if pair 3's candidate maximum major pause is no greater thanmax(50 ms, 2 × pair-3 baseline maximum)and the allocation, promotion, total GC/turn, and loop-p99 means across all three pairs hold under the existing decision rules. Otherwise retain HOLD and investigate the major-GC traces; no fourth valid pair. Keep pair 2's outlier in the evidence. Host interference is plausible but unproven. This is the maintainer's first ruling on that outlier; the earlier no-third-pair interpretation was the worker's.Focused validation passed 285 tests across the shared carrier/runner, affected owner contracts, wrapper closure checks, and CI test-plan routing. One spawn-broker test is skipped on macOS; Linux PR CI owns that platform proof. The one local core tsrs lane, export-name collision check, changed-file lint/format, and probe smoke passed. No Testbox/Crabbox lease was used; PR CI supplies broad validation.
The carrier regression tests cover nested scopes, clearing, throws, mutable value identity, concurrent and detached continuations, globally shared versus local fields, and independent sibling restoration. Initial review found an incorrect sibling-field restoration and two probe assumptions; all were corrected before the published implementation. Fresh independent review reports no actionable findings. Follow-up probe lint and assertion-comment repairs received independent subagent review (autoreview route unavailable), also clean.
Focused test files
src/shared/async-context.test.tssrc/shared/async-store.test.tssrc/infra/diagnostic-trace-context.test.tssrc/process/gateway-work-admission.continuation.test.tssrc/agents/agent-tools.ring-zero-context.import-boundary.test.tssrc/agents/tools/gateway-caller-context.test.tssrc/config/sessions/transcript-write-context.test.tssrc/infra/sqlite-transaction.diagnostics.test.tssrc/infra/sqlite-database-admission-turn.test.tssrc/infra/net/fetch-guard.authority.test.tssrc/agents/code-mode-state.test.tssrc/agents/subagents/spawn/subagent-capabilities.store.test.tstest/scripts/eager-import-closure.test.tstest/scripts/pr-wrapper-source-closure.test.tstest/scripts/ci-node-test-plan.test.tssrc/process/spawn-broker/callback-context.test.ts(macOS platform skip)Runtime production delta: +171 / −141 lines, net +30 (excluding tests and measurement tooling). The new carrier adds a small amount of production code to preserve native field-local restoration and share state across separately loaded runtime chunks. It replaces the migrated stores outright; there is no parallel compatibility carrier or retained prepared-state cache.
Frame census and owner allocation
The plugins-enabled synthetic Gateway census observes the source frame immediately before native
enterWithcopies it. Both sides completed two measured cohorts, five total cohorts, sixteen session resets, and two synthetic cron runs. Snapshot boundaries have approximately one second of uncertainty; the census instrumentation is absent from allocation and latency acceptance runs.The six-store target is missed. The shared carrier, two async-work carriers, native task monitor, plugin invocation, input recovery, and agent-event execution account for seven high-presence stores. The two async-work stores and agent-event context preserve released-runtime interoperability; the monitor uses native in-place
disable()semantics; plugin invocation and input recovery belong to the separate re-entry work. Lower-presence model/tool/lifecycle scopes explain the rest. This change deliberately preserves those ownership boundaries.Node 26.12.1 owner measurements use the census-shaped 26 → 8 native entries: baseline has twenty-five ambient native stores plus a pre-entered native target; candidate has six ambient native stores, nineteen fields in the shared carrier, and the same pre-entered target. Four sequential fresh-process pairs run baseline and candidate concurrently, swap interleaved CPU sides between pairs, and use 100,000 measured entries after 20,000 warmup entries per process. Allocation sampling uses a 512-byte interval and includes objects collected by minor and major GC. Timing is a separate unprofiled phase.
Field lookup cost increases by 1.80–4.22 ns in this controlled workload (oldest/middle/newest: 15.97/12.66/14.34 ns → 19.03/14.45/18.56 ns). Gateway latency remains a separate acceptance gate. The Map-storage row is benchmark-specific attribution: every intrinsic Map subtree belongs to the shared runner or its inlined task-owned callback, which creates no application Maps. Generic AsyncContextFrame-constructor attribution is unavailable because V8 inlines that boundary. Neither entry allocation nor Map-storage allocation is a whole-Gateway allocation result.
Gateway acceptance — passed under the October 23 ruling
Pairs 1 and 2 use baseline
6b1e5390daaffe41812c58810f4194f06eedb41dand candidate15da14e71f3dbbc8fcce1ea99fe38b380d453bca, including #181771. Pair 3 directly measures published head5cd8132a45055767ad97cbbbf2c359636f177fefagainst its current main merge-base6cc605dfe2044a2d2649dea02458e7982739d493. No product code, rebase, or push was needed for this final pair. Source hashes and per-side runtime package resolution were verified before launch. The older pairs and owner/census evidence remain explicitly labeled with their measured SHAs; all 31 earlier lane files are byte-identical at the published head, apart from the additional one-file lint configuration change. The intervening main delta repairs a UI test and exceptional stale-FTS update/backup handling outside this clean, warmed workload.Three valid concurrent 20-minute pairs used interleaved 16-CPU sides and fresh synthetic fixtures. Pairs 1/2 (raw labels
soak-3/soak-6) used slot A with baseline even/odd and candidate odd/even; pair 3 (soak-7) used slot B with baseline even/candidate odd, opposite pair 2. Pair 3 captured approximately 19:35:06–19:55:06 UTC. Every side completed 60 measured/63 total cohorts, 480 foreground turns, 480 tool calls and results, 60 subagent completions and persisted parent acknowledgments, 32 session resets, and 40 cron starts/finishes in the measurement window. Figures per turn include the entire mixed workload normalized by the 480 foreground turns.Allocation sample counts come from collected-object heap sampling at 512 KiB. Promotion counts are main-isolate V8 collections; total-GC counts are diagnostics events. All four core metrics improve in every pair; their baselines do not differ by more than 5×. Neither adverse threshold is reached, and none of these core metrics needs opposite-sign resolution. The magnitude varies substantially, especially promotion (−0.19%, −52.36%, −49.18%), so the average is not a promised production reduction.
Pair 1 matched all recorded model work. Pair 2 matched fixed work but had more dynamic work on the candidate: recap requests 722 → 755, utility streams 1,011 → 1,120, total streams 1,971 → 2,080. Pair 3 also matched fixed work, with smaller dynamic differences: recaps 747 → 753, utility streams 1,050 → 1,068, total streams 2,010 → 2,028. These counters reset each cohort and omit inter-cohort requests, so they do not establish complete equal dynamic work. This limits a strict equal-work interpretation of the allocation and promotion magnitude.
Pair 3 passes the amended maximum-pause criterion: 85.283 ms is below
max(50 ms, 2 × 98.900 ms) = 197.800 ms. Raw V8 maxima independently confirm 98.663 → 85.122 ms across 120/114 major collections. Together with the favorable all-three core means, this establishes PASS under the explicit October 23 ruling. No fourth pair was run.Pair 2's outlier is retained: 1,194.272 ms exceeds its
max(50 ms, 2 × 365.743 ms) = 731.486 mslimit. Independent V8 trace parsing confirms 1,193.830 ms versus 365.052 ms. The candidate event occurs between measured cohorts 54 and 55, approximately 1,089–1,100 seconds into the 1,200-second capture. The final forced memory collection happens after the capture. This is an in-scope observation, not profiler shutdown. Its trace reports 806.031 ms clearing and 346.081 ms evacuation, with live object bytes 1,027,309,056 → 793,209,264. The third pair does not explain or erase this event; attribution to the consolidation or host interference remains unproven.Event-loop maximum was 590.873 → 316.932 ms in pair 1 (56,366/56,398 samples), 406.061 → 1,294.991 ms in pair 2 (56,868/57,198), and 112.132 → 125.567 ms in pair 3 (56,856/57,305). Loop maximum is context under the rule; qualified loop p99 improves in every pair. None of the three valid pairs was guard-aborted. Pair 1 had one dirty-page warning; pair 2 had one production-loop warning; pair 3 had no guard warnings. The shared guard and its three-consecutive-failure abort rule were unchanged.
Read-only historical journal verification found production main-thread stalls at 19:14:50.405 UTC (476 ms, GC-dominated), 19:15:09.981 UTC (3,163 ms), and 19:19:37.830 UTC (1,926 ms). None falls within ±10 seconds of the candidate pause's conservative 19:16:57.542–19:17:09.335 UTC bracket. The last production stall is after the capture, retained only as surrounding host context. No one-second historical PSI series exists for pair 2; the roughly 8% cgroup memory-full avg60 reported when the additional pair was requested is later context, not pressure evidence at the old pause. Host interference is plausible but unproven; neither the journal nor the GC trace establishes the cause of the outlier.
Pair 3 host-interference audit
The external observer recorded 1,511 pressure samples across startup, capture, and the post-capture tail from
/sys/fs/cgroup/system.slice/memory.pressure,/proc/pressure/memory, and/proc/pressure/io. Maximum sample gap was 1,003.968 ms; maximum PSI-read duration was 0.410 ms. Every main-isolate major GC has a corresponding arrival record: 120 baseline and 114 candidate. Raw trace promotion totals independently match the result files, with worker isolates excluded.No pair-3 major pause exceeds the requested historical audit thresholds: baseline 356.097 ms and candidate 350.479 ms, each twice that side's pair-1 maximum. The table below therefore supplies supplemental context for each side's maximum. Timestamps are conservative external log-arrival bounds, not exact GC start times. PSI percentages are calculated from cumulative stall-microsecond deltas over actual surrounding samples, not from avg60 or interpolated values. Padding the approximately one-second arrival bounds by five seconds on each side yields enclosing windows of approximately 12 seconds / 13 samples.
The enclosing PSI windows are 19:46:39.812–19:46:51.812 UTC for baseline and 19:37:23.812–19:37:35.812 UTC for candidate. Separate before/after windows are about six seconds each; system-slice memory-full pressure is 48.068%/9.729% around the baseline maximum and 4.942%/2.002% around the candidate maximum. Thus pressure was observable during this pair, including around the baseline maximum, without a repeated excessive candidate pause. This does not establish why pair 2 spiked.
Read-only production journal extraction for 19:34:56–19:55:17 UTC records four main-thread stalls: 19:39:23.503 (403 ms), 19:41:44.892 (2,804 ms), 19:52:14.913 (349 ms), and 19:54:11.308 (311 ms). None falls within ±10 seconds of either side's maximum arrival bracket. The shared guard did not abort the pair. Raw PSI, cumulative-counter calculations, GC phase/heap records, old-space snapshots, and journal timestamps are retained with the measurement evidence.
RPC tails and sample qualification
Each cell shows baseline → candidate with samples B/C. Qualified p95 metrics with mixed signs are assessed using the three-pair absolute mean: agent +1.832 ms (under 1% of its mean baseline), sessions.diff −4.917 ms, and agent.wait −163.607 ms; none reaches an adverse threshold. Undersampled p99 values remain context.
One earlier swapped pair completed its workload but was discarded because a truncated V8 GC JSON record omitted the promoted-byte field. Its replacement reran both sides concurrently on fresh fixtures with the same placement. No missing promotion value was estimated. An earlier pre-#181771 soak was also superseded and supplies no acceptance evidence.
Workload: committed
scripts/perf/transcript-broadcast-measure.ts, source entry,memory-soak,--soak-rounds 60 --runs 8 --clients 8 --exact-clients 2 --chunks 100 --chunk-interval-ms 10 --round-interval-ms 20000 --reset-every-rounds 20 --warmup-ms 60000 --duration-ms 1200000 --memory-interval-ms 60000 --retained-profile-ms 0 --stress-tools --stress-subagents --mixed-rpc --list-interval-ms 2000 --allocations --diagnostics --trace-gc; each pair uses one shared start timestamp and poll seed, separate state directories/loopback ports, and the shared quiet-slot guard. Fixtures contain 5,000 sessions, 6,000 retained runs, 200 approvals, 100 cron entries, 12 projects, and 1 MiB synthetic transcript text (about 42 MB per fixture). Seescripts/perf/README.mdfor harness setup.CI and review
CI run 40000373920 passed on exact published head
5cd8132a45055767ad97cbbbf2c359636f177fef: 106 successful jobs, 24 skipped, including the requiredopenclaw/ci-gate. The live watcher completed successfully.Earlier CI found probe lint violations and a missing
SAFETY:comment marker; both are fixed. The probe's intentional native-method interception is covered by a one-file addition to the existing CJS lint exception; the rule remains enabled globally. Original-head startup, delivery, and UI failures had exact scheduled-main matches; upstream delivery and UI fixture repairs are included in the current base. An earlier synthetic cron child exited before PATCH, with no captured child stderr. Its root cause remains unproven; the exact case (claude-cli/channel-edit/trusted, disabled before 200) and the other eight cases passed in current job 120576113024. That pass is not presented as a demonstrated fix for the earlier failure.Independent review is clean, and the GitHub Codex review completed without findings on exact head
5cd8132a45055767ad97cbbbf2c359636f177fef. The follow-up reviews used independent subagent review (autoreview route unavailable); no provider configuration was changed. ClawSweeper's exact-head re-review completed October 23 at 19:32:43 UTC with no code findings; its remaining items were the final acceptance decision and lead-only merge. The completed three-pair evidence is now recorded here. This PR remains open and unmerged for the lead.After any lead-approved deployment, the intended production signal is less
AsyncContextFrameallocation under plugin invocation, with stable promotion and total GC per turn, event-loop p99, and maximum major-GC pause. Production profiling remains with the lead. Production-scale benefit and the cause of pair 2's long pause remain unproven.