Skip to content

fix(agents): recover delegated task finals across gateway restarts - #137606

Merged
steipete merged 5 commits into
mainfrom
codex/stable-review-f06-landing-20260903
Sep 4, 2026
Merged

steipete merged 5 commits into
mainfrom
codex/stable-review-f06-landing-20260903

Conversation

@steipete

@steipete steipete commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor
Additional instructions

MUST: Keep Allow edits from maintainers enabled for this PR so maintainers can help update the branch when needed.

What Problem This Solves

Fixes an issue where users waiting for delegated work could receive no final answer when Gateway restart overlapped a deferred completion. Finished children could lose their requester wake during drain, exhaust it against a closed Gateway, or remain attached to the old instance. Separate requester turns could also stall when distinct caller closures represented the same live Gateway.

Why This Change Was Made

The existing registry lifecycle now retains and reactivates durable wakes: admission deferral spends no attempt, restored terminal rows bind to the current instance, and exact row/batch/generation checks fence old callbacks while preserving every captured caller's authority. Interrupted built-in completion turns reuse their existing keyed user only after fresh writer/session/physical-tail validation; projection keeps one copy without suppressing later steering or follow-up writes, and an accepted dispatch is not mistaken for a recorded visible final.

User Impact

Delegated-task finals can recover through drain, restart and delayed activation without reviving old active claims. Overlapping requester turns retain their ownership. Retry budgets and completed-delivery receipts remain intact; no configuration, protocol, dependency or schema change is introduced.

Evidence

Fresh integrated proof

The frozen integration is committed as 7a437c9712e012f8d0604f684291eae211d53acc, incorporating main through 0a1e564d34580935a955c434645103b3fa41a389. All 36 candidate-file hashes are unchanged by the merge commit.

Check Observed result
Owner/sibling tests 43 files, 1,704 passes, 0 skips, including startup/restore and incompatible-binding lifecycle coverage
Complete 36-file changed gate Passed in 1465.16s, including canonical core/core-test/test-root typechecks, dead-export scans and lint
Full runtime and Control UI build Passed in 689.94s
One real Gateway/SQLite/served-UI mixed-distinct-alpha flow Passed in 203.56s; eight actual HTTP requests to a synthetic local Responses provider

The live flow admitted two distinct requester runs, one yielding and one completing normally. Their children overlapped, alpha completed first, and one consolidated wake produced one visible final. After 65,101ms of ordinary sweep observation, both child rows were delivered with wake/requester-run state cleared. Gateway, browser and provider stopped normally, with zero cleanup errors or observed surviving descendants. This is fresh caller-context composition proof, not fresh replacement/restart proof.

Source/index, runtime, fixture, static-helper and dependency-payload checks matched before/after. Retained QA helpers came from the earlier helper checkout, with their static closure and package payloads checked against the new runtime's dependencies; this is not an unbounded dynamic-import identity claim. Browser proof used verified Developer-ID-signed Google Chrome and a fresh ephemeral context, never a saved profile. Both fresh screenshots were inspected as synthetic-only; they are not the historical media below.

Original harness failures remain recorded: an overlong task-owned Unix-socket path and a reporter-path accounting error. The short private temporary-directory correction resumed only failed/unexecuted files; the accounting correction did not rerun tests. No product guard, assertion or test deadline was weakened. These failures are not counted as passes.

Historical red/green and media

The original built baseline reproduced the missing final through a real Control UI request, child spawn/yield and natural retry deadline during restart drain. Failing-before regressions cover late/partial restoration, replaced batch members, old-finally races, caller wrappers and closure on the final admitted attempt.

Earlier candidate proof covered original inside-drain recovery and final-attempt replay across forced restart with replacement activation held by a normal plugin service. All 79 samples retained the exact attempt-three wake; recovery reused the same three durable keyed user rows/projections and recorded one visible final before releasing the old response. Those replacement results, and the three real flows previously run on the f1e49edfb85cc integration, remain historical, not added to the fresh totals.

Original baseline failure:

Original restart-drain failure

The same original flow succeeds in this inspected, synthetic-only 50.20-second recording from the earlier b122b21f051c candidate, not the new head:

f06-after.webm

Review dispositions and compatibility

ClawSweeper Rank-up move: incompatible-binding backoff/no-hot-loop coverage. The proposed immediate-loop premise is not supported. The resolver does reject mixed/unrelated bindings, but ordinary scheduler finally calls deadline-only retry, which returns when no future deadline exists. Immediate re-entry consumes a one-shot marker produced only by a separate persisted requester-turn settlement, either normal completion or yield—not by the exception. Individual live/unbound owner fences can also permit terminal bookkeeping despite shared dispatch incompatibility; closed fences retain the wake for later lifecycle work.

The existing registry product-flow matrix passed both completion orders for distinct-live and mixed-unbound bindings through the real resolver/lifecycle, with Gateway/store I/O harnessed. After a sweep and 30 seconds of simulated time it asserts no incompatible consolidated dispatch and both wakes cleared. Deadline, expired-deadline, rearm and pre-admission-rejection scheduler tests also passed. No speculative durable-backoff policy was added. These controls do not claim exhaustive interleavings or exact warning-count coverage; the raw review remains retained.

ClawSweeper Rank-up move: exact-head CI. The fresh local gate passes and exact-head CI for 7a437c9712e012f8d0604f684291eae211d53acc completed successfully: all 125 jobs passed or were intentionally skipped. Recovery fixtures now follow canonical empty-registry startup/activation order. The obsolete spawned-CLI clock override is removed after upstream relative-expiry fixtures; all five CLI children use real time with original arguments/assertions/deadlines. Earlier advancing-clock proof is historical only.

Managed review: all 29 review passes completed; the raw incorrect verdict and two duplicate optional-call/TS2349 reports are retained. Both claims were rejected against installed compiler source, strict-null controls and the passing canonical typecheck graphs; no source workaround or nicer-verdict rerun was used. All 36 candidate files were reviewed, but the managed helper refused the upstream-only src/gateway/server-reload-managed-secrets.ts callee. A separate full local source read does not erase that managed-context gap.

Stored-shape concern: canonical readers/writers/serializers preserve the existing registry payload, transcript/event/message shapes and pending-input custody. Replay adopts the exact existing current user through the recorder with appended: false, without rewriting it or firing a fresh-input commit notification. SQLite close/reopen tests preserve the complete pending wake and durable transcript events, then verify replacement settlement and one later user write. This proves candidate-reader reopening/byte preservation, not a separate older executable opening a candidate-produced database. No migration, schema-version, index, retention or material store-design change is introduced.

Scope, LOC exception and related work

Against pinned main, production is +601/-382 (net +219); tests/support +2320/-739 (net +1581); docs +7/-0. The positive production exception implements the fresh interrupted-turn fence, whole-batch/visible-receipt handoff and per-Gateway restored capacity. It replaces function-identity batching, ID-only async ownership, process-long recovery capacity and broad next-user suppression; the announce-wake owner shrinks 52 lines. Existing resolver, recorder, physical-current-turn and runtime-projection owners are reused. The physical branch/snapshot checks and late descendant recheck protect observed cases, not hypothetical compatibility.

This does not claim authenticated external inference, production-channel delivery, byte-identical whole developer prompts, or cross-crash exactly-once delivery in the already-visible but registry-unsettled window. The Codex continuation owner and terminal-event mapping were checked directly; requester wake ownership remains in the Gateway.

Thanks to Josh Lehman (@jalehman) for the fallback-resolver sibling-settlement diagnosis in #137471. This independently developed lifecycle/replay repair includes that subset without copying a second resolver holder; the smaller contributor PR retains its history and scope. #121195's intentional-quiet product change is distinct and not adopted. #137332 (related #137344) remains the named terminal non-success/projection follow-up. Existing transcript-commit ordering from #134920 is preserved.

Final disposition of the September 4, 09:13 UTC review

The latest ClawSweeper review reports no correctness or security finding. Its exact-head validation request is satisfied by the green CI above and the recorded owner/gate/live proof.

The rebase/rank-up request is skipped after direct main-interaction review, not merely because the branch is mergeable. The complete changed-path intersection between this candidate and observed main ed6e3aabf0ef6cd58a8ee9d9282a6dc6c06cc918 is the registry entry point, its test file, and the already-upstream clock cleanup. The newer registry change synchronously replays the existing idempotent task-status projection before resume exits, explicitly excluding steer-restart. F06 leaves resumeSubagentRun unchanged and binds fresh owners before calling it; task-status projection does not acknowledge the requester wake or publish a second subagent final. Root and an independent reader checked the owner, exact-task mapping, delivery policy and new restore tests. A synthetic merge is conflict-free; it is not being described as an executed merged-runtime test. Repository policy does not require rebasing for drift alone. Native landing still enforces its current-head and merge checks.

The +219 production lines cannot be removed by a single pre-admission check: awaited writer/session preparation can change the exact physical transcript tail or owner before the later commit, so custody must be revalidated at that commit boundary. Existing admission, recorder and projection owners are reused; duplicate policy and old paths are removed. Data compatibility evidence and its older-executable limitation remain stated above. Effective landing delta against the inspected main is production +219, tests/support +1602, docs +7, excluding clock cleanup already landed independently.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Sep 3, 2026
@clawsweeper

clawsweeper Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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 3, 2026
@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 4, 2026, 5:13 AM ET / 09:13 UTC.

ClawSweeper review

What this changes

The PR makes delegated-task final delivery restart-safe by preserving the current requester turn and retaining its original Gateway-instance binding through durable requester-settle recovery.

Merge readiness

⛔ Blocked before merge - 4 items remain

Keep open: the restart-safe requester-final recovery is not included in fetched current main, and no merged PR is verified to supersede it. The reviewed ownership and replay paths are coherent, with no introduced correctness finding identified; merge needs current-main integration and exact-head validation.

Priority: P1
Reviewed head: 7a437c9712e012f8d0604f684291eae211d53acc

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch has focused ownership and replay coverage, but its current-main integration and exact-head validation remain outstanding.
Proof confidence 🦐 gold shrimp (3/6) Not applicable: The external-contributor proof gate does not apply to this MEMBER-authored PR; its supplied recovery scenarios remain supplemental evidence.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The external-contributor proof gate does not apply to this MEMBER-authored PR; its supplied recovery scenarios remain supplemental evidence.
Evidence reviewed 6 items Captured Gateway-owner composition: The wake derives one resolver from every settled row before dispatch and passes that captured resolver into requester delivery, preventing ambient routing from replacing a recorded owner.
Lifecycle ownership fence: Batch transition and completion validate the exact row object, wake generation, and each captured resolver before mutating durable wake state.
Sibling binding coverage: The product-flow test exercises shared, distinct, mixed bound/unbound, and yielded requester cases; distinct owners intentionally do not receive an unsafe consolidated dispatch while their already-delivered child rows settle.
Findings None None.
Security None None.

How this fits together

Subagent completions are stored in the durable registry and can require a final requester wake after a restart. The wake composes the recorded Gateway ownership, dispatches a consolidated requester turn when safe, and records whether delivery settled.

flowchart LR
  A[Subagent completion] --> B[Durable subagent registry]
  B --> C[Requester-settle batch]
  C --> D[Captured Gateway owner]
  D --> E[Requester wake delivery]
  E --> F[Transcript and visible final]
  B --> G[Restart restoration]
  G --> C
Loading

Before merge

  • Resolve merge risk (P1) - Fetched main has overlapping lifecycle and replay changes after this PR's base, so the stale test-merge cannot establish behavior for the merge result.
  • Resolve merge risk (P1) - The bug-fix diff adds 219 net production lines across transcript replay and durable recovery; that growth is justified only if the separate before/after-await ownership checks cannot be absorbed into the existing admission boundary.
  • Complete next step (P2) - Rebase onto current main and provide green exact-head validation for restart recovery and requester-final delivery.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +219, Tests +1581, Docs +7. Total +1807 across 36 files.

View PR surface stats
Area Files Added Removed Net
Source 15 601 382 +219
Tests 20 2320 739 +1581
Docs 1 7 0 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 36 2928 1121 +1807

Review metrics

Metric Value Why it matters
Production versus test delta production +601/-382 (net +219); test-support +86; tests +2234/-739; docs +7 The change is test-heavy but also materially expands the session-replay and lifecycle owner boundary.
Changed files 36 files affected The recovery invariant spans registry lifecycle, embedded-runner replay, Gateway ownership, and restart documentation.

Stored data model

Persistent data-model change detected: serialized state: src/agents/embedded-agent-runner/run/attempt-session-prepare.ts, unknown-data-model-change: src/agents/embedded-agent-runner/run/attempt-session-prepare.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Validate the integrated recovery path (recommended)
    Rebase the branch onto current main and run the restart/replay and requester-final checks on the resulting exact head before merge.

Technical review

Best possible solution:

Rebase onto current main, retain only the owner-bound replay checks needed at each asynchronous boundary, and validate the resulting exact head through the restart and requester-final flow.

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

No current-main execution was performed in this read-only review, but the affected recovery and replay paths are source-reproducible and covered by focused branch scenarios.

Is this the best way to solve the issue?

Yes, the captured-resolver and exact-row approach preserves Gateway-instance ownership rather than falling back to ambient routing; it still needs exact-head integration proof.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add merge-risk: 🚨 message-delivery: Requester-settle wake completion determines whether a consolidated final is dispatched and durably settled.
  • add merge-risk: 🚨 session-state: The PR changes persisted-turn identification, transcript replay, and lifecycle ownership across restart.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The external-contributor proof gate does not apply to this MEMBER-authored PR; its supplied recovery scenarios remain supplemental evidence.
  • remove merge-risk: 🚨 availability: Current PR review merge-risk labels are merge-risk: 🚨 session-state, merge-risk: 🚨 message-delivery.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: A failed recovered requester final can leave an agent workflow without its expected continuation after restart.
  • merge-risk: 🚨 session-state: The PR changes persisted-turn identification, transcript replay, and lifecycle ownership across restart.
  • merge-risk: 🚨 message-delivery: Requester-settle wake completion determines whether a consolidated final is dispatched and durably settled.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The external-contributor proof gate does not apply to this MEMBER-authored PR; its supplied recovery scenarios remain supplemental evidence.

Evidence

Acceptance criteria:

  • [P1] Run the restart/replay and requester-settle test surfaces on the rebased exact head.
  • [P1] Validate an isolated Gateway restart where a pending requester final resumes under the current Gateway owner.

What I checked:

Likely related people:

  • unknown: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Jacqueline Henriksen: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Sho Jikumaru: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Rebase and validate the exact integrated head through the restart and requester-final flow.

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 (2 earlier review cycles)
  • reviewed 2026-09-03T22:34:15.150Z sha 4290869 :: blocked before merge. :: none
  • reviewed 2026-09-04T03:53:23.250Z sha ada5a0b :: blocked before merge. :: [P1] Defer incompatible resolver batches before rescheduling

@clawsweeper clawsweeper Bot added 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: 🐚 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 4, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 4, 2026
@steipete
steipete merged commit acdd2bb into main Sep 4, 2026
199 checks passed
@steipete
steipete deleted the codex/stable-review-f06-landing-20260903 branch September 4, 2026 09:38
@steipete

steipete commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 5, 2026
…penclaw#137606)

* fix(agents): recover delegated task finals across gateway restarts

* test(agents): model gateway activation before recovery fixtures

* test(release): preserve elapsed time in fixture clocks
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 maintainer Maintainer-authored PR merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. 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. 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