Skip to content

fix: plugin reloads lose tool results and strand subagent settlement - #157339

Merged
obviyus merged 13 commits into
mainfrom
fix/plugin-reload-inflight-turns
Sep 25, 2026
Merged

obviyus merged 13 commits into
mainfrom
fix/plugin-reload-inflight-turns

Conversation

@obviyus

@obviyus obviyus commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Fixes: removing or disabling a plugin while an agent turn is running loses that turn's tool result, and a background subagent started before the change never settles. Its completion retries about once per second until the Gateway restarts.

User Impact

User impact: owners can uninstall or disable a plugin mid-conversation, even through the agent's own plugins tool. The running turn keeps its tool output, and subagents started before the change deliver their results and finish.

Why This Change Was Made

  • Admitting Gateway: each Gateway registry owner now links every registry it publishes to itself. A turn's derived agent-runtime registry (src/agents/runtime-plugins.ts) is linked to the Gateway whose request admitted the turn. A registry claimed by two owners, or built by a published build without the link, has no owner, and recovery stays strict for it.
  • Tool results: a run resolves its tool-result middleware once. When the plugin that owns a middleware was removed mid-run, calling it threw PluginInstanceUnavailableError, and the harness replaced the whole tool result with "Tool output unavailable due to post-processing error." The runner now drops a handler only when that handler's own plugin instance is retired and the plugin is gone from the current registry of the Gateway that published it. It checks before choosing a path, so a run whose only middleware was removed returns the untouched result exactly like the no-middleware path. It checks again right before each call. A skipped plugin never runs. Every error a handler throws still fails closed, a replaced plugin fails closed, and a handler whose Gateway is closing or unlinked fails closed.
  • Detached task settlement: a child run, its lifecycle events and its retry timers keep the parent turn's plugin-generation scope. After a plugin reload that scope's registry is retired, and captureDetachedTaskRuntimeOwner refused every core settlement ("Detached task runtime owner changed before task settlement."); each retry captured the same stale scope, so it looped. Lookup and settlement of rows that already exist now resolve through the admitting Gateway's current registry, only while that Gateway is open and core owns tasks in both generations. The owner check runs again right before the terminal write. Task creation stays bound to its admitting scope, so a retired generation cannot admit new task work. A closing admitting Gateway, a different live Gateway, or a successor that registers a plugin task runtime is refused with DetachedTaskRuntimeOwnerRetiredError before any task write.

Evidence

Production trace (before): an owner asked the agent to uninstall a plugin that owned tool-result middleware. The plugins tool succeeded and two hot reloads followed. About 1 s later the log showed tool result middleware failed for tool_call, and the model received "Tool output unavailable due to post-processing error." A subagent started before the reload then logged DetachedTaskRuntimeOwnerRetiredError about 2,480 times over about 50 minutes, until the Gateway restarted.

Live Telegram matrix, built dist of c6a7bf3 vs base b5346d6. Each run uses a real Gateway, the Telegram test server with a real QA user, and a mock provider. The DM or forum-topic turn runs exec, spawns a subagent (about 20 s of work), then runs a 12 s exec. During that exec, the scenario changes a test plugin that owns tool-result middleware by editing config in place, so the Gateway hot-reloads. "Owner-retired lines" counts DetachedTaskRuntimeOwnerRetiredError and "settlement deferred" log lines until Gateway shutdown (about 2 minutes later). The task state is read with openclaw tasks list --json at 115 s.

# Case base b5346d6 this PR c6a7bf3
1 DM, plugin uninstalled mid-turn (disable, then remove: two hot reloads, as in production) Reply TOOL2_LOST(Tool output unavailable due to post-processing error.); 512 owner-retired + 252 deferred lines; child task stays running Reply TOOL2_OK; child task succeeded; 1 owner-retired line (one retried lookup), then no loop
2 Same, in a forum topic Same loss and loop (512 + 252); child running TOOL2_OK and the child's result posted in the topic; child succeeded/delivered; 1 owner-retired line
3 DM, plugin only disabled mid-turn (one hot reload) not run TOOL2_OK; child succeeded/delivered; 1 owner-retired line
4 DM, new task work after the reload: the same turn waits, then sessions_sends a follow-up to its finished child Tool results lost (3 middleware failures, including the sessions_send result); follow-up task created TOOL2_OK and the sessions_send result intact; the follow-up task (cli, succeeded) is admitted on the live generation; child succeeded/delivered; no owner-retired line
5 DM, middleware plugin replaced (reinstalled) mid-turn Gateway refuses: still has active retained work; … replacement not applied. User sees TOOL2_OK and the child result Same refusal; TOOL2_OK; child succeeded
6 DM happy path, no plugin change not run HAPPY_DONE TOOL_OK, one reply

