Skip to content

fix(agents): subagent sweep skips context-engine cleanup after its request ends - #163331

Merged
steipete merged 5 commits into
mainfrom
steipete/subagent-sweeper-detached-cleanup
Oct 2, 2026
Merged

steipete merged 5 commits into
mainfrom
steipete/subagent-sweeper-detached-cleanup

Conversation

@steipete

@steipete steipete commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: context-engine cleanup for finished subagents is skipped when the periodic subagent sweep (or one of its cleanup tails) runs after the request that armed it has ended. The Gateway only logs context-engine onSubagentEnded failed (best-effort) with {"err":{}}, so the cause is invisible.

User Impact

Periodic session and collector cleanup completes after the initiating request closes, so context engines see onSubagentEnded for those children. When a best-effort cleanup still fails, the warning carries a redacted error, the cleanup reason, and the masked child session key.

Why This Change Was Made

The sweeper's tick and its asynchronous cleanup tails used independent root-work admission, which still inherited the initiating request's async scope. Once that scope closed, context-engine resolution failed before the hook ran. Both now use the existing detached-work admission, separately for the tick and for each tail, because a tail can also outlive its tick. Gateway drain accounting for cleanup descendants is preserved. The warning uses the existing buildSafeLifecycleErrorMeta convention instead of serializing the Error object to {}. The shared logging helpers live in a leaf module so context cleanup does not depend on lifecycle delivery and form an import cycle; all existing callers use that owner.

This is the same family as the Browser cleanup timer fix (#162312): periodic work must not run on a request's lifetime.

Evidence

  • Seen once in a live run of an isolated Gateway with a real model, after a recent main change routed unwatched child follow-ups through this sweep. A file-free probe reproduced the exact warning and {err:{}}.
  • New regressions in subagent-registry-context-cleanup.test.ts fail on main with Async work scope is closed. A tick-only fix passes the collector case but still fails the delayed tail, which is why both use detached admission. The tests cover hook execution, exactly-once disposal, descendant drain accounting, and warning redaction.
  • 264 tests pass across the context-cleanup, sweeper lifecycle, sweeper recovery, and normal lifecycle suites. Changed-file checks, lint, and oxfmt pass. Codex autoreview through P2 is scoped-clean.
  • Test cost: the context-cleanup file runs in 48.6 s wall with --maxWorkers=1, mostly runner/import overhead.

CI repair and validation

  • Initial exact-head CI found an import cycle introduced by the logging import. Moving the unchanged helpers to a leaf module removes it; pnpm check:madge-import-cycles reports zero cycles.

  • The expanded detached-work observer exposed an expected stale kill-owner rejection in the cancellation publication fixture. The original failure reproduced locally; the fixture now asserts that exact rejection and retains all successor-safety assertions. Publication and registered-sweeper lifecycle suites pass: 18 tests, 81.18 s wrapper wall.

  • Cleanup, normal lifecycle, requester-wake retry, and requester-wake pointer suites pass after the helper move: 226 tests, 193.74 s wrapper wall, including one-time worker preparation.

  • Changed-file checks pass, including production and test types, formatting, lint, dead exports, and runtime import cycles. Final isolated Codex autoreview is scoped-clean through P2.

  • Initial CI also found two missing-brace lint errors in the untouched src/gateway/server-worker-placement-session-target.test.ts. Main fixed these in 95a67da528c7; main was merged without conflicts to incorporate that repair. All 16 reviewed PR files remained byte-identical, preserving the focused-test and autoreview evidence. Current-head CI is required separately.

  • CI on daa6155d7444 exposed runAllTimersAsync() exhausting the recurring scheduler in the sessions-spawn lifecycle fixture. The local replay passed, so no local reproduction is claimed. The fixture now uses its existing deletion notification without draining every future timer; all five tests pass in 34.03 s wrapper wall, with matching typecheck/lint and a fresh scoped-clean Codex review. The failed CI file took 26.02 s.

  • The same CI merge ref incorporated main commit 40d284f9a6aa, whose duplicate trace property in src/agents/prepared-model-runtime.test-harness.ts fails lint and production/test types. This PR does not modify that file. Main fixed it in d81a2d8b7294. The later CI merge ref also inherited a process-custody import cycle, fixed on main in 0f470aecdc12. Both fixes were incorporated in one conflict-free main merge; all 17 reviewed PR files remained byte-identical.

Give periodic sweeps and asynchronous cleanup tails their own Gateway work admission so context-engine cleanup survives the initiating request and sweep tick. Log safe lifecycle error metadata with the cleanup reason and masked child session identity.

Cover closed callers, cleanup tails that outlive their ticks, disposal, descendant drain accounting, and warning serialization. Include detached admissions in the cleanup test observer so rejected work remains visible.
@clawsweeper

clawsweeper Bot commented Oct 2, 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: S labels Oct 2, 2026
@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 Oct 2, 2026
@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 2, 2026, 4:12 AM ET / 08:12 UTC (Revision 5).

ClawSweeper review

What this changes

The PR gives periodic subagent cleanup its own asynchronous lifetime, adds redacted failure details, and updates lifecycle tests and documentation.

Merge readiness

✅ Ready for maintainer review

The fix remains necessary on current main and in the latest release. No actionable introduced defect was found, and the reviewed files are unchanged since the previous review.

Likely related people: steipete (medium confidence), based on recent merged subagent lifecycle work.

Priority: P2
Reviewed head: 831707a4c5c4a119d8721679bee179359fc2c4d6

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, source-supported lifecycle repair with meaningful regression coverage and no blocking finding.
Proof confidence 🌊 off-meta tidepool Not applicable: Verified repository admin authorship exempts this internal cleanup repair from external-contributor proof. The supplied live observation establishes the pre-fix symptom; focused tests supplement the sweeper-to-context-engine lifecycle repair. No stored-data contract changes or material authorization changes require additional proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Verified repository admin authorship exempts this internal cleanup repair from external-contributor proof. The supplied live observation establishes the pre-fix symptom; focused tests supplement the sweeper-to-context-engine lifecycle repair. No stored-data contract changes or material authorization changes require additional proof.
Evidence reviewed 9 items Pinned introduction and review continuity: Read the complete introduced diff. Comparing the previous reviewed head with this head produces no changes in the reviewed registry, lifecycle-test, or documentation paths. Raw head and test-merge parent records match the supplied identities.
Current main still needs the repair: Current main uses independent root admission for both sweep ticks and cleanup tails. That admission retains the caller's asynchronous work scope rather than creating the fresh scope needed after the originating request closes.
Latest release retains the affected admission: GitHub identifies v2026.9.7 as the latest release. Its sweeper source also uses independent root admission for ticks and cleanup tails; the proposed detached admission is not present there.
Findings None None.
Security None None.

How this fits together

The subagent registry tracks child-agent completion and schedules session and resource cleanup. Its periodic sweeper calls context engines when children end, while Gateway admission tracks unfinished cleanup during shutdown.

flowchart TD
  A[Finished child agents] --> B[Periodic registry sweep]
  B --> C[Gateway work admission]
  C --> D[Independent cleanup lifetime]
  D --> E[Context engine ended hook]
  E --> F[Resource disposal]
  E --> G[Redacted failure warning]
  D --> H[Gateway drain accounting]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +11, Tests +168, Docs +4. Total +183 across 17 files.

View PR surface stats
Area Files Added Removed Net
Source 9 41 30 +11
Tests 7 182 14 +168
Docs 1 4 0 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 17 227 44 +183

Review metrics

Metric Value Why it matters
Production and regression growth production net +11 lines; tests and test support net +168 lines Production growth is justified by safe diagnostics and lifecycle ownership; most added code protects the two cleanup lifetimes.

Technical review

Best possible solution:

Keep periodic cleanup under the existing detached-work owner, with shared drain accounting and redacted lifecycle diagnostics.

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

Yes, from source: arm the sweeper inside an AsyncWorkScope, close that scope, and let a tick or delayed cleanup tail resolve a context engine. The new regressions encode this path; this reviewer did not execute them.

Is this the best way to solve the issue?

Yes. Using the existing detached admission for both lifetimes is a focused repair, and extracting unchanged logging helpers avoids a competing implementation or import cycle.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 0f470aecdc12.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This repairs periodic context-engine cleanup with a bounded lifecycle impact and no demonstrated urgent core outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Verified repository admin authorship exempts this internal cleanup repair from external-contributor proof. The supplied live observation establishes the pre-fix symptom; focused tests supplement the sweeper-to-context-engine lifecycle repair. No stored-data contract changes or material authorization changes require additional proof.

Evidence

What I checked:

  • Pinned introduction and review continuity: Read the complete introduced diff. Comparing the previous reviewed head with this head produces no changes in the reviewed registry, lifecycle-test, or documentation paths. Raw head and test-merge parent records match the supplied identities. (831707a4c5c4)
  • Current main still needs the repair: Current main uses independent root admission for both sweep ticks and cleanup tails. That admission retains the caller's asynchronous work scope rather than creating the fresh scope needed after the originating request closes. (src/agents/subagents/registry/subagent-registry-sweeper.ts:152, 0f470aecdc12)
  • Latest release retains the affected admission: GitHub identifies v2026.9.7 as the latest release. Its sweeper source also uses independent root admission for ticks and cleanup tails; the proposed detached admission is not present there. (src/agents/subagents/registry/subagent-registry-sweeper.ts:131, c074824a27c9)
  • Shared admission preserves fences and cleanup accounting: Detached admission creates a fresh AsyncWorkScope and retains its root until tracked descendants drain. Both admission variants use the same restart and suspension checks. This changes work lifetime without changing caller identities, method permissions, or stored contracts. (src/process/gateway-work-admission.ts:467, 831707a4c5c4)
  • Focused lifecycle regressions: The new table-driven cases exercise the real sweeper and context-cleanup owners with a closed caller scope, covering inline collector cleanup and a tail delayed beyond its tick. Assertions cover hook execution, exactly-once disposal, descendant root retention, and warning redaction. These are supplemental mocked tests; no tests were executed during this read-only review. (src/agents/subagents/registry/subagent-registry-context-cleanup.test.ts:64, 831707a4c5c4)
  • Logging owner and security inspection: The logging helpers move unchanged into a leaf module and all discovered callers use that owner. Error messages pass through the existing sensitive-text redactor; child session identifiers are masked. The diff adds no dependencies, workflows, permission settings, or executable downloads. (src/agents/subagents/registry/subagent-registry-lifecycle-log.ts:4, 831707a4c5c4)

Likely related people:

  • steipete: 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 (4 earlier review cycles)
  • reviewed 2026-10-02T06:56:54.191Z sha 7a6ef56 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-02T07:26:46.803Z sha 504ef51 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-02T07:35:57.791Z sha daa6155 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-02T07:59:48.655Z sha 6cd1ebd :: needs maintainer review before merge. :: none

Move unchanged lifecycle error and identifier formatting into a leaf module to break the context-cleanup import cycle. Update all callers and mocks together.

Assert the stale cancellation-owner cleanup rejection exposed by observing detached admissions while preserving successor-safety coverage. Verified 244 focused tests, changed-file checks, zero import cycles, and isolated review through P2.
@steipete steipete self-assigned this Oct 2, 2026
Use the existing lifecycle cleanup notification to observe deletion instead of running every future timer. Preserve all cleanup and Gateway-call assertions while avoiding the periodic scheduler loop reported by CI.

The initial local replay passed; the timer-loop failure is supported by the retained CI log. The repaired file passes all five tests, matching typecheck and lint, and isolated review through P2.
@steipete
steipete merged commit bd34489 into main Oct 2, 2026
129 of 131 checks passed
@steipete
steipete deleted the steipete/subagent-sweeper-detached-cleanup branch October 2, 2026 08:19
@steipete

steipete commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 3, 2026
…quest ends (openclaw#163331)

* fix(agents): detach sweeper cleanup from request scopes

Give periodic sweeps and asynchronous cleanup tails their own Gateway work admission so context-engine cleanup survives the initiating request and sweep tick. Log safe lifecycle error metadata with the cleanup reason and masked child session identity.

Cover closed callers, cleanup tails that outlive their ticks, disposal, descendant drain accounting, and warning serialization. Include detached admissions in the cleanup test observer so rejected work remains visible.

* fix(agents): isolate lifecycle logging from delivery

Move unchanged lifecycle error and identifier formatting into a leaf module to break the context-cleanup import cycle. Update all callers and mocks together.

Assert the stale cancellation-owner cleanup rejection exposed by observing detached admissions while preserving successor-safety coverage. Verified 244 focused tests, changed-file checks, zero import cycles, and isolated review through P2.

* test(agents): await spawn cleanup without draining recurring timers

Use the existing lifecycle cleanup notification to observe deletion instead of running every future timer. Preserve all cleanup and Gateway-call assertions while avoiding the periodic scheduler loop reported by CI.

The initial local replay passed; the timer-loop failure is supported by the retained CI log. The repaired file passes all five tests, matching typecheck and lint, and isolated review through P2.
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