Skip to content

perf(agents): avoid repeated retained subagent recovery reads - #159082

Merged
steipete merged 3 commits into
mainfrom
steipete/perf-micro-subagent-sweeper-recovery-reload-per-tick-20260919
Sep 26, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/perf-micro-subagent-sweeper-recovery-reload-per-tick-20260919

Conversation

@steipete

@steipete steipete commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

The subagent sweeper repeatedly reads and parses retained child sessions while a live session owner prevents restart recovery. Deferred rows also reschedule the entire sweep every second, repeating unrelated work.

User Impact

Unchanged live-owned rows skip session reads. Unresolved recovery retries independently at 1, 2, 4, 8…60 seconds; published session changes and admission release request a sweep within one second. Normal interruption, cancellation, and superseded-row cleanup remain with their existing owners. No new configuration, schema, or retention policy.

Why This Change Was Made

The coordinator retains small ownership predicates and registry/Gateway facts, rechecks live authority before every skip, and invalidates on owner publications or admission release. It deliberately does not cache arbitrary session classifications: notifications cannot establish freshness after a foreign SQLite commit. Unowned rows and saved requester wakes still receive fresh keyed reads.

Initial reads use the existing worker metadata projection, omitting saved prompt snapshots. Existing synchronous side-effect fencing stays authoritative. Pause, steer, kill, and queued eligibility now recheck across the awaited read. Superseded rows fall through to ordinary sweeper cleanup. Net production growth: 123 lines.

Evidence

The fixture uses the real sweeper/recovery composition, 30 retained running rows with live session owners, and entries larger than 1 MiB. Mocked storage counts keyed reads and actual JSON parsing; this is not a SQLite throughput benchmark.

Five sweep ticks Before After, final head
Reads by tick 60, 60, 60, 60, 60 30, 0, 0, 0, 0
Total parsed bytes 314,620,800 31,462,080
Sweep time 150.54 ms 17.88 ms
Whole test-process RSS 1,340,563,456 bytes 1,277,788,160 bytes

That is 90% less parsing, 88.1% less sweep time, and zero reads on unchanged ticks. RSS includes the test harness and is not an isolated retained-heap measurement. The mock still parses the large entry on its first read, so the numbers do not credit the worker projection for omitting prompt payloads.

Production Testbox proof: 130 tests passed, including all 26 faithful SQLite/restart integration cases, on provider blacksmith-testbox, profile openclaw-check, lease tbx_01m3ff8jsfj6gp32j91d441d82, head f2f8b8fa7bf6d027a1ec0b0db30101eea396e0a2.

node scripts/run-vitest.mjs \
  src/agents/subagents/registry/subagent-orphan-recovery.restart-integration.test.ts \
  src/agents/subagents/registry/subagent-registry-restart-recovery.test.ts \
  src/agents/subagents/registry/subagent-registry-sweeper-recovery.test.ts \
  src/agents/subagents/registry/subagent-registry-sweeper-lifecycle.test.ts \
  src/config/sessions/session-entry-readonly.worker.test.ts --maxWorkers=1

Wall: 77.66 s for the wrapper, 82.02 s remote command. Test process costs: restart recovery 9.21 s / 53 tests; sweeper recovery plus worker-reader sibling 15.74 s / 46 tests; real restart integration plus sweeper lifecycle 36.97 s / 31 tests. The existing integration suite exercises persistence and restart ownership and accounts for most test execution time.

The read regression fails on the baseline. Separate baseline controls also fail for backoff and all four in-read ownership changes. Independent Codex review found no actionable P0–P2 issues, including the subsequent CI repair.

Current-head CI: https://github.com/openclaw/openclaw/actions/runs/36264969848 — success, head 7bfabdb874ec994d0639c2cf7596acc3426284fe; final openclaw/ci-gate passed. Both previously failing shards passed: compact-large-2 job wall 368 s and compact-small-2 job wall 461 s, including setup.