Notes:

  • Case 4: a turn's new task work goes through Gateway admission, which uses the live generation, so no live flow reaches task creation inside a retired scope. The unit test below proves that such creation is rejected before any write.
  • Case 5: the Gateway will not replace a plugin whose work is still held, so the fail-closed path for a stale handler with a live replacement cannot be reached from a turn. The loader test below covers it.
  • Cases 1 and 5 (DM): the child's completion message was still pending at the 115 s read. Its direct send failed with Plugin telegram was reloaded or disabled; use its current tools. This is the separately tracked Telegram send issue [Bug]: Telegram progress disappears without a final reply when the active plugin instance is invalidated #155788, which this PR does not change.

Upgrade: the published-updater × candidate Docker cell (published-upgrade-survivor, scenario legacy-operator-state, restart mode auto-auth) passed from [email protected] to a c6a7bf3 package: update success, backup/rollback passed. This PR stores no new data.

Tests. Each new case fails on the source it guards and passes on this PR; controls pass on both. Wall time is pnpm test <file> --maxWorkers=1 for the whole file on c6a7bf3, except where noted.

File New/changed cases Fails on Wall
src/tasks/detached-task-lookup.worker.test.ts (9) Through the real task store: Gateway A's replaced generation finds its child's task and writes the terminal succeeded row only while A is open. With A closing and a different Gateway B live, lookup is unavailable, settlement rejects with DetachedTaskRuntimeOwnerRetiredError, and the stored row stays running. base (both open-Gateway cases) 48 s on 17a8b88
src/tasks/detached-task-runtime.test.ts (37) A retired scope's task creation is rejected before any write. Admitted work settles on Gateway A's core-owned successor. It is refused on a successor that registers a plugin task runtime, on a closing Gateway A while Gateway B is live, and on a generation left unlinked by a published build. base; 10d8057 47 s
src/agents/subagents/registry/subagent-registry.test.ts (188) A child registered inside the spawning generation settles its task after its Gateway publishes a successor; the test awaits the terminal write, with no polling. base 34 s
src/plugins/loader.test.ts (203) Through the real plugin loader: after the only middleware's plugin is removed, the result is the same object as on the no-middleware path. A replaced plugin fails closed. A removed plugin's handler fails closed while Gateway B is live, while Gateway A is closing, and on a registry left unlinked by a published build. base; 10d8057 81 s
src/agents/harness/tool-result-middleware.test.ts (38) A later middleware whose plugin is removed while an earlier one awaits is skipped. A handler that mutates the result and then throws PluginInstanceUnavailableError still fails closed. efc7336, a16ca21 14 s

pnpm tsgo:core and oxlint on the changed files are clean.

Disabling or uninstalling a plugin while an agent turn is running replaced
the turn's tool result with a post-processing error when the removed plugin
owned tool-result middleware. A subagent started before the reload then
retried its task settlement every second until the Gateway restarted.

The harness now skips middleware whose plugin instance retired during the
run and keeps the tool result. Detached task settlement captured in a
retired plugin generation settles on the live generation when core owns
tasks in both; a real ownership move to a plugin runtime still refuses.
@clawsweeper

clawsweeper Bot commented Sep 24, 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: S labels Sep 24, 2026
@obviyus
obviyus marked this pull request as ready for review September 24, 2026 14:53
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 24, 2026
@clawsweeper

clawsweeper Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 25, 2026, 2:06 AM ET / 06:06 UTC (Revision 16).

ClawSweeper review

What this changes

The branch preserves tool results when removed plugin middleware expires and lets previously admitted child tasks settle through the Gateway that admitted them after a plugin reload.

Merge readiness

✅ Ready for maintainer review

Current main still has the reported reload failure. The latest revision adds stored-task write evidence for the authority boundary raised in the prior review; I found no remaining introduced correctness defect.

Priority: P1
Reviewed head: 17a8b88c6772326b5388d473fb44a0618eb76f14

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Detailed live observations and a real worker-write boundary test support a coherent repair, with no blocking finding identified.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Reported before/after Telegram Test Server runs on the unchanged production code show restored tool output and child settlement. The latest revision adds an actual stored-row check after allowed settlement and closed-Gateway refusal while another Gateway is live. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): Reported before/after Telegram Test Server runs on the unchanged production code show restored tool output and child settlement. The latest revision adds an actual stored-row check after allowed settlement and closed-Gateway refusal while another Gateway is live. No stored-data contract changes.
Evidence reviewed 8 items Introduced middleware guard: The runner checks a retired handler against its own Gateway and skips it before the raw-result path or a later handler call.
Gateway-bound task authority: Existing core-owned work may adopt only its admitting Gateway's current registry; the assertion checks that registry again before settlement.
Final-effect boundary test: The new split-state worker test checks the stored row after allowed settlement and after refusal when the admitting Gateway closes while another Gateway remains live. The PR body reports 48 seconds for the file.
Findings None None.
Security None None.

How this fits together

The Gateway publishes plugin registry generations that agent turns retain while tools and subagents run. Tool-result middleware feeds output back to the model, while the detached-task runtime records and settles child work.

flowchart LR
 A[Plugin change] --> B[Gateway registry owner]
 B --> C[Running agent turn]
 C --> D[Tool-result middleware]
 D --> E[Model receives result]
 C --> F[Child task lookup]
 F --> G[Authority check]
 G --> H[Stored task update]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +107, Tests +418. Total +525 across 13 files.

View PR surface stats
Area Files Added Removed Net
Source 7 119 12 +107
Tests 6 418 0 +418
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 13 537 12 +525

Review metrics

Metric Value Why it matters
Production and test lines production +119/−12; tests +418/−0 The production growth establishes Gateway-scoped recovery; the larger test addition covers reload, settlement, and refusal boundaries.

Technical review

Best possible solution:

Keep reload recovery with the admitting Gateway, preserve untouched results when removed middleware cannot run, and handle the distinct Telegram final-send failure in #155788.

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

Yes, the current-main source exposes the stale middleware and strict retired-scope paths, and the PR body reports a before/after Telegram Test Server reproduction. This read-only review did not run current main.

Is this the best way to solve the issue?

