Repository navigation
perf(agents): reduce subagent registry snapshot churn - #167684
Conversation
Reuse immutable topology at the registry lookup owner and select live rows from its indexes while keeping durable comparisons and authority checks current. Resolve only relevant retirement owners and order sweeps with stable priority buckets, preserving time-driven recovery and queued run identity.
|
🦞👀 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 changesThe subagent registry, which tracks delegated tasks, reuses task relationships and indexed reads to reduce allocation and CPU work as retained tasks accumulate. Review scores
ProductKind: Performance · Worth it: Yes Merge readiness✅ Ready for maintainer review This PR provides distinct, useful performance work that current main does not contain. Source review found no actionable correctness or security defect. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherThe Gateway uses the subagent registry to display delegated task status, protect descendants during cleanup, and recover interrupted work. These paths combine durable database records with current in-memory task ownership. flowchart TD
A[Committed task records] --> C[Registry membership index]
B[Live task publications] --> C
C --> D[Shared immutable relationships]
D --> E[Selected session and descendant reads]
A --> E
E --> F[Freshness and ownership checks]
F --> G[Task status and cleanup decisions]
B --> H[Stable sweep priority buckets]
H --> G
Technical reviewBest possible solution: Keep the optimization in the existing registry owners while preserving fresh durable comparisons, live replacement precedence, and time-dependent sweep ordering. Do we have a high-confidence way to reproduce the issue? Not applicable as a bug reproduction; current-main source confirms the repeated scans and copies, and the supplied paired benchmark exercises those operations with 2,500 retained runs. Is this the best way to solve the issue? Yes. The implementation extends the existing mutation-maintained lookup and preserves durable freshness and ownership checks without adding configuration, persistent formats, or competing owners. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against f8e594e461ef. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +30, Tests +179. Total +209 across 10 files. Added test files: 0. 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 Reviewed October 9, 2026, 3:37 AM ET / 07:37 UTC. |
|
Landed at The sole failed test job in CI run 37899483577 was Independent replay on clean main Registry proof passed: 1,361 sibling tests, final 53 state/read-snapshot tests, all 66 explicit recovery E2E tests, and the opt-in 5,000-session benchmark. Core types, lint, security checks, independent review, and ClawSweeper review passed. The PR records the separate inherited dead-export scan qualification and the synthetic performance measurements. CI was not rerun or relabeled green. |
Share immutable subagent topology through its mutation-maintained lookup, select scoped live rows by index, prune only changed runtime owners, and bucket sweep priorities once per pass. Preserve fresh durable comparisons, moved-row precedence, rekeyed custody, and time-driven sweep ordering. Synthetic 2,500-run proof reduces registry allocation by 99.0% for prepared capture, 96.0% for selected trees, 91.5% for sparse pruning, and 36.9% for full sweeps. Remote sibling and recovery tests passed. Landed with the inherited accepted-facts fixture CI failure independently reproduced on unchanged main; see PR evidence.
What Problem This Solves
Repeated subagent reads and maintenance allocate and inspect unrelated registry rows as the retained run count grows.
User Impact
This reduces registry allocation and CPU work without changing subagent results, cleanup priority, expiry, or recovery behavior. There are no schema, configuration, or update changes.
Why This Change Was Made
The registry's existing mutation-maintained lookup now owns a shared immutable topology snapshot. A row mutation or broad publication invalidates that snapshot; fresh durable comparison reads and live authority checks still run. Session-tree and prepared descendant reads select live rows through that same index, including replacements that moved out of the durable selection.
Retirement pruning resolves only relevant runtime owners, preserving queued-to-accepted identities. Sweeps partition runs into stable priority buckets instead of recomputing priority in a comparator. Priority is reevaluated each sweep because time and active execution can change without a registry mutation.
Current callers explain the repetition: the cron reaper consumes a prepared descendant read for each candidate and again in commit predicates; point session projections select requester trees; registry publications invoke retirement pruning; the sweeper orders rows each pass.
The source has moved on from the original allocation sample: compact snapshots and row immutability were already shared. This change removes the remaining topology copies, unrelated-row selection, and repeated priority work at their current owners.
Production LOC: +74/-44, net +30 (tests and support excluded). Retaining an immutable topology requires a frozen copy and mutation invalidation; indexed reads must include moved durable identities, and sparse pruning must preserve queued-to-accepted runtime identity. These contracts account for the growth.
Evidence
Synthetic benchmark at the registry owner: 2,500 retained runs, five warmups, 200 operations per read/prune probe and 100 sweeps. CPU was measured without profiling; a separate 512-byte heap sampler included objects collected by both minor and major GC. Registry attribution follows production registry stack frames.
At explicit synthetic rates of 1,200 notifications/minute, 600 reads/minute for each read probe, and one sweep/minute, sampled registry allocation falls from 2,308.2 → 196.0 MB/min for pruning, 480.1 → 19.2 MB/min for selected trees, 333.0 → 3.3 MB/min for prepared captures, and 7.30 → 4.60 MB/min for sweeping. These normalized rates are not measured production traffic. RSS includes the test harness/imports and is not a steady-state heap measurement.
Benchmark proof: AWS Crabbox
cbx_f610afb92771, runrun_2e74f1187e068e19ce001c1f8ff65405, c7a.4xlarge, Node 24.19.0, pnpm 12.5.1. Before/after ran sequentially in the same checkout with only the six changed production modules swapped to their pinned baseline, then restored. The benchmark command completed successfully in 114 seconds after sync. The sparse-pruning regression failed on the baseline for both ordinary and rekeyed owners, as intended.Focused proof on the Linux rig:
node scripts/run-vitest.mjsfor registry state, read snapshots, lifecycle, and sweeper recovery: 336 tests passed, 532.32 seconds including initial worker compilation. The overloaded rig's subsequent type-graph gate was interrupted, not counted as passing.AWS changed gate (
run_7e19e6e59ce2a06b869dab51850c53dd): production types and all 27 test type graphs passed, along with formatting and the preceding guards. The gate failed on pre-existing Knip exports:bindCliQuestionAnswerAuthority,prepareSessionEventTargetForHost,readSessionEntryCreationTransition, andRESTART_CONTINUATION_CONTEXT_PREFIX. Restoring the six production modules to base59309cc7777e07d52ca1be94bf8c25fd685919bcreproduced the identical production/full-tree findings inrun_01d71f07bc13f9dbe335a10867de31b4.That baseline run also failed the new read regressions as intended: live-tree reads enumerated the registry twice, and successive preparations copied identical topology. Candidate versions passed in the focused run. The final continuation (
run_2a1153b34a61095f50f3e7ab22902a0b) passed lint and every remaining schema/storage/import-cycle/webhook/pairing guard. The overall changed gate remains qualified by that baseline failure.Regular sibling suite:
pnpm test src/agents/subagents/registry/ --maxWorkers=1passed 1,361 tests across 75 files in 928.01 seconds; one opt-in 5,000-session benchmark was skipped by its default flag. Final source core types/lint and the 53 state/read-snapshot tests passed again after preserving direct Map iteration for full reads. Explicit E2E validation passed 65/66 cases; the failed startup-inspection recovery case is repaired by upstreama73ef559b23a, brought in through a patch-identical rebase. Post-rebase verification on Hetzner Crabboxcbx_f457a5c5ef5f, runrun_3b988fbe5f211e5c507e7beeb6dcb616, verified the exact head and all ten file hashes. Core types and changed-file lint passed; the same 53 tests passed in 44.08 seconds, all 66 explicit E2E cases passed (189.55 seconds of Vitest; 629.39 seconds including required runtime preparation), and the opt-in 5,000-session benchmark passed in 47.53 seconds. The full dead-export scan reproduced the same four inherited exports. Node 24.21.0, pnpm 12.7.0; command time 907.05 seconds.Final independent review: clean through P2, including the final iteration correction and test placement. The rebase preserved the exact patch ID. The benchmark's measured loops reuse the already-built topology; full reads retain their original direct Map iteration. Testbox
tbx_01m4fdrdkejny900cz2bmps7r2had no runner after 15 minutes and was stopped; the authorized fallback supplied the proof above.Limitations: this is synthetic boundary proof, not a new production heap profile. Sweeps still scan rows each pass because expiry and active-execution state can change without a row mutation; ordering is linear and stable rather than cached across time changes.
Exact-head CI: run 37899483577 completed with one failed Node shard and its downstream gate. All 18 failures are the unchanged
session-row-projection.accepted-facts.test.tsfixture expecting three custody releases after upstreama73ef559b23aintroduced an inner native-reader lease. The actual sequence is inner native → worker → continuation → outer native; the outer lifetime contract is preserved. Independent baseline replay: on the same Hetzner lease, runrun_062e9c69e3adcacd7beb95525d748ae7,pnpm test src/gateway/session-row-projection.accepted-facts.test.ts --maxWorkers=1on clean main83ce1401d658f4c723063a9900ba5af9bcbb5adbreproduced 18 failed / 4 passed, with the identical cleanup-order assertion, in 69.56 seconds. Git verified no tracked changes before and after the test. The failed fixture and five relevant dependencies are byte-identical between CI baselinef8e594e461efand the tested PR merge. Landing uses the authorized inherited-failure exception; CI is not claimed green. Both independent review and ClawSweeper found no actionable issues.