CI also exposed four stale mocks in subagent-registry.test.ts: the new worker reader bypassed its in-memory session fixture. Both APIs now share the existing mutable fixture and preserve read failures and caller-current checks. All 186 registry seam tests pass. Across eight related fixture files, 338 tests passed and the two extra E2E failures described below remained. The remote E2E runtime build passed in 7m 55.6s; test-process wall times were 15.58s (186 tests), 14.13s (91 tests), 5.38s (5 tests), and 42.39s (58 E2E tests, two pre-existing failures). Combined with the separate 130-test proof, this is 468 passing tests. No production code changed in the fixture follow-up.

Initial CI caught a genuine regression: an early guard skipped ordinary cleanup of a superseded predecessor. The guard now discards its cache and returns to ordinary cleanup; the original failing integration case passes on Testbox. That initial impacted agent-support CI shard ran 69 files / 1,624 cases in 138.95 s before reporting this failure.

Remote validation history and limits

All heavy local-invoked validation used the installed Crabbox CLI and Blacksmith Testbox. Each lease received one successful pnpm install --frozen-lockfile; leases were replaced sequentially, never used for concurrent commands. All five leases are stopped.

Lease Commands and observed results
tbx_01m3fb9z8hrhntpafq3hae48ra Baseline run-vitest restart-recovery file: expected read-regression failure, 46 existing tests passed. Patched recovery/sweeper/lifecycle files: 88 passed. Two check-changed attempts timed out during native file sync before checks ran.
tbx_01m3fc2drngkc8dhqykbq7dm5w Baseline backoff control failed at the intended retry-count assertion. The combined control wrapper stopped before its second shard; a separate mutation-fence control then produced all four expected failures. Subsequent check-changed sync timed out.
tbx_01m3fcmm8aqgvvn62r2s2vwbpq Default check-changed used stale runner refs and selected unrelated line-cap growth. Pinning base dd3e8a4af4d8fb8267c601cf7eacbdbf3bec2af9 exposed two TypeScript narrowing issues, both fixed. Core types and structural checks passed; a later sync timed out.
tbx_01m3fdrk6x9380pdwh50w2csxk Four focused files: 104 passed. The pinned gate initially lacked its base Git object; after fetching it, core types and agent/Gateway test-type graphs passed. The run was stopped when CI required the superseded-row repair and a new head.
tbx_01m3ff8jsfj6gp32j91d441d82 Five-file production proof: 130 passed. Expanded eight-file fixture proof: 338 passed, two requester-wake E2E failures. Restoring all five changed recovery/sweeper production files from baseline dd3e8a4af4d8 reproduced exactly the same two failures; the candidate source was restored afterward. Both E2E runtime builds succeeded. Lease stopped.

Known pre-existing E2E failures: subagent-registry.requester-wake.e2e.test.ts still expects a yielded alpha batch to wait for unrelated beta, and a stale unrelated sibling to consume a frozen batch’s deferral budget. Both failures reproduce with the lane’s baseline recovery implementation. They conflict with the intentionally independent frozen-batch behavior in #158642; neither failing assertion reaches the sweeper. These untouched expectations need separate maintenance.

There is no completed standalone check-changed run on the final head; the exact-head CI run supplies the remaining broad type/lint/guard/docs gates. No live Gateway was changed or profiled. Unpublished foreign-store changes are discovered on the next bounded retry; this is intentionally not a general revision cache for every retained row.

Recheck live session ownership before rereading retained child metadata, keep unresolved retries on per-row bounded backoff, and wake recovery on owner publications or admission release. Move initial metadata reads to the session worker and fence pause, steer, kill, and queue changes across awaited reads.
@clawsweeper

clawsweeper Bot commented Sep 26, 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 docs Improvements or additions to documentation agents Agent runtime and tooling size: M labels Sep 26, 2026
@steipete
steipete marked this pull request as ready for review September 26, 2026 18:01
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 26, 2026
@clawsweeper

clawsweeper Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 26, 2026, 3:18 PM ET / 19:18 UTC (Revision 2).

ClawSweeper review

What this changes

The branch makes subagent restart recovery skip repeated session reads while a live owner remains, use worker metadata reads, and retry unresolved rows with bounded backoff, with accompanying tests and operations documentation.

Merge readiness

✅ Ready for maintainer review

Keep open: current main still reads retained child sessions on each sweep, so this branch has distinct performance value. The follow-up commit repairs the superseded-row cleanup regression, and this review found no remaining definite patch defect.

