Skip to content

fix(subagents): honor recorded owners during reconciliation and cleanup - #166845

Merged
steipete merged 4 commits into
mainfrom
deslop/d06c-subagent-raw-owner-20261007
Oct 8, 2026
Merged

steipete merged 4 commits into
mainfrom
deslop/d06c-subagent-raw-owner-20261007

Conversation

@steipete

@steipete steipete commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Related: #166550, #166691

What Problem This Solves

Fixes subagent recovery, announcement, and cleanup selecting the wrong agent's session when a recorded child uses a raw key such as global.

User Impact

Raw-key children are reconciled and conditionally cleaned up under their recorded owner. Qualified keys retain encoded-owner precedence, and explicit shared SQLite stores retain their shared raw-key namespace. Configuration, protocol, schema, persisted-data shapes, tool descriptions, and prompts are unchanged.

Why This Change Was Made

src/agents/subagents/registry/subagent-session-reconciliation.ts:62 derived ownership from the key alone and read SQLite synchronously. The repair carries the recorded child owner through the existing worker reader and cleanup request.

Reads retain the original source, Gateway, lifecycle, and run authority across awaits and drain. Sweep classification and completion use one worker observation. Restore rejects obsolete collector addresses after rekeying, and requester transfer owns its initial wake when metadata reads yield.

This bug-fix follow-up adds 361 production lines (434 added / 73 removed), principally for worker-read and continuation guards. The existing sweep-scope object replaces duplicate local aliases. Recovery tests use the canonical typed runtime fixture; the completion-retry test group moved into existing support with its assertions, text, and registration order preserved.

Evidence

  • Raw-owner regressions failed before repair. Real Gateway cleanup preserves the unrelated main session; restart restoration uses the real SQLite fixture. Encoded precedence, shared stores, replacement/refusal paths, read errors, and authority across drain remain covered.
  • Final candidate: 7400b120685482836190d9e1676ac3311840d24d, source tree e43dd9c45c44c021d50bab7534b0f24f7b55fff2. The complete changed-file checker passed on that tree: production types, all 27 test-type graphs, three unused-export scans, lint, and source guards. No size waiver was needed.
  • The full subsystem packet on pre-rebase head 5c968063e6f33ec75db233f520a7b8086c3f3879 ran both directories, all four E2Es, two Gateway boundaries, and lint-suppression checks: 5,389 passed, one inherited logging failure, two existing skips, 339 files, 1,864.71 seconds. Full build passed in 416.7 seconds; SDK comparison found no API changes (digest ff7b090f).
  • The final source tree passed 162 tests across 11 files in 563.63 seconds, including the original native-cancellation E2E (25.997 seconds). Runtime and Madge cycles were both zero. Source-tree and patch checks passed before and after execution, matching the signed final commit; the native terminal receipt recorded exit 0. The scope/test relocation also passed all eight focused cases and independent P2 review.

The initial integrated packet exposed duplicate requester wakes after the new metadata await and fixtures attached to the former synchronous reader. The existing resumed-run state now marks actual transferred wakes, and those fixtures use the existing worker-reader boundary. All seven original lane failures passed in the full packet. Conflict validation also exposed incomplete runtime fixtures and line-cap growth; both are corrected without weaker assertions, larger budgets, retries, or new skips.

Earlier failures and remaining limits

The earlier logging suppression failure was reproduced on clean main. Its upstream repair 354f94083a3 is included in the current base, and the suppression tests pass on the rebased source.

Exact-head hosted run 37726433932 completed with 133 checks: 77 successful, 53 skipped, 1 neutral, and 2 failures; no pending or cancelled checks. The native-cancellation replacement-registration race and its secondary read-admission rejection were reproduced separately with controlled ordering on pinned main b9533fbd155b0d0b455b23825d9e3c32f3a1eb7a. The aggregate gate reflects that job. The original unmodified main sequence passed; these diagnostics prove inherited defects, not a fixture repair. The final evidence comment records each failing job, causal isolation, exact source comparisons, commands, and limitations.

An earlier local cleanup-exhaustion case observed one global fake timer instead of zero. Its ordered replay and later packets passed, but its cause remains unresolved.

The original full-run broker receipt was unavailable despite retained stage output; a subsequent command verified source identity and retrieved SDK artifacts before lease release. The final-tree command has a successful native receipt and verified source identity. Exact-head hosted CI remains the merge gate.

@clawsweeper

clawsweeper Bot commented Oct 8, 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 gateway Gateway runtime agents Agent runtime and tooling size: XL labels Oct 8, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 8, 2026
@clawsweeper

clawsweeper Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed October 8, 2026, 12:22 AM ET / 04:22 UTC (Revision 3).

ClawSweeper review

What this changes

The branch carries recorded child-agent ownership through session reconciliation, announcement metadata reads, and conditional cleanup while retaining asynchronous owner guards.

Example: Cleanup runs for a recorded research child using global

  • Before: Reconciliation cannot resolve global without an encoded agent owner.
  • After: Cleanup selects research/global and preserves the unrelated main/global session.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful owner-aware reconciliation and cleanup have meaningful boundary coverage, but the claimed announcement repair remains partial.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: The supplied maintainer-authored classification exempts ordinary contributor proof. Recorded Linux validation and inspected production-boundary cases cover real SQLite restoration and Gateway deletion preserving the unrelated main session; they do not establish ordinary raw-key announcement delivery. No stored-data format or migration contract changes.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: A delegated child using global can be reconciled against the wrong agent's session or fail to report its result.
Reason: Correct recorded ownership is an established session contract, and the area owner's prior merged work supports this repair direction. Ordinary raw-key announcements still encounter an unscoped statistics read.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep open: this PR addresses a real ownership defect, but its claimed raw-key announcement repair remains incomplete.

Priority: P2
Reviewed head: 7400b120685482836190d9e1676ac3311840d24d

Before merge

  • Complete next step (P2) - Finish the claimed ordinary raw-key announcement repair by carrying childAgentId into statistics resolution and exercising the real resolver.

Findings

None.

Provenance

  • Restored requester wake bookkeeping: original intent not found (unknown: Targeted base-line blame could not retrieve a required historical blob because the promisor remote returned HTTP 403.)

Tests

  • Missing end-to-end proof: The ordinary raw-key announcement case needs the real agent-key resolver and statistics reader; its current resolver mock hides the remaining failure, so successful base-failing/head-passing delivery is not established.
Agent review details

How this fits together

The subagent registry tracks delegated work across completion and Gateway restarts. It reads child session metadata, reports results to the parent, and conditionally removes expired child sessions.

flowchart TD
  A[Recorded child run] --> B[Resolve child session owner]
  B --> C[Worker metadata reader]
  C --> D[Check current run and Gateway]
  D --> E[Reconcile completion]
  E --> F[Announce result to parent]
  D --> G[Conditional child cleanup]
Loading

Technical review

Best possible solution:

Carry recorded ownership through the remaining announcement statistics read using the existing worker reader, preserving encoded-key precedence and conditional deletion.

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

Yes, source establishes both the base reconciliation defect and the remaining announcement failure: global lacks an encoded agent ID, and the statistics reader supplies no recorded owner. No runtime reproduction was executed here.

Is this the best way to solve the issue?

Partly: reusing worker readers and existing conditional cleanup is appropriate, but ownership must also reach the statistics reader to deliver the claimed ordinary raw-key announcement behavior.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness. Added test files: 16.

Security

None.

Evidence

Acceptance criteria:

  • [P1] pnpm test src/agents/subagents/announce/subagent-announce.test.ts src/agents/subagents/announce/subagent-announce-output.test.ts --maxWorkers=1.
  • [P1] pnpm test src/gateway/server-methods/sessions-lifecycle-agent-scope.test.ts --maxWorkers=1.
  • [P1] node scripts/check-changed.mjs.
  • [P1] git diff --check.

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 9a94a23 adds src/agents/subagents/registry/subagent-session-reconciliation.ts:153 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 9a94a2356a4f; files: src/agents/subagents/registry/subagent-session-reconciliation.ts)

PR surface

Source +361, Tests +980, Other -1. Total +1340 across 27 files.

View PR surface stats
Area Files Added Removed Net
Source 10 434 73 +361
Tests 16 1030 50 +980
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 27 1464 124 +1340

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Recorded raw-key child ownership is a bounded correctness repair affecting subagent recovery and cleanup.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • 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.

  • Complete recorded-owner propagation into announcement statistics and verify ordinary global-child delivery with the real resolver.

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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-08T00:33:20.345Z sha 5c96806 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-08T00:45:43.473Z sha 5c96806 :: needs maintainer review before merge. :: none

@steipete
steipete marked this pull request as ready for review October 8, 2026 00:39
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Oct 8, 2026
@steipete
steipete force-pushed the deslop/d06c-subagent-raw-owner-20261007 branch from 5c96806 to 7400b12 Compare October 8, 2026 04:13
@steipete

