Skip to content

perf(agents): reduce subagent registry snapshot churn - #167684

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-subagent-registry-snapshot-churn-20260919
Oct 9, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-subagent-registry-snapshot-churn-20260919

Conversation

@steipete

@steipete steipete commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

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.

Operation CPU ms/op, before → after Sampled registry KiB/op, before → after Wall ms for timed batch, before → after Process RSS MiB, before → after
Sparse retirement notification 0.9651 → 0.2478 1878.4 → 159.5 154.26 → 27.24 711.0 → 578.5
Full retained-run sweep 5.8238 → 3.1041 7124.7 → 4492.6 561.17 → 269.66 773.0 → 697.9
Selected session tree 0.8620 → 0.2191 781.4 → 31.2 129.26 → 29.54 384.0 → 310.0
Prepared descendant capture 0.6359 → 0.0194 542.0 → 5.4 103.08 → 1.86 545.9 → 496.2

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, run run_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.mjs for 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, and RESTART_CONTINUATION_CONTEXT_PREFIX. Restoring the six production modules to base 59309cc7777e07d52ca1be94bf8c25fd685919bc reproduced the identical production/full-tree findings in run_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=1 passed 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 upstream a73ef559b23a, brought in through a patch-identical rebase. Post-rebase verification on Hetzner Crabbox cbx_f457a5c5ef5f, run run_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_01m4fdrdkejny900cz2bmps7r2 had 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.ts fixture expecting three custody releases after upstream a73ef559b23a introduced 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, run run_062e9c69e3adcacd7beb95525d748ae7, pnpm test src/gateway/session-row-projection.accepted-facts.test.ts --maxWorkers=1 on clean main 83ce1401d658f4c723063a9900ba5af9bcbb5adb reproduced 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 baseline f8e594e461ef and 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.

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.
@clawsweeper

clawsweeper Bot commented Oct 9, 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.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Oct 9, 2026
@steipete
steipete marked this pull request as ready for review October 9, 2026 07:31
@steipete
steipete enabled auto-merge (squash) October 9, 2026 07:34
@clawsweeper

clawsweeper Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

The subagent registry, which tracks delegated tasks, reuses task relationships and indexed reads to reduce allocation and CPU work as retained tasks accumulate.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is focused and source-correct, with useful component measurements and regression coverage, while proof of the changed behavior remains at an in-process boundary.
Proof confidence 🦐 gold shrimp (3/6) The supplied MEMBER metadata places this area-owner PR outside the external-contributor proof gate. Its synthetic Crabbox run exercises production registry reads, pruning, and sweeping and reports improved allocation and CPU; the broader E2E summary does not establish those gains through a shipped Gateway. The diff changes only process-local derived state and selection, with no stored-data contract change.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes
User problem: Large retained task registries make conversation status reads and background task maintenance consume avoidable CPU and memory allocation.
Reason: The bounded measurements demonstrate useful savings at existing owners, and the author has sustained prior ownership of those areas. The change preserves existing output and defaults.

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
Reviewed head: b85b60de9f929707f181409dad60f91aaac21b7d

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied E2E summary does not establish a before/after run through the shipped Gateway exercising the changed registry operations.
Agent review details

How this fits together

The 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
Loading

Technical review

Best 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

  • src/agents/subagents/registry/subagent-registry-lifecycle.ts keeps the original intent (3f761a8: Preserve runtime custody and callback fencing across immutable post-acknowledgment publications and collector rekeys.)
  • src/agents/subagents/registry/subagent-registry-read-cache.ts keeps the original intent (059ac34: Reuse committed compact facts while cold payload reads remain worker-owned and current live rows override durable facts.)
  • src/agents/subagents/registry/subagent-registry-read-snapshot.ts keeps the original intent (26dffe7: Move retention planning off the Gateway thread while protecting descendants and preserving fresh durable deletion comparisons.)
  • src/agents/subagents/registry/subagent-registry-state.ts keeps the original intent (2dbf888: Use lazy membership lookups to select complete requester trees while preserving live overlays, generation policy, and Map order.)
  • src/agents/subagents/registry/subagent-session-read-scope.ts keeps the original intent (f4c6545: Consolidate ordered run and session membership under the existing lookup and its publication lifecycle.)
  • src/agents/subagents/registry/subagent-registry-sweeper.ts keeps the original intent (7aaf302: Give restart recovery one ordered registry-owned lifecycle with generation-fenced cleanup and at-most-once dispatch.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +30, Tests +179. Total +209 across 10 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 6 74 44 +30
Tests 4 181 2 +179
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 10 255 46 +209

Review metrics

Metric Value Why it matters
Production versus tests Production +74/-44; tests and support +181/-2 The production growth is justified by shared immutable topology, indexed live selection, and preservation of rekeyed runtime identities.

Labels

Label changes:

  • add P2: This is a bounded performance improvement for large retained task registries, with no demonstrated 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 performance improvement for large retained task registries, with no demonstrated 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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

Reviewed October 9, 2026, 3:37 AM ET / 07:37 UTC.

@steipete
steipete merged commit 570c7bc into main Oct 9, 2026
206 of 209 checks passed
@steipete
steipete deleted the steipete/perf-micro-subagent-registry-snapshot-churn-20260919 branch October 9, 2026 08:07
@steipete

steipete commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Landed at 570c7bcf1b84e2f054ec885e4e8b98c01c93460f under the authorized inherited-CI exception, with PR head pinned to b85b60de9f929707f181409dad60f91aaac21b7d.

The sole failed test job in CI run 37899483577 was checks-node-changed-compact-large-19. All 18 failures were the shared cleanup-order assertion in session-row-projection.accepted-facts.test.ts: upstream a73ef559b23a added an inner native-reader lease, while the unchanged fixture still expects only the original three releases. The CI gate failed downstream; no jobs were cancelled.

Independent replay on clean main 83ce1401d658f4c723063a9900ba5af9bcbb5adb reproduced the identical 18 failed / 4 passed in 69.56 seconds: Hetzner Crabbox cbx_f457a5c5ef5f, run run_062e9c69e3adcacd7beb95525d748ae7, pnpm test src/gateway/session-row-projection.accepted-facts.test.ts --maxWorkers=1. No tracked changes before or after. The fixture and five relevant dependencies are byte-identical in the CI baseline and PR merge.

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.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 10, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant