Skip to content

fix: clear stale subagent activity after restart cleanup - #146248

Merged
VACInc merged 3 commits into
mainfrom
openclaw/investigate-missing-subagents-display-bug
Sep 12, 2026
Merged

VACInc merged 3 commits into
mainfrom
openclaw/investigate-missing-subagents-display-bug

Conversation

@roboclaw-bot

@roboclaw-bot roboclaw-bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #146224

Additional instructions

Maintainers can edit this branch in the main repository.

What Problem This Solves

Fixes an issue where users viewing Control UI could see subagent activity remain running after restart cleanup removed its native run owner. The task kept its last tool name, such as process or sessions_yield, even though the retained chat session was not proof of active work.

Why This Change Was Made

Orphan handling now uses the existing completion lifecycle rather than deleting registry entries through a separate cleanup path. Known linked-task write failures keep completion retriable before cleanup, and Gateway maintenance reconciles tasks stranded by earlier pruning only when their live and durable owners are absent.

Actual live runs, queued/yielded work, replacement generations, restart recovery, and pending completion delivery retain ownership. No UI-only hiding, schema/config changes, or changes to execution timeouts.

User Impact

Orphaned work reaches an honest terminal state instead of appearing to run indefinitely. Existing stranded task records can also converge through normal Gateway maintenance. Genuine detached work stays visible after its parent turn ends.

Reported by @VACInc.

Evidence

  • The isolated retained-session/restart regression failed against the original implementation because its task never became terminal. The already-stranded-task regression failed with zero tasks reconciled instead of one. Both pass with the repair.
  • 303 focused tests passed across registry persistence, resume, lifecycle, helper, and task-maintenance suites. Coverage includes failed task persistence/retry, active-page removal, existing stranded records, queued/yielded/recovery/replacement owners, live-memory owners, unavailable reads, and an ownership change during recovery.
  • Core and core-test typechecks passed.
  • Fresh independent autoreview --mode local returned scoped-clean at the workflow default P0 threshold, including the split regression groups and test fixtures.
  • node scripts/check-changed.mjs passed, including formatting, core/core-test typechecks, changed-file lint, import-cycle and dead-export checks, and repository guards.

Focused command:

OPENCLAW_VITEST_MAX_WORKERS=2 node scripts/run-vitest.mjs \
  src/agents/subagents/registry/subagent-registry-helpers.test.ts \
  src/agents/subagents/registry/subagent-registry-lifecycle.test.ts \
  src/agents/subagents/registry/subagent-registry.persistence.test.ts \
  src/agents/subagents/registry/subagent-registry.persistence.resume.test.ts \
  src/tasks/task-registry.maintenance.issue-60299.test.ts

Live before/after acceptance — September 12, 2026

Both cases ran real built Gateway processes, native chat.send → sessions_spawn → child read, real SQLite persistence, cold process restarts, and Chromium UI. The model endpoint was a deterministic local HTTP/SSE fixture. Only the initial Gateway clock was shifted three hours behind, then returned to normal on restart, to exercise stale-run handling without a three-hour wait. No expected task status or UI fields were seeded and no Gateway requests were mocked.

Observation after restart Before: bec4d2172b8c Fixed: 4aa58e847dfc
Task state Still running completed through the original task ID
Native owner Removed; no execution resumes Recovery execution reaches terminal state
Active task count 1 0
Visible subagent activity rows 1 ghost row 0

This live case verifies that eligible work is recovered and genuinely completed, not merely hidden. The already-stranded-row maintenance repair remains covered by the isolated persistence regression.

The same driver and Node 24.18.1 ran in distinct rootless, network-none containers using image fee853fafa59550d162cef52bca02d907694b44ebf6ef9fb075bcc0c65d8dedb. Each case crossed container PID 50 → 143, with the original process confirmed gone; these are separate container PID namespaces, not host PIDs. Source/dependencies were read-only and host credentials were not forwarded. Gateway/provider processes were stopped, temporary SUT state removed, and the proof containers removed. The operator Gateway was not changed or deployed.

The captures below are the original inspected 1280×900 screenshots. The GitHub-hosted SVG assets embed the PNG bytes unchanged; Chromium verified pixel-for-pixel equivalence.

Before fix — orphaned task still shown as running

Before fix: native owner gone, task still running, one ghost subagent activity row

After fix — original task recovered and completed

After fix: original task completed, zero active tasks and no ghost subagent activity row

CI follow-through

  • Fixed the cancellation-publication fixture assumption exposed by immediate completion retries, without weakening its generation/cascade/successor assertions: 72 focused tests passed, full changed-scope checks passed, and fresh independent review was scoped-clean. The previously failing checks-node-compact-large-5 then passed in hosted run 34711854134.
  • That run exposed a separate main-branch QA selector mismatch introduced by fix(ui): show active work beyond the first history page #146207. The upstream correction fix(qa): select the renamed diagnostics browser test #146323 is now included through main 6b92ac80b5ab; 20 QA runner tests passed locally on the corrected baseline.
  • CI now targets 6615cff9bd2dae48deef9b23c14cb7f8c4f7b012. This is a main refresh with an identical repair patch (stable patch ID 118ac1d2e736d7fd7016c5ca534e456038863adb); the live proof above names the revisions actually executed.

Final CI result and remaining decision

  • CI run 34713988481, attempt 2, passed on exact head 6615cff9bd2dae48deef9b23c14cb7f8c4f7b012 at September 12, 2026, 19:55:25 UTC. The aggregate openclaw/ci-gate passed. One failed-job rerun cleared an ETXTBSY native-compiler launch failure in an unchanged fixture; no assertion or product code was weakened.
  • ClawSweeper revision 4 verified the live behavior and reported no blocking code findings. Its remaining gate is maintainer acceptance, still pending, of the bounded recovery proposal. This is not a claim that the decision has been accepted or that merge/deployment is authorized.

Worked on by


View the OpenClaw team session

Settle orphaned native runs through canonical completion before cleanup, keep task-write failures retriable, and reconcile previously stranded registry-backed tasks without hiding live work.

Closes #146224

Co-authored-by: VACInc <[email protected]>
@clawsweeper

clawsweeper Bot commented Sep 12, 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: XL maintainer Maintainer-authored PR labels Sep 12, 2026
@roboclaw-bot
roboclaw-bot marked this pull request as ready for review September 12, 2026 17:27
@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 12, 2026
@clawsweeper

clawsweeper Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 12, 2026, 4:39 PM ET / 20:39 UTC (Revision 6).

ClawSweeper review

What this changes

The PR settles orphaned subagent tasks before cleanup, retries failed task updates, and reconciles previously stranded activity through Gateway maintenance.

Merge readiness

⛔ Blocked before merge - 3 items remain

This repair remains necessary on current main, and no blocking code defect was found. The protected PR has sufficient real behavior evidence, but acceptance of its durable recovery behavior remains explicitly pending.

Priority: P2
Reviewed head: 6615cff9bd2dae48deef9b23c14cb7f8c4f7b012
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent owner-level repair with meaningful runtime evidence and no blocking code findings; pending design acceptance does not reduce patch quality.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Recorded before/after observations exercise real Gateway spawning, SQLite persistence, and cold restart: the fixed lifecycle completes the original task and clears ghost activity. The executed repair is unchanged at this head; already-stranded maintenance has supplemental persistence coverage, while linked screenshot inspection was blocked by the reviewer environment.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Recorded before/after observations exercise real Gateway spawning, SQLite persistence, and cold restart: the fixed lifecycle completes the original task and clears ghost activity. The executed repair is unchanged at this head; already-stranded maintenance has supplemental persistence coverage, while linked screenshot inspection was blocked by the reviewer environment.
Evidence reviewed 10 items Current main still permits phantom activity: Current main removes orphan registry entries without settling their tasks; task maintenance still accepts a retained child session as backing liveness.
Latest release retains direct orphan pruning: The v2026.9.4 source still deletes orphan registry rows directly. This repair is not established as shipped.
Task settlement gates cleanup: The finalizer propagates known active-task write failures and rejects a result that does not terminalize the linked task. Completion retries and restored-run replay retain that obligation before cleanup.
Findings None None.
Security None None.

How this fits together

The subagent registry tracks delegated work and records its outcomes in the persistent task ledger. Gateway maintenance reconciles abandoned work, and Control UI displays the resulting task activity.

flowchart TD
  A[Gateway restart] --> B[Restore subagent runs]
  B --> C{Surviving owner?}
  C -->|Yes| D[Preserve or recover work]
  C -->|No| E[Complete orphaned work]
  F[Stranded task maintenance] --> G[Persistent task ledger]
  E --> G
  G --> H[Control UI activity]
Loading

Decision needed

Question Recommendation
Accept automatic terminal settlement of ownerless subagent tasks, including existing stranded records becoming subject to normal retention? Accept bounded recovery: Accept the documented owner checks, retry behavior, and existing retention consequences.

Why: The repository requires acceptance of material durable recovery changes, and the linked proposal explicitly remains pending.

Before merge

  • Resolve merge risk (P1) - Previously stranded tasks will automatically become terminal and eligible for existing retention pruning; reverting the code cannot restore those updates or subsequently pruned records.
  • Complete next step (P2) - Record maintainer acceptance or a requested narrowing of the bounded recovery proposal at fix: clear stale subagent activity after restart cleanup #146248 (comment).
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
Agent review details

Security

None.

PR surface

Source -7, Tests +153, Docs +2, Other 0. Total +148 across 21 files.

View PR surface stats
Area Files Added Removed Net
Source 9 186 193 -7
Tests 9 597 444 +153
Docs 2 5 3 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 21 789 641 +148

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #146224
Summary: This PR is the explicit implementation candidate for the orphan-cleanup activity report.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Accept the documented recovery contract (recommended)
    Record acceptance of terminal settlement and its retention consequences before landing.
  2. Pause stranded-record reconciliation
    Narrow the patch if maintainers do not accept automatic changes to previously stranded task records.

Technical review

Best possible solution:

Keep completion and maintenance as the canonical owners of truthful task activity, with explicit acceptance of bounded automatic recovery and its retention consequences.

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

Yes: current-main source still permits orphan deletion without task settlement and accepts retained sessions as liveness. The recorded before/after Gateway run corroborates this mechanism; this review did not execute target code.

Is this the best way to solve the issue?

Yes: repairing canonical completion and maintenance avoids a competing UI interpretation of liveness and preserves existing recovery owners.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: The repair addresses misleading persistent subagent activity after restart with bounded task-lifecycle impact.
  • merge-risk: 🚨 session-state: Merging changes existing stranded records into terminal states subject to retention that code rollback cannot reverse.
  • 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. Sufficient (live_output): Recorded before/after observations exercise real Gateway spawning, SQLite persistence, and cold restart: the fixed lifecycle completes the original task and clears ghost activity. The executed repair is unchanged at this head; already-stranded maintenance has supplemental persistence coverage, while linked screenshot inspection was blocked by the reviewer environment.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded before/after observations exercise real Gateway spawning, SQLite persistence, and cold restart: the fixed lifecycle completes the original task and clears ghost activity. The executed repair is unchanged at this head; already-stranded maintenance has supplemental persistence coverage, while linked screenshot inspection was blocked by the reviewer environment.

Evidence

What I checked:

Likely related people:

  • VACInc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • fuller-stack-dev: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Peter Steinberger: 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 (5 earlier review cycles)
  • reviewed 2026-09-12T17:34:01.329Z sha e50d88b :: needs maintainer review before merge. :: none
  • reviewed 2026-09-12T18:45:51.212Z sha 4aa58e8 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-12T19:29:21.338Z sha 6615cff :: blocked before merge. :: none
  • reviewed 2026-09-12T19:47:32.206Z sha 6615cff :: blocked before merge. :: none
  • reviewed 2026-09-12T20:06:33.095Z sha 6615cff :: blocked before merge. :: none

roboclaw-bot and others added 2 commits September 12, 2026 18:38
Keep the exact failed-task write fault active until cancellation publishes its result, then release it without weakening generation, cascade, or successor assertions.

Co-authored-by: VACInc <[email protected]>
Include the upstream diagnostics scenario selector correction from #146323. Preserve the existing subagent repair without changing its implementation.

Co-authored-by: VACInc <[email protected]>
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. label Sep 12, 2026
@roboclaw-bot

Copy link
Copy Markdown
Collaborator Author

Added source-bound live before/after acceptance to the PR body: real Gateway processes, native spawn/read, SQLite persistence, cold restarts, and Chromium. Before the fix, the native owner disappears while the task/UI remains running; with the fix, recovery completes the original task and the ghost row disappears. Synthetic local model endpoint and accelerated stale-time window are explicitly documented.

The CI fixture repair is in place, and head 6615cff9bd2dae48deef9b23c14cb7f8c4f7b012 refreshes main to include upstream QA-selector fix #146323 without changing the repair patch. Exact-head CI verification is tracked separately.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@roboclaw-bot

Copy link
Copy Markdown
Collaborator Author

Proposed bounded recovery design — acceptance pending

ClawSweeper’s current storage-review question is a maintainer decision, not a code finding. This comment proposes the scope; it does not assert that a human has accepted it. The implementation remains unmerged and undeployed.

  • Owners: the existing native subagent completion lifecycle settles its linked canonical task before cleanup; the existing task-maintenance owner handles previously stranded registry-backed tasks. Control UI only consumes task state.
  • Behavior: automatically settle orphaned runs through normal completion. After the existing grace period, mark an already-stranded native task lost only when the authoritative Gateway finds neither live execution context nor a matching current/durable subagent owner. Failed ownership reads and non-authoritative processes retain the task. Active, queued, yielded, recovering, replacement, collector, and required-delivery ownership remains protected.
  • Persistence: no new schema, table, version, configuration, or parallel state store. Terminal task state remains canonical; the UI does not get a second interpretation of liveness. Cleanup/retention follows existing modes, including normal keep-mode retention rather than prematurely deleting an unresolved owner. Known failed task writes remain retriable before cleanup.
  • Alternatives: a UI-only filter leaves incorrect canonical state and can hide valid detached work. The proposal instead reuses the existing completion and maintenance owners, without a new cleanup state machine.
  • Concurrency/cost: preserve exact run/generation fences and write-before-publication ordering. Ownership checks reuse the existing scoped child-session index and run only for relevant stale native tasks. No new retention interval or database-wide scan is introduced.
  • Rollback: reverting the repair stops future automatic reconciliation; it does not automatically undo terminal task updates already persisted. Normal task/history retention remains in effect; any restoration of already-updated state would require operator review/backup rather than blindly resurrecting work.
  • Validation: before/after real Gateway/SQLite/Chromium acceptance is in the PR body; original process death and cold restart were observed. The model endpoint and clock acceleration are explicit fixtures. The original regression suite, the 72-case cancellation/recovery follow-through, and the corrected 20-case QA runner passed locally. CI on the refreshed head remains separate. No operator Gateway state was mutated.

Decision requested from @VACInc: accept this bounded automatic-recovery behavior for PR #146248? This is design acceptance only, not permission to merge or deploy.

Reference: docs/reference/database-schemas/storage-changes.md, “Review checkpoint for material changes.”

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Sep 12, 2026
@VACInc VACInc self-assigned this Sep 12, 2026
@VACInc
VACInc merged commit 1319119 into main Sep 12, 2026
332 of 334 checks passed
@VACInc
VACInc deleted the openclaw/investigate-missing-subagents-display-bug branch September 12, 2026 20:56
This was referenced Sep 12, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 13, 2026
…6248)

* fix: clear stale subagent activity after restart cleanup

Settle orphaned native runs through canonical completion before cleanup, keep task-write failures retriable, and reconcile previously stranded registry-backed tasks without hiding live work.

Closes openclaw#146224

Co-authored-by: VACInc <[email protected]>

* test: retain the cancellation race during task settlement retries

Keep the exact failed-task write fault active until cancellation publishes its result, then release it without weakening generation, cascade, or successor assertions.

Co-authored-by: VACInc <[email protected]>

---------

Co-authored-by: roboclaw-bot <[email protected]>
Co-authored-by: VACInc <[email protected]>
etzelm added a commit to etzelm/openclaw that referenced this pull request Sep 13, 2026
…nts_wait forever

- Reject sessions_yield from a Swarm collector turn before any claim source
  runs, so no durable yield intent is recorded against a child row, and return
  a diagnostic telling the model to finish the turn so its collected result is
  recorded for whoever waits on the run. This admission layer only sees turns
  whose tool factory is given collector context.
- Settle a yielded terminal for a run with collect === true as an ordinary ok
  terminal on both the lifecycle-event path and the agent.wait observer path.
  A collector is read by an explicit wait and never receives a requester
  continuation, so a parked collector row has no wake source at all and its
  waiter blocks until the operator gives up.
- Keep a result the collector already captured through structured_output; a
  collector that captured nothing keeps the existing "structured_output was not
  called" diagnostic instead of having a valid result overwritten.
- Settle as ok rather than a cancellation: a yielded terminal can also look
  aborted, and any other settlement would reintroduce the false cancellation
  notice from openclaw#92448.
- Leave every non-collector yielded terminal on the shipped
  markSubagentRunPausedAfterYield path. The documented sub-agent
  self-yield-for-external-work contract preserved in openclaw#125850 is unchanged;
  openclaw#141474 carries clawsweeper:needs-product-decision for that arm.
- Write no pauseReason on the settle path, so downstream
  pauseReason === "sessions_yield" guards, openclaw#146248 retention, and the paused-run
  adoption added by openclaw#146667 are untouched: they select paused rows, which a
  settled collector never becomes.
- Document the collector rule in the sessions_yield and Swarm docs, qualified to
  demonstrated behavior rather than universal tool hiding: the tool is withheld
  where collector context reaches the tool factory, such as the embedded runner;
  a CLI-backed collector turn through the Gateway tool resolver can still be
  offered it and receive a successful yielded result; and in every case the
  terminal settle is what resolves the waiter.
- Repoint the yielded-continuation reset case added by openclaw#146565 at an ordinary
  announcing sub-agent fixture, with every assertion unchanged, because a
  yielded collector is now settled at its terminal and is no longer a
  continuation to preserve. Add a sibling case pinning that contract: a yielded
  collector completes with no pauseReason and a frozen collectorCompletion, and
  sessions.reset then revokes its cleanup as a completed run.
- Await the durable cleanup mark of the settled collector in that reset case,
  not the residual-roots deadline. Its cleanup: "delete" work is dispatched
  detached and takes 0.5 s to 3.9 s locally depending on whether the SQLite
  reclamation worker starts cold, so the one-second vi.waitFor inside
  settleSubagentRegistryPersistenceWork could observe a live registry root under
  CI load. The guard and every assertion are unchanged.

Related: openclaw#141474
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 maintainer Maintainer-authored PR merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL 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.

[Bug]: Subagent activity remains running after orphan cleanup

2 participants