Yes, the repair stays with the registry, middleware, and task owners and preserves strict refusal when the admitting Gateway is unavailable or task ownership moves to a plugin.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. Reported before/after Telegram Test Server runs on the unchanged production code show restored tool output and child settlement. The latest revision adds an actual stored-row check after allowed settlement and closed-Gateway refusal while another Gateway is live. No stored-data contract changes.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): Reported before/after Telegram Test Server runs on the unchanged production code show restored tool output and child settlement. The latest revision adds an actual stored-row check after allowed settlement and closed-Gateway refusal while another Gateway is live. No stored-data contract changes.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove merge-risk: 🚨 compatibility: Current PR review merge-risk labels are merge-risk: 🚨 session-state, merge-risk: 🚨 security-boundary.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: A plugin reload during an active turn can lose tool output and leave child work retrying without settlement.
  • merge-risk: 🚨 session-state: Settlement now follows a successor registry, so an incorrect owner choice could mis-associate or strand existing child tasks.
  • merge-risk: 🚨 security-boundary: The patch changes when a retired generation may reach a task write, making final-effect Gateway authority important to review.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): Reported before/after Telegram Test Server runs on the unchanged production code show restored tool output and child settlement. The latest revision adds an actual stored-row check after allowed settlement and closed-Gateway refusal while another Gateway is live. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. Reported before/after Telegram Test Server runs on the unchanged production code show restored tool output and child settlement. The latest revision adds an actual stored-row check after allowed settlement and closed-Gateway refusal while another Gateway is live. No stored-data contract changes.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. The changed tool result and child completion can alter visible Telegram replies, and the PR body reports relevant Test Server runs.

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)
  • Mariano: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Josh Lehman: 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 (15 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-24T22:02:57.162Z sha 0063d2f :: needs real behavior proof before merge. :: [P1] Key successor authority by the admitting Gateway
  • reviewed 2026-09-24T22:23:13.850Z sha 202a19e :: needs real behavior proof before merge. :: [P1] Bind task settlement to the admitting Gateway's successor | [P2] Check removed middleware against its Gateway owner
  • reviewed 2026-09-24T22:32:20.424Z sha 10d8057 :: needs real behavior proof before merge. :: [P1] Bind settlement to the admitting Gateway | [P2] Resolve removed middleware through its Gateway owner
  • reviewed 2026-09-24T22:52:11.638Z sha 10d8057 :: needs real behavior proof before merge. :: [P1] Bind settlement to the admitting Gateway | [P2] Resolve removed middleware through its Gateway owner
  • reviewed 2026-09-25T02:38:58.629Z sha 8a3a572 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-25T04:20:09.981Z sha a9a0609 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-25T04:42:45.023Z sha 1bdedec :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-25T05:09:19.614Z sha c6a7bf3 :: needs real behavior proof before merge. :: [P3] Report the added worker test's measured cost

Only settlement of existing tasks moves from a retired plugin generation to
the live one; task creation stays bound to its admitting scope.

The harness skips cached tool-result middleware only when the handler's own
plugin instance is retired and the plugin is gone from the live registry,
before the handler runs. Any error a handler throws still fails closed,
including one raised after it mutated the result.

The subagent settlement test awaits the task registry's terminal write
instead of polling.
@obviyus obviyus closed this Sep 24, 2026
@obviyus obviyus reopened this Sep 24, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 24, 2026
Filter removed plugins' middleware before choosing the runner path, so a run
whose only middleware was removed returns the untouched result, the same as
with no middleware. Callable and cyclic details are no longer serialized.
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. label Sep 24, 2026
An earlier handler can await while a later handler's plugin is removed.
Keep the upfront filter for the raw-result fast path and skip a handler
whose plugin was removed right before calling it.
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 24, 2026
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Sep 25, 2026
The async task lookup added on main reads an existing child's task row but
captured the runtime owner strictly, so after a plugin reload the child's
own lookups failed and its delivery retried on backoff. Existing-row reads
now follow the same owner as settlement: the admitting Gateway's current
registry, and nothing when that Gateway is closing.
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 25, 2026
@obviyus
obviyus merged commit 4db779e into main Sep 25, 2026
211 of 212 checks passed
@obviyus
obviyus deleted the fix/plugin-reload-inflight-turns branch September 25, 2026 06:17
@obviyus

obviyus commented Sep 25, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in 4db779e.

  • Bug: removing or disabling a plugin mid-turn replaced the turn's tool result with a post-processing error, and a subagent started before the reload retried settlement about once per second until the Gateway restarted.
  • Fix: each turn registry is bound to the Gateway that admitted it. Removed-plugin middleware is skipped, and existing child tasks look up and settle through that Gateway's live successor only. A closing or different Gateway is refused before any task write.
  • Proof: live Telegram test-server matrix on the built candidate (tool results kept, child tasks succeeded, no retry loop; base lost the result and looped), a published-updater upgrade cell, and a real task-store test that writes the terminal row only through the open admitting Gateway.

vincentkoc added a commit that referenced this pull request Sep 25, 2026
…4-prep

* commit '8fe893da516ebdc817692fb2d272e27bc3c88376': (31 commits)
  fix(test): wait for reload admission before restart polling (#157964)
  refactor(mattermost): reuse DM retry option selection (#157800)
  chore(i18n): refresh native locales (#157850)
  perf(sessions): reuse current participants across transcript appends (#157622)
  refactor(signal): share pending transport migration results (#157777)
  fix(tui): open model pickers without waiting for the Gateway (#157839)
  fix(gateway): apply config despite delayed file notifications (#157906)
  fix(auth): clear deleted account selections and support account recovery (#157745)
  fix: plugin reloads lose tool results and strand subagent settlement (#157339)
  fix(gateway): avoid preview errors during worker metadata updates (#157943)
  refactor(diffs): reuse native promisify for compression (#157835)
  fix(models): keep current choices on the first picker page (#157869)
  fix(plugins): retain existing quarantine across unrelated reloads (#157907)
  fix(openai): prioritize ChatGPT sign-in and clarify auth choices (#157792)
  chore(ui): refresh control ui locales (#157955)
  fix(ui): refresh connected accounts after auth changes (#157950)
  fix(scripts): avoid redundant npm version process in package checks (#157809)
  refactor(usage): capture hosted pricing once per operation (#157838)
  refactor(ui): share slash-command failure results (#157649)
  fix(cron): announce runs miss the channel's formatting rules (#157877)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 26, 2026
…penclaw#157339)

## What Problem This Solves

Fixes: removing or disabling a plugin while an agent turn is running loses that turn's tool result, and a background subagent started before the change never settles. Its completion retries about once per second until the Gateway restarts.

## User Impact

User impact: owners can uninstall or disable a plugin mid-conversation, even through the agent's own `plugins` tool. The running turn keeps its tool output, and subagents started before the change deliver their results and finish.

## Why This Change Was Made

- **Admitting Gateway:** each Gateway registry owner now links every registry it publishes to itself. A turn's derived agent-runtime registry (`src/agents/runtime-plugins.ts`) is linked to the Gateway whose request admitted the turn. A registry claimed by two owners, or built by a published build without the link, has no owner, and recovery stays strict for it.
- **Tool results:** a run resolves its tool-result middleware once. When the plugin that owns a middleware was removed mid-run, calling it threw `PluginInstanceUnavailableError`, and the harness replaced the whole tool result with "Tool output unavailable due to post-processing error." The runner now drops a handler only when that handler's own plugin instance is retired and the plugin is gone from the current registry of the Gateway that published it. It checks before choosing a path, so a run whose only middleware was removed returns the untouched result exactly like the no-middleware path. It checks again right before each call. A skipped plugin never runs. Every error a handler throws still fails closed, a replaced plugin fails closed, and a handler whose Gateway is closing or unlinked fails closed.
- **Detached task settlement:** a child run, its lifecycle events and its retry timers keep the parent turn's plugin-generation scope. After a plugin reload that scope's registry is retired, and `captureDetachedTaskRuntimeOwner` refused every core settlement ("Detached task runtime owner changed before task settlement."); each retry captured the same stale scope, so it looped. Lookup and settlement of rows that already exist now resolve through the admitting Gateway's current registry, only while that Gateway is open and core owns tasks in both generations. The owner check runs again right before the terminal write. Task creation stays bound to its admitting scope, so a retired generation cannot admit new task work. A closing admitting Gateway, a different live Gateway, or a successor that registers a plugin task runtime is refused with `DetachedTaskRuntimeOwnerRetiredError` before any task write.

## Evidence

**Production trace (before):** an owner asked the agent to uninstall a plugin that owned tool-result middleware. The `plugins` tool succeeded and two hot reloads followed. About 1 s later the log showed `tool result middleware failed for tool_call`, and the model received "Tool output unavailable due to post-processing error." A subagent started before the reload then logged `DetachedTaskRuntimeOwnerRetiredError` about 2,480 times over about 50 minutes, until the Gateway restarted.

**Live Telegram matrix, built `dist` of `c6a7bf3` vs base `c852711`.** Each run uses a real Gateway, the Telegram test server with a real QA user, and a mock provider. The DM or forum-topic turn runs `exec`, spawns a subagent (about 20 s of work), then runs a 12 s `exec`. During that exec, the scenario changes a test plugin that owns tool-result middleware by editing config in place, so the Gateway hot-reloads. "Owner-retired lines" counts `DetachedTaskRuntimeOwnerRetiredError` and "settlement deferred" log lines until Gateway shutdown (about 2 minutes later). The task state is read with `openclaw tasks list --json` at 115 s.

| # | Case | base `c852711` | this PR `c6a7bf3` |
| --- | --- | --- | --- |
| 1 | DM, plugin uninstalled mid-turn (disable, then remove: two hot reloads, as in production) | Reply `TOOL2_LOST(Tool output unavailable due to post-processing error.)`; 512 owner-retired + 252 deferred lines; child task stays `running` | Reply `TOOL2_OK`; child task `succeeded`; 1 owner-retired line (one retried lookup), then no loop |
| 2 | Same, in a forum topic | Same loss and loop (512 + 252); child `running` | `TOOL2_OK` and the child's result posted in the topic; child `succeeded`/`delivered`; 1 owner-retired line |
| 3 | DM, plugin only disabled mid-turn (one hot reload) | not run | `TOOL2_OK`; child `succeeded`/`delivered`; 1 owner-retired line |
| 4 | DM, new task work after the reload: the same turn waits, then `sessions_send`s a follow-up to its finished child | Tool results lost (3 middleware failures, including the `sessions_send` result); follow-up task created | `TOOL2_OK` and the `sessions_send` result intact; the follow-up task (`cli`, `succeeded`) is admitted on the live generation; child `succeeded`/`delivered`; no owner-retired line |
| 5 | DM, middleware plugin replaced (reinstalled) mid-turn | Gateway refuses: `still has active retained work; … replacement not applied`. User sees `TOOL2_OK` and the child result | Same refusal; `TOOL2_OK`; child `succeeded` |
| 6 | DM happy path, no plugin change | not run | `HAPPY_DONE TOOL_OK`, one reply |

Notes:
- **Case 4:** a turn's new task work goes through Gateway admission, which uses the live generation, so no live flow reaches task creation inside a retired scope. The unit test below proves that such creation is rejected before any write.
- **Case 5:** the Gateway will not replace a plugin whose work is still held, so the fail-closed path for a stale handler with a live replacement cannot be reached from a turn. The loader test below covers it.
- **Cases 1 and 5 (DM):** the child's completion message was still `pending` at the 115 s read. Its direct send failed with `Plugin telegram was reloaded or disabled; use its current tools.` This is the separately tracked Telegram send issue openclaw#155788, which this PR does not change.

**Upgrade:** the published-updater × candidate Docker cell (`published-upgrade-survivor`, scenario `legacy-operator-state`, restart mode `auto-auth`) passed from `[email protected]` to a `c6a7bf3` package: update `success`, backup/rollback `passed`. This PR stores no new data.

**Tests.** Each new case fails on the source it guards and passes on this PR; controls pass on both. Wall time is `pnpm test <file> --maxWorkers=1` for the whole file on `c6a7bf3`, except where noted.

| File | New/changed cases | Fails on | Wall |
| --- | --- | --- | --- |
| `src/tasks/detached-task-lookup.worker.test.ts` (9) | Through the real task store: Gateway A's replaced generation finds its child's task and writes the terminal `succeeded` row only while A is open. With A closing and a different Gateway B live, lookup is `unavailable`, settlement rejects with `DetachedTaskRuntimeOwnerRetiredError`, and the stored row stays `running`. | base (both open-Gateway cases) | 48 s on `17a8b88` |
| `src/tasks/detached-task-runtime.test.ts` (37) | A retired scope's task creation is rejected before any write. Admitted work settles on Gateway A's core-owned successor. It is refused on a successor that registers a plugin task runtime, on a closing Gateway A while Gateway B is live, and on a generation left unlinked by a published build. | base; `10d8057` | 47 s |
| `src/agents/subagents/registry/subagent-registry.test.ts` (188) | A child registered inside the spawning generation settles its task after its Gateway publishes a successor; the test awaits the terminal write, with no polling. | base | 34 s |
| `src/plugins/loader.test.ts` (203) | Through the real plugin loader: after the only middleware's plugin is removed, the result is the same object as on the no-middleware path. A replaced plugin fails closed. A removed plugin's handler fails closed while Gateway B is live, while Gateway A is closing, and on a registry left unlinked by a published build. | base; `10d8057` | 81 s |
| `src/agents/harness/tool-result-middleware.test.ts` (38) | A later middleware whose plugin is removed while an earlier one awaits is skipped. A handler that mutates the result and then throws `PluginInstanceUnavailableError` still fails closed. | `efc7336`, `a16ca21` | 14 s |

`pnpm tsgo:core` and oxlint on the changed files are clean.

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

VACInc commented Sep 28, 2026 •

Copy link
Copy Markdown
Member

PR #160009 adds guarded saved-final Telegram delivery alongside this PR's admitting-Gateway continuity work. It does not replace the tool-result or task-settlement repair in #157339. The pending Telegram child-completion sends recorded here were linked to #155788, but #160009's inbound final-delivery proof must not be treated as proof that every generic detached-subagent announcement path is fixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L 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.

2 participants