Priority: P2
Reviewed head: 7bfabdb874ec994d0639c2cf7596acc3426284fe

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Focused before/after measurements, restart coverage, and a corrected integration regression support a sound internal performance patch.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: The repository state identifies a MEMBER-authored internal performance PR, so the external-contributor proof gate does not apply. The captured Testbox report supplies supplemental sweeper measurements and SQLite restart coverage, though no live Gateway profile; the patch changes no stored-data contract.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The repository state identifies a MEMBER-authored internal performance PR, so the external-contributor proof gate does not apply. The captured Testbox report supplies supplemental sweeper measurements and SQLite restart coverage, though no live Gateway profile; the patch changes no stored-data contract.
Evidence reviewed 7 items Current-main behavior: The coordinator on fetched main calls recovery for each eligible sweep and schedules every deferred result after one second; it has no retained-owner skip or per-row backoff.
Introduced recovery guard: The branch stores small row facts, rechecks live retained ownership on each skip, invalidates on session publications, and backs deferred rows off up to one minute.
Read and settlement boundary: The initial session lookup uses the existing worker read contract; recovery checks current ownership after the await and retains the synchronous session-effect guard before settlement.
Findings None None.
Security None None.

How this fits together

The subagent registry tracks child runs and sweeps them after interruptions or Gateway restarts. Recovery combines registry ownership and session metadata to decide whether to wait, settle a run, or leave cleanup to the ordinary sweeper.

flowchart LR
 A[Retained child runs] --> B[Registry sweep]
 C[Live session owners] --> D[Recovery coordinator]
 B --> D
 D --> E{Owner active?}
 E -->|Yes| F[Skip or retry]
 E -->|No| G[Read session metadata]
 G --> H[Recover or clean up]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +123, Tests +197, Docs +7. Total +327 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 5 143 20 +123
Tests 5 215 18 +197
Docs 1 7 0 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 365 38 +327

Review metrics

Metric Value Why it matters
Production and test growth production +123 net lines; tests and support +197 net lines The PR explains the production growth through owner invalidation and retry scheduling, while the added coverage exercises those transitions.

Technical review

Best possible solution:

Keep recovery owned by the registry, with fresh authority checks before settlement and bounded retries for rows that cannot yet be reconciled.

Do we have a high-confidence way to reproduce the issue?

Yes, current-main source gives a high-confidence path: repeat sweeps of retained live-owned child rows call recovery and read session metadata each time. I did not execute that path in this read-only review.

Is this the best way to solve the issue?

Yes, the change stays with the registry recovery owner, uses the existing worker reader, and preserves live checks before settlement. The reported Testbox results support the scoped performance claim.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against cafb3a4d1ca2.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded agent recovery performance improvement with no demonstrated urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The repository state identifies a MEMBER-authored internal performance PR, so the external-contributor proof gate does not apply. The captured Testbox report supplies supplemental sweeper measurements and SQLite restart coverage, though no live Gateway profile; the patch changes no stored-data contract.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Jason (Json): Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Ayaan Zaidi: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-26T18:08:21.586Z sha d7fb942 :: needs maintainer review before merge. :: none

Serve the worker reader from the same mutable in-memory session fixture as the synchronous accessor. Preserve read failures and caller authority checks without changing registry assertions.
@steipete
steipete merged commit 5899667 into main Sep 26, 2026
213 checks passed
@steipete
steipete deleted the steipete/perf-micro-subagent-sweeper-recovery-reload-per-tick-20260919 branch September 26, 2026 19:30
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 27, 2026
…aw#159082)

* perf(agents): avoid repeated retained subagent recovery reads

Recheck live session ownership before rereading retained child metadata, keep unresolved retries on per-row bounded backoff, and wake recovery on owner publications or admission release. Move initial metadata reads to the session worker and fence pause, steer, kill, and queue changes across awaited reads.

* fix(agents): preserve superseded subagent orphan cleanup

* test(agents): align registry fixtures with worker session reads

Serve the worker reader from the same mutable in-memory session fixture as the synchronous accessor. Preserve read failures and caller authority checks without changing registry assertions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant