Repository navigation
fix(agents): subagent sweep skips context-engine cleanup after its request ends - #163331
Conversation
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.
|
🦞👀 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. Reviewed October 2, 2026, 4:12 AM ET / 08:12 UTC (Revision 5). ClawSweeper reviewWhat this changesThe 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 Review scores
Verification
How this fits togetherThe 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]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +11, Tests +168, Docs +4. Total +183 across 17 files. View PR surface stats
Review metrics
Technical reviewBest 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. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (4 earlier review cycles)
|
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.
…eper-detached-cleanup
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.
…eper-detached-cleanup
|
Merged via squash.
|
…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.
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
onSubagentEndedfor 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
buildSafeLifecycleErrorMetaconvention instead of serializing theErrorobject 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
{err:{}}.subagent-registry-context-cleanup.test.tsfail on main withAsync 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.--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-cyclesreports 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 in95a67da528c7; 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
daa6155d7444exposedrunAllTimersAsync()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 duplicatetraceproperty insrc/agents/prepared-model-runtime.test-harness.tsfails lint and production/test types. This PR does not modify that file. Main fixed it ind81a2d8b7294. The later CI merge ref also inherited a process-custody import cycle, fixed on main in0f470aecdc12. Both fixes were incorporated in one conflict-free main merge; all 17 reviewed PR files remained byte-identical.