steipete commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Exact-head CI attribution for 7400b120685482836190d9e1676ac3311840d24d, run 37726433932, attempt 1.

The exhaustive check-run census contains 133 completed checks: 77 success, 53 skipped, 1 neutral, 2 failures; no cancelled or pending checks. Both failures are attributed individually below. The dependency and security-sensitive review statuses succeeded; the legacy CI status mirrors the aggregate failure.

  1. checks-node-changed — job 113145843786. The native-cancellation E2E failed replacement registration with SubagentRegistryWriteError: Queued subagent registry persistence failed: Subagent registration owner changed during preparation. This is a preexisting startup race: the test awaits mandatory sidecars through startupSettled, while post-ready observers can activate subagents later. Gateway binding republishes an original run after a replacement captured ownership. The unchanged registration guard correctly rejects that stale preparation.

    On pinned main b9533fbd155b0d0b455b23825d9e3c32f3a1eb7a, the original six-target CI sequence passed. A separate controlled diagnostic delayed the real post-ready activation until the replacement's first preparation assertion returned, retaining the E2E's original assertions. It then reproduced the exact queued error at the worker-dispatch boundary. Publication traces identify bindSubagentRunGatewayOwners as the concurrent publisher. This ordering occurs before the restore metadata-read changes in this PR; the registration, persistence, memory guard, Gateway binding owner, and failing E2E are unchanged. No production failure was mocked or injected.

    The same job also reported an unhandled STATE_DATABASE_READ_ADMISSION_INVALIDATED rejection, OpenClaw state database read admission is closed, through subagent-registry-run-wait.ts:104/443. A second diagnostic on the same main revision reused the existing real-registry restart fixture and its retry-release barrier, closed the current default state database through its native async owner, held resource cleanup open, and advanced the existing fake timer by 25ms. All selected test assertions passed, but Vitest correctly exited 1 for that identical unhandled rejection. The extended stack identifies the unchanged retry callback at subagent-registry-run-wait.ts:135, which checks run/lifecycle identity but starts a new wait without revalidating its retained database admission. State capture at line 104 is outside the wait's try block. This reproduction adds no candidate production code.

    The hosted stack is truncated before the retry caller, so it does not independently identify that callback. The diagnostic proves the same secondary defect exists on main. Separately, inspection of this PR's new resume and restore reads confirms that they revalidate state admission immediately after each await and before synchronously starting a wait; they cannot introduce this uncaught capture through a delayed read. The primary and secondary diagnostics were separate controlled probes, not a claim that the unmodified main sequence failed.

    The 15 test, startup, registration, wait, publisher and read-admission source files compared for attribution are byte-identical between the PR and pinned main, and remain identical on freshly fetched main 2b988ee83444f08ccaf37aa5e98f370726c75f6e. All temporary diagnostic patches were reversed, with clean source verified afterward. Linux/Hetzner, Node 24.19.0, two-CPU affinity; secondary proof took 67.27 seconds through the repository test wrapper. No timeout, retry, skip, assertion, or production guard was weakened.

  2. openclaw/ci-gate — job 113147280034. This is the aggregate of the above failed job, not an independent product failure. All other exact-head checks completed successfully, neutrally, or as configured skips.

The PR's final source tree passed the complete changed-file checker, all 27 test-type graphs, production types, three unused-export scans, lint/guards, 162 focused/boundary tests, and zero runtime/Madge cycles. The full subsystem and build proof, with exact revision qualifications, remains in the PR body. No hosted rerun was requested merely to obtain green.

Under the campaign's authorized inherited-failure exception, this evidence supports an admin squash pinned to the exact head above. The startup-registration race and stale state-admission retry remain separate main-owner follow-ups; neither is fixed or hidden by this PR.

@steipete
steipete merged commit 027dd4c into main Oct 8, 2026
142 of 145 checks passed
@steipete
steipete deleted the deslop/d06c-subagent-raw-owner-20261007 branch October 8, 2026 06:25
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 9, 2026
…up (openclaw#166845)

* fix(subagents): preserve recorded owners through reconciliation and cleanup

* fix(subagents): retain restored wake ownership across worker reads

* test(subagents): provide recovery runtimes in sweep fencing fixtures

* refactor(subagents): simplify sweep scope references
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 13, 2026
…166845)

Upstream made orphan reads async (resolveSubagentRunOrphanReason returns a
worker read, driven by createSubagentResumeReader) and carries recoveryCurrent
into orphan settlement. Kept on top of that:
- F2: armed spawn rows are deferred before any orphan read, and again when an
  async read completes after the row was armed.
