Skip to content

refactor(subagents): check a Stop's caller authority once, then let the admitted kill finish - #205940

Merged
vincentkoc merged 2 commits into
mainfrom
refactor/subagent-kill-owner
Nov 26, 2026
Merged

vincentkoc merged 2 commits into
mainfrom
refactor/subagent-kill-owner

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

What Problem This Solves

When someone stops a sub-agent, OpenClaw kept re-asking during the Stop whether that caller still had authority over the run. The question came up again before each step, after the kill intent was already recorded, after the run was interrupted, and before the result was published. If the answer changed at any of those points, the Stop backed out with "ownership changed; retry".

That had two bad results:

  • A Stop could do real work, such as aborting the child's run, and still report failure to the caller. Example: authority is revoked after the abort. The run is stopped, but the call rejects with the caller's revocation error.
  • A Stop could undo itself. Stopping a parent's chat retires the parent turn that the Stop's authority came from. The collector kill then refused partway through, so sessions.abort reported that nothing was stopped and the collector stayed queued.

The repository rule (AGENTS.md, "Choose good compromises") is to check authority once, when work starts, and let a started request finish. Revocation applies to the next request. #202442 and #204249 already removed in-run authority re-checks elsewhere. Kill is the largest remaining place that still does it.

User Impact

  • A caller who loses control before the Stop selects its runs is refused, and nothing stops. This is unchanged.
  • After that point, the Stop finishes and reports what it did, even if the caller loses control meanwhile or the Stop ends the parent turn that started it.
  • The checks that this exact run and session incarnation are still the ones being stopped are unchanged. A kill never touches a successor run.
  • docs/tools/subagents/operations.md ("Stopping") now states when authority is checked.

Why This Change Was Made

  • withSubagentKillScope owns admission. It checks the caller while selecting the run tree and once more right before running the kill. After that its assertCurrent checks only the registry write source, not the caller. It also stops calling the caller's prepareRead, because that read prepares the caller's authority check (the subagents tool's version calls assertSelection()). Each tree's own session and registry read preparation is unchanged. The descendant-refresh special case that let already-accepted outcomes past a revoked caller is deleted, because there is no revoked caller after admission.
  • mutateSubagentRunForKill loses declineRevokedCancellation and its five call sites (three in preparation, two in the run phase). It also loses the acceptance.callerFailure paths and the post-claim branches that settled or released the claim after a revocation.
  • createSubagentKillAcceptance drops assertCallerCurrent and its recorded caller failure. It keeps only native-owner checks when cancelling commands.
  • The kill-settlement owner drops the caller check inside markSubagentRunTerminated. assertCancellationCurrent becomes assertClaimCurrent (the claimed row and session incarnation only).
  • settleSubagentKill no longer re-asserts the caller after the kill. killLatestSubagentRun no longer re-asserts it while cancelling the run's commands.

Size: production code is +39 −149 across 5 files (tests +52 −64). Complexity from the same scanner (scb-check) before and after: mutateSubagentRunForKill CC 154 → 132, withSubagentKillScope CC 140 → 134, and the runtime's cancellation closure CC 40 → 35.

Not in this PR: the session-incarnation fence (ownsSessionIncarnation, releaseChangedSession) is still re-checked in flight. The kill claim already records sessionId and lifecycleRevision, so the next step makes the claim the single identity check. That changes what a session reset during a kill reports, so it gets its own PR and proof.

Open overlap: #194275 changes subagent-control-kill-scope.ts and subagent-control-kill.ts, and #189391 changes subagent-control-kill-scope.ts. Either will need a rebase.

Evidence

  • subagent-control.concurrency.test.ts "refuses a Stop revoked before admission and finishes one revoked %s":
    • Revoked while the tree is selected: the Stop is refused, nothing is aborted and nothing is interrupted.
    • Revoked after interruption or after abort: the Stop resolves { found: true, killed: true }, the run is aborted, the admission is interrupted once, and no kill intent is left behind.
    • On main, the two "after" cases reject with the caller error, and in the "after abort" case the run is still aborted. They fail on main and pass here.
  • session-utils.queued-collector.test.ts, scenario sessions.abort exact=false parent-retired: the Stop that retires its own parent turn now stops the collector (respond true, collector no longer queued).
  • Other tests updated to the same contract. In each one, the cleanup and ordering assertions that are the test's real subject are unchanged:
    • subagent-control.accepted-stop.test.ts: an accepted Stop whose caller is revoked mid-settlement resolves and publishes onResult once instead of rejecting.
    • subagent-control.commands.test.ts: postaccept-revoked reports ok, and late-revoked-evicted no longer carries the revocation in its error. The cleanup failure still reports error.
    • subagent-control.worker.test.ts: a caller that retires after the kill claim commits gets a completed kill. A replaced session incarnation still releases the claim, because that identity check is kept.
    • subagent-control.concurrency.test.ts "an admitted Stop never waits on caller facts requested while …": caller facts are not read after admission.
  • Before the change, the 26 kill-related test files passed 363/363 on main.
  • After the change, run sequentially:
    • src/agents/subagents: 1,331 passed and 1 skipped. The only failures in that run were the 5 cases of the last concurrency test above, which was then rewritten; that file now passes 12/12.
    • The gateway and auto-reply abort, stop, kill, queued-collector and reset tests, plus the tool and kill callers: all passed (763 + 120 + 118 + 11 + 7).
  • A first combined run had 6 gateway-server files fail in teardown with ERR_SPAWN_BROKER_UNAVAILABLE and no assertion failures. Those files pass when run alone (8 files, 70 tests).
  • pnpm tsgo:core and pnpm tsgo:test:src are clean, as are oxfmt, oxlint on the changed files and git diff --check.
  • Local autoreview, branch mode at P0–P2, with the unchanged kill capture, intent, types and session modules and the subagents-tool, chat-abort-runtime and chat-abort-descendants callers as source context: scoped-clean, no findings, confidence 0.84.
  • Not exercised: a live Gateway Stop raced against a role change in a real channel. The proof is the in-process gateway and registry harness above.
  • Follow-up 244964d: PR CI's checks-node-changed-compact-large-33 shard showed that two spawn production-boundary helpers still expected the old contract. They now expect admitted native Stops to finish: "separates native stop acceptance from caller revocation" (after interruption, already interrupted) and the consumed-active-revoked custody case, which reports ok with killed: 1. With main's production code those three fail, and they pass here. subagent-spawn.production-boundary.test.ts passes 140/141. The one failure, preserves routed native Stop authority … (consumed-session), fails the same way with main's production code (aborted expected false, received true). It is the existing order-dependent failure on main described in refactor(subagents): retire finished child rows by one rule instead of two handed-off flags #205482.
  • CI run 45835338650 on 244964d: the checks-fast-baseline-ratchets job ran for 47 minutes and stopped inside "Run baseline ratchets". The step never reported a result, and GitHub returns BlobNotFound for its log, so the runner was lost. Locally, pnpm check:baseline-ratchets --base origin/main --no-merge-base on the PR merged with current main passes every ratchet: max-lines, assertion-safety, session-identity, runtime-process-lifecycle, mock-exports, and test-lines (net −12 against a 400 allowance). Only the failed jobs were rerun, as an infrastructure recovery.

…he admitted kill finish

A subagent Stop re-checked its caller's authority before almost every step,
including after its kill intent was recorded and after the run was aborted.
A revocation in between made the Stop back out or report failure after the
work was done.

The kill scope now checks the caller while it selects the run tree and once
more at admission. After that only the claimed row and session incarnation
stay checked. This removes the per-run revocation decline path, the
acceptance caller-failure path and the post-kill caller re-assertions.
@vincentkoc vincentkoc self-assigned this Nov 26, 2026
@clawsweeper

clawsweeper Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: M labels Nov 26, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. impact:session-state Session, memory, transcript, context, or agent state can drift or corrupt. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 26, 2026
@clawsweeper

clawsweeper Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Codex review: passed.

What this changes

This PR checks caller authority at Stop admission and lets admitted cancellation finish while retaining run and session identity checks.

Example: Stopping caller-control-run aborts the child, then the caller loses authority.

  • Before: The child stops, but cancellation rejects with the caller's revocation error.
  • After: Cancellation resolves with found=true and killed=true and clears the kill intent.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The patch is focused and coherent with no discrete findings; required real-behavior proof is absent, and the draft's broad CI gates have not run.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A Stop can abort a child and still report failure, or leave a collector queued when cancellation retires its own parent.
Reason: The maintainer-authored direction follows the repository's admission contract and removes substantial failure bookkeeping while preserving target identity.

Merge readiness

✅ Ready for maintainer review

Keep this maintainer-authored draft open: it addresses false Stop failures through the existing cancellation owner, and no introduced correctness defect was found.

Reviewed head: 8c061df8cd38842e8b023955d4d5e568899c6926

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Provide redacted output from an isolated Gateway with a real agent/model showing sessions.abort finishing successfully when its own cancellation retires the parent, with the queued collector cancelled and never launched; redact IPs, API keys, phone numbers, and non-public endpoints.
Agent review details

How this fits together

Gateway and subagents-tool Stop requests enter the subagent registry's kill scope, which selects owned descendants, interrupts captured execution and commands, persists cancellation, and publishes the outcome.

flowchart TD
  A[Gateway or subagents tool] --> B[Select tree and admit caller]
  B --> C[Capture exact execution]
  C --> D[Interrupt and drain cleanup]
  D --> E[Settle existing registry claim]
  E --> F[Publish Stop result]
Loading

Technical review

Best possible solution:

Keep admission in the existing kill scope and let its captured cancellation finish under the retained run, session, persistence, and cleanup owners.

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

Current-main source reasserts caller authority after cancellation effects, and the author reports matching red-on-main, green-on-head regressions; this read-only review did not execute them.

Is this the best way to solve the issue?

The patch removes the repeated policy decision at its existing owner, updates affected consumers' expectations, and preserves exact-target and cleanup contracts without adding another control path.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • In-flight caller reauthorization changes intended behavior with a stated reason (a3376d5: Prevent former controllers from starting new descendant-cancellation effects while retaining accepted native cleanup, as recorded in fix: require current subagent control to cancel descendant tasks #149082.)
  • Worker persistence and retained cleanup ownership keeps the original intent (fd1467d: Move Stop persistence off the Gateway thread without losing committed claims, queue holds, or protection against replacement sessions.)
  • Descendant ordinary-command cancellation keeps the original intent (f61b347: Drain commands belonging to selected native children, preserve independent services and completed results, and surface cleanup failures.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source -110, Tests -12, Docs +5. Total -117 across 11 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 5 39 149 -110
Tests 5 52 64 -12
Docs 1 5 0 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 96 213 -117

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Capture the self-retiring-parent Stop scenario through an isolated real Gateway and attach its successful cancellation output.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 26, 2026, 7:27 AM ET / 12:27 UTC.

@vincentkoc
vincentkoc marked this pull request as ready for review November 26, 2026 13:18
@vincentkoc

Copy link
Copy Markdown
Member Author

Merged via squash auto-merge.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 27, 2026
…he admitted kill finish (openclaw#205940)

* refactor(subagents): check a Stop's caller authority once, then let the admitted kill finish

A subagent Stop re-checked its caller's authority before almost every step,
including after its kill intent was recorded and after the run was aborted.
A revocation in between made the Stop back out or report failure after the
work was done.

The kill scope now checks the caller while it selects the run tree and once
more at admission. After that only the claimed row and session incarnation
stay checked. This removes the per-run revocation decline path, the
acceptance caller-failure path and the post-kill caller re-assertions.

* test(subagents): expect admitted native Stops to finish after caller revocation
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
…he admitted kill finish (#205940)

* refactor(subagents): check a Stop's caller authority once, then let the admitted kill finish

A subagent Stop re-checked its caller's authority before almost every step,
including after its kill intent was recorded and after the run was aborted.
A revocation in between made the Stop back out or report failure after the
work was done.

The kill scope now checks the caller while it selects the run tree and once
more at admission. After that only the claimed row and session incarnation
stay checked. This removes the per-run revocation decline path, the
acceptance caller-failure path and the post-kill caller re-assertions.

* test(subagents): expect admitted native Stops to finish after caller revocation

(cherry picked from commit 438f743)

Co-authored-by: RomneyDa <[email protected]>
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 gateway Gateway runtime impact:session-state Session, memory, transcript, context, or agent state can drift or corrupt. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. 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