- a retained required completion delivery is never settled as an orphan; the
  resume skips the read and goes to the ordinary path.
- handleOrphanedSubagentResume now takes the resolved reason (+ host currency).
- sweep delete re-reads the frozen session identity (worker-backed) before the
  continuation guards and again before dispatch, since isCurrent is sync.
- restore keeps the accepted-spawn-rollback guard, reusing upstream's read.
Tests: resume-orphan harness passes the resolved reason (+ a null-reason case);
orphan-collector mock returns the now-async session entry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Jhynq2GVpzuVQQieebEubg
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 13, 2026
… repairs

Step 12 conflicts: command-queue (upstream's finally-settled lane pump; our
lane-idle waiter notify inside the current-generation release),
session-event-wake (our extracted types; upstream's drain listener),
run-attempt-dispatch (upstream's selectedPromptTarget captured before our
resolveEmbeddedAttemptSessionTarget), subagent-spawn-contract and
sqlite-lifecycle imports, sweeper (upstream's phase buckets + our rollback
candidates), embedded-candidate (runBaseParams is now flat), reply-state and
execution-results tests (upstream removed low-value tests; our continuation
assertions kept), worker inventory regenerated.

Repairs for regressions my earlier steps introduced (my suite filter had
counted 'N failed | M passed' lines as green; reclassified against the
pre-absorb head f4675cf and plain upstream at each cut):
- step 3 sweep delete: drop the extra pre-dispatch identity re-check
  (the delete is already CAS'd); a failed identity read now defers to that CAS
  instead of skipping the delete. Restores upstream's call shape and
  archive retry behaviour.
- step 3 owner rule (openclaw#166845) carried into our continuation readers: an
  agent-scoped key names its own owner (owner-bound announce loader,
  continuation owner-session loader, child continuation entry read).
- step 3 test alignment: custody fixtures give the recovery runtime
  prepareRestartRecovery; persistence resume asserts the batch the settling
  wake received (resume reads are async now); orphan completion carries
  recoveryCurrent.
- step 8: drop a duplicated session-hooks-context entry from the worker test
  path list (ci-test-timings duplicate-ownership error).
- step 10: restart-sentinel delivery reads its session target in the worker
  and re-proves queue admission after the read (as upstream openclaw#167113); our
  continuation delivery suite now routes worker reads and plain-notice session
  events through the shared harness, and its plain-row cases assert upstream's
  ordinary session-event handoff instead of enqueue+heartbeat.
Checks: tsgo core/extensions/core-test/extension-test clean. Previously red,
now green: subagent-announce 12/12, sweeper-recovery 42/42, archive.e2e 19/19,
persistence.resume 24/24, launch-dispatch-custody 6/6,
spawn-acceptance-custody 22/22, orphan-collector 3/3, ci-test-timings 212/212,
restart-sentinel system-event-owner 10/10, continuation-delivery 14/14.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Jhynq2GVpzuVQQieebEubg
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 14, 2026
…s scoped session key

Absorb step 12 (23e9574) carried upstream openclaw#166845's owner rule into our
continuation entry loader: an agent-scoped key names its own owner, so the
recorded agent id was dropped for scoped keys. The owned read
(loadSessionEntryByKey -> tryResolveSubagentRequesterAgentId) answers a
contradicting pair with "no entry" rather than an error, so a continuation
could chain from a child whose persisted owner disagrees with its key.

The loader now keeps upstream's rule when the recorded id agrees (or is
absent) and throws when it contradicts the scoped key, restoring our
fail-closed guard.

Proof: subagent-announce.continuation "fails closed when the persisted child
owner mismatches the session key" 13/13 with the fix; 1 failed/12 with the
fix reverted (red since step 12; the per-step lists never ran it); 13/13
reapplied. 38 announce/owner neighbour suites green at step 22.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Jhynq2GVpzuVQQieebEubg
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 14, 2026
…the test's entry

Since absorb step 3 (openclaw#166845) the subagent sweeper reads child sessions with
readSessionEntryReadOnlyInWorker. This suite still mocked only
loadSessionEntryReadOnly, so the child looked missing and the sweep never
reached the authoritative-custody gate the test asserts ("keeps the session
while authoritative custody is live even when the projection is clear").

The worker read now returns the same entry the accessor mock serves. No
assertion changed: the custody check must still be called and the session
must still survive the sweep.

Proof: 3/3 with the mock; 1 failed/2 without it (red since step 3).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Jhynq2GVpzuVQQieebEubg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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.

1 participant