Skip to content

[ENG-20801] fix(agents): sub-agent resumed twice after a gateway restart - #269

Merged
orswn merged 8 commits into
boonfrom
okka/ENG-20801/subagent-double-resume
Oct 7, 2026
Merged

orswn merged 8 commits into
boonfrom
okka/ENG-20801/subagent-double-resume

Conversation

@orswn

@orswn orswn commented Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator

Related: ENG-20801, #266

What Problem This Solves

Fixes an issue where a sub-agent that was interrupted by a gateway restart would be resumed twice after the gateway came back. The sub-agent repeated its interrupted work, including any tool calls with side effects, and the parent's answer arrived late.

Seen on a test host running 2026.6.34-boon.2 after openclaw gateway restart while a sub-agent was running a 90 s shell command:

09:12:04.186 found orphaned subagent session: agent:main:subagent:1f2b0d13… (run=af58e3d4…)
09:12:04.650 resumed orphaned session: agent:main:subagent:1f2b0d13…
09:12:05.889 found orphaned subagent session: agent:main:subagent:1f2b0d13… (run=c25535eb…)
09:12:06.236 resumed orphaned session: agent:main:subagent:1f2b0d13…
09:12:07.904 orphan recovery complete: recovered=1 failed=0 skipped=1
09:12:08.203 orphan recovery complete: recovered=1 failed=0 skipped=1
09:13:41.395 lane wait exceeded: lane=session:agent:main:subagent:1f2b0d13… waitedMs=93571

The command ran twice. The parent got one answer about 94 s later than needed.

Why This Change Was Made

Two recovery scans run at boot: one when sub-agent runs are restored from disk and one from the post-ready startup sidecar. The 1 s debounce merges them only when they are queued close together. On a host that starts Slack, Teams, and Google Chat during boot they were about 1.7 s apart. Each scan cleared abortedLastRun only after its resume finished, so the second scan resumed the same child again. A loaded gateway can also accept a resume after the 10 s call timeout; the retry then sent a new random idempotency key and started a second run.

The fix has these parts:

  • In-process claim. A scan claims a child session in a process-wide set before resuming it and releases the claim when that attempt ends. Before claiming, it re-reads the child entry from the session store instead of its own cached copy, so a scan that was busy with another child does not act on a stale flag. A scan that finds another scan's claim counts the child as deferred and its schedule retries later; a deferred child is never finalized as failed.
  • Stable resume key. The resume idempotency key is derived from the child session key, the current gateway lifecycle, and the child's recovery marker (last accepted attempt time and count). Every resume of one interruption inside one gateway lifecycle sends the same key, so the gateway returns the run it already accepted instead of starting another one. This covers a resume accepted after the call timeout and a later scan after a failed store write. The key changes once an accepted resume is recorded, so a later interruption still gets a new run. It also changes on an in-process gateway restart: the new runtime has an empty dedupe map, and agent.wait results stay cached at module scope for 10 minutes, so reusing the old run id could let the registry read the old run's result and end the new run's record early. The session id is not part of the key because other writers can change it before a retry.
  • Late-accepted resume. When a resume call fails, the scan remembers the key it sent and the run it was sent for. If a later scan finds that run with the abort flag already cleared and computes the same key, the gateway accepted the call late and the resumed run has started. The scan then moves the registry to that run (the gateway uses the key as the run id) and records the attempt as a confirmed resume does, instead of skipping the child. The old record is not ended as a failure while the resumed run works, and a later interruption still gets a new key. A different run on the child, such as a steer, or a key from an earlier gateway lifecycle, is not taken over.
  • Boot marking. At boot the registry marks crashed sub-agent sessions so recovery resumes them. That loop awaits a store write per child and iterated the live run map, so on a slow host it could reach the replacement run of a child that a scan had just resumed, read the child from its pre-resume cache, and mark it as crashed again. It now works on a snapshot of the restored runs and leaves runs that changed during the loop alone.

Scheduling and the debounce are unchanged.

Not covered:

  • The clear write can drop an abort mark that the resumed run wrote meanwhile. This predates the change and is noted in the code.
  • A resume accepted after the timeout of the schedule's last attempt is not tracked, because no later scan visits the child. Its old record ends as a failed recovery. This is noted in the code.
  • After an in-process gateway restart, a late end event from the interrupted run can set the abort flag again on the resumed run, and a later scan can resume it again. Gateways supervised by systemd do not restart in process: the restart signal restarts the whole process.

User Impact

A sub-agent cut off by a restart is resumed once. Its tool calls are not repeated, and the parent's answer is not delayed by a second run.

Evidence

Local reproduction before the fix

Local gateway on the previous build, CPU limited to 5% during the restart to match a loaded host. Prompt: a sub-agent runs sleep 90; echo <token>; the gateway is restarted while the command runs.

Measure Value
Restored-run mark to gateway ready 2,900 ms (about 80 ms without the CPU limit)
Gap between the two scans finding the child 202 ms
Resume calls that timed out but were accepted 1 (gateway timeout after 10000ms)
resumed orphaned session lines for the one child 2
Times the child ran sleep 90 after the restart 2 (two echo tokens, 95 s apart)
lane wait exceeded on the child session 94,897 ms
Parent answer delay caused by the second run 100.6 s
Work item duration for a 90 s command 6 min

before-fix-double-resume.png

Randomized interleaving test

A local randomized test (not committed) runs 2 to 3 overlapping recovery schedules over 1 to 3 interrupted children with random delays. It injects store write failures, gateway failures before acceptance, gateway timeouts after acceptance, and session id rotation. The mocked gateway dedupes on the idempotency key as the real handler does, and an accepted run clears the abort flag after a random delay, as a real run start does. A seed fails when any child is started more than once or is left with abortedLastRun set.

Build Seeds Faults Failed child outcomes
Before this PR 300 on 564
Before this PR 300 off 582
In-process claim only 300 on 213
In-process claim only 300 off 0
This head 1,000 on 0
This head 300 off 0
This head 500 doubled 0

On this head the gateway dedupe absorbed 909 repeated resumes across the faulty runs. No child was started twice. The test also checks that the registry tracks the run that actually started: 0 misses on this head, against 42 of 300 seeds on the commit before late-accepted resumes were tracked. The test models one gateway lifecycle; the restart case is covered by the unit test above.

Unit tests

New tests in src/agents/subagent-orphan-recovery.test.ts:

  • resumes an interrupted child once when a second scan overlaps the first resume
  • resumes each interrupted child once when overlapping scans cover two children
  • lets a later scan retry after a failed resume releases the claim
  • reuses the idempotency key when a resume is retried after a gateway timeout
  • reuses the idempotency key when the timed-out resume rotated the session id
  • reuses the idempotency key when the clear write fails after an accepted resume
  • uses a new idempotency key for a new interruption after an accepted resume
  • uses a new idempotency key after a gateway restart when the attempt was not recorded
  • uses different idempotency keys for different children
  • tracks a resume the gateway accepted after the call timed out
  • records the attempt of a tracked late-accepted resume so a new interruption gets a new key
  • forgets a timed-out resume once its run is finalized as failed
  • does not take over a steer run that replaced the run of a timed-out resume
  • does not track a timed-out resume from an earlier gateway lifecycle
  • retries a scheduled scan that deferred a child behind another scan's claim

New tests in src/agents/subagent-registry.test.ts:

  • does not mark the new run of a child resumed while restored runs are being marked
  • holds the new run of a child resumed while its own crashed mark is being written

Local runs:

Check Result
subagent-orphan-recovery.test.ts 36 passed
Sub-agent registry (4 files), restart resume, and startup tests 100 + 172 passed
Gateway agent and agent-wait-dedupe tests (dedupe behavior relied on) 366 passed
src/infra/agent-events.test.ts (lifecycle generation) 30 passed
oxfmt --check, oxlint, node scripts/run-tsgo.mjs, git diff --check clean

Runtime check after the fix

Same local setup and prompt as the reproduction. Run on 16ce993e997 (claim, stable key, deferred retry). Run ids come from the registry and the run files; sleep 90 runs come from a process sampler in the gateway's cgroup.

Scenario CPU limit Scans overlapped on the child Run ids per child sleep 90 after each restart Parent answers Result
One child 5% yes, second scan deferred 1 1 1 pass
One child, repeat 5% yes, second scan deferred 1 1 1 pass
One child, gateway timeout on the resume call 3% yes, second scan deferred 1 1 1 pass
One child, scans did not overlap 3% no 1 1 1 pass
Two children in parallel 5% no, one scan per child 1 each 1 each 1 with both outputs pass
Two restarts in a row none no 1 per restart, new id each time 1 and 1 1 pass
Baseline none no 1 1 1 pass

On 8b58aec2b22 (adds the boot-marking fix):

Scenario CPU limit Scans overlapped on the child Run ids per child sleep 90 after each restart Parent answers Result
One child 5% yes, second scan deferred 1 1 1 pass
Two children in parallel, resume of B timed out 5% no 1 each 1 each 1 with both outputs pass
Two children in parallel, repeat, resume of B timed out 5% no 1 each 1 each 1 with both outputs pass

0 lane wait exceeded lines in all 13 runs, including the runs below. Before the fix the same lane waited 94,897 ms.

after-fix-single-resume.png

The two-children run also logged a crashed mark for child A's resumed run, 15 s after its resume. No second resume followed only because that run was dispatched 2 ms after the mark, and a run start clears the mark. That race is the boot-marking fix above. In the two later two-children runs the boot loop was still running 2.6 s and 3.9 s after child A's resume, and it marked only original runs: 0 crashed marks on resumed runs.

On 54a60a957c9 (adds late-accepted resume tracking). The head after it changes only that path, which did not run here:

Scenario CPU limit Resume call timed out Run ids per child sleep 90 after each restart Parent answers Result
Two children in parallel 5% child B, not accepted, retried 1 each 1 each 1 with both outputs pass
Two children in parallel, repeat 5% no 1 each 1 each 1 with both outputs pass
One child, scans overlapped 3% yes, not accepted, retried 1 1 1 pass

Each child's registry row matched the run after the restart and ended complete. No lost active execution context or Automatic recovery failed lines. Neither timed-out call had been accepted, so the late-accepted path did not run here; the unit tests and the randomized test cover it.

after-fix-two-children.png

An in-process restart was not exercised: under systemd the restart signal restarted the whole process.

After a gateway restart, two orphan-recovery scans can overlap: one is
scheduled when sub-agent runs are restored from disk, and one by the
post-ready startup sidecar. The 1 s schedule debounce merges them only
when they are queued less than 1 s apart, which is not the case on a
host that starts several channel providers during boot.

Each scan kept its own set of resumed sessions and cleared
abortedLastRun only after the resume call and the store write finished.
A second scan that read the store in that window resumed the same child
session again, so the child repeated its interrupted work, including
any tool calls, and the parent waited for the second run.

Claim a child session key in a process-wide set before resuming it, and
release the claim when that iteration ends. Before claiming, re-read the
child entry from the session store instead of the scan's own cache, and
use that entry for the recovery gate and the resume. A scan that was
waiting on another child then does not act on a stale abortedLastRun
after the other scan has already resumed the session.

Three older gaps are left as is and noted in the code: a resume that the
gateway accepts after the call timeout is started again by the retry, a
failed store write after an accepted resume lets a later scan resume
again, and the unconditional clear can drop an abort mark that the
resumed run wrote meanwhile.
@orswn
orswn requested a review from a team October 7, 2026 10:15
@orswn

orswn commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

@cubic-dev-ai review

@cubic-dev-ai

cubic-dev-ai Bot commented Oct 7, 2026

Copy link
Copy Markdown

@cubic-dev-ai review

@orswn I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 2 files

Reply with feedback, questions, or to request a fix.

Fix all with cubic | Turn on auto-fix | Re-trigger cubic

Comment thread src/agents/subagent-orphan-recovery.ts Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 2 files

Reply with feedback, questions, or to request a fix.

Fix all with cubic | Turn on auto-fix | Re-trigger cubic

Comment thread src/agents/subagent-orphan-recovery.ts Resolved
Comment thread src/agents/subagent-orphan-recovery.ts Resolved
The in-process claim stops two scans from resuming one child at the
same time, but a resume can still be sent twice for one interruption:

- the gateway accepts the resume but answers after the 10 s call
  timeout, and the retry sends a new random idempotency key;
- the resume is accepted but the store write that clears
  abortedLastRun fails, and a later scan resumes again.

Derive the resume idempotency key from the child session key and its
recovery marker (last accepted attempt time and count). The key stays
the same for every resume of one interruption, so the gateway returns
the run it already accepted instead of starting another one. It changes
once an accepted resume is recorded, so a later interruption still gets
a new run. The session id is left out because the gateway can rotate it
while accepting the resume.

A scan that finds another scan's claim no longer drops the child: it
counts it as deferred and its schedule retries, without finalizing it.
Before, if the claim holder then failed on its last retry, the child
ended as failed even though the other schedule could still resume it.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 2 files (changes from recent commits).

Requires human review: Auto-approval blocked because this review re-detected 1 unresolved issue already reported by Cubic.

Fix all with cubic | Turn on auto-fix | Re-trigger cubic

Comment thread src/agents/subagent-orphan-recovery.ts Resolved
orswn added 4 commits October 7, 2026 18:10
The resume idempotency key did not change across an in-process gateway
restart when the previous attempt was never recorded, for example after
a failed store write or an explicit session reset. The new runtime has
an empty dedupe map, so it started a new run under the old run id.
agent.wait results are cached at module scope for 10 minutes, and only
the new run's start event drops them, so the registry could read the
old run's terminal result and end the record while the new run kept
going.

Add the agent event lifecycle generation to the key. It rotates on
every in-process restart, so retries inside one gateway lifecycle still
dedupe and a restart always gets a fresh run id. The key is now
computed right before the resume call so it uses the generation that
is current when the call is sent.

Note a pre-existing gap at the skip after a fresh store read: a resume
that timed out after the gateway accepted it, and whose run already
started, is not remapped, so the registry keeps the old run id until
the sweeper ends it.
The rotated session id test compared the two resume keys without
checking them, so it would also pass if no idempotency key was sent.
Assert both keys have the UUID shape first.
At boot the registry marks crashed sub-agent sessions with
abortedLastRun so orphan recovery resumes them. The marking loop
iterates the live run map and awaits a store write per child. On a
slow host the post-ready recovery scan can resume a child during
those awaits. The resume replaces the child's run in the map, and the
loop then visits the replacement. It reads the child entry from the
loop's store cache, loaded before the resume, so the running child
looks crashed and is marked again. A later scan can then resume it a
second time.

Snapshot the restored runs before the loop. A run that is not in the
snapshot, or whose record changed, came from a resume or a new spawn
during the loop: it already has a completion wait, so hold it and do
not mark it.
Orphan recovery resumes a child with a 10 s gateway call. If the
gateway accepts the resume after the call has timed out, the resumed
run starts and its start write clears the child's abort flag. The
retry then reads the cleared flag and skips the child, so the registry
keeps the old run. The sweeper or the last-attempt finalize later ends
that old run as a failure while the resumed run still works, and the
parent can start the task again.

Remember the idempotency key of each resume call that fails, bound to
the run it was sent for. The gateway uses that key as the run id. When
a later scan finds the same run with the flag cleared and computes the
same key, it remaps the registry to that run instead of skipping. A
different run on the child, such as a steer, or a key from an earlier
gateway lifecycle, is not taken over.

A failed call on the schedule's last attempt is not covered, because
no later scan visits the child.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 2 files (changes from recent commits).

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread src/agents/subagent-orphan-recovery.ts Resolved
@orswn

orswn commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

@cubic-dev-ai review

@cubic-dev-ai

cubic-dev-ai Bot commented Oct 7, 2026

Copy link
Copy Markdown

@cubic-dev-ai review

@orswn I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 4 files

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread src/agents/subagent-orphan-recovery.ts Resolved
Comment thread src/agents/subagent-orphan-recovery.ts Resolved
Comment thread src/agents/subagent-orphan-recovery.ts Resolved
When a scan takes over a sub-agent resume that the gateway accepted
after the call timed out, it did not write the recovery marker that a
confirmed resume writes. The resume key is derived from that marker,
so a later interruption of the same child in the same gateway
lifecycle sent the same key, and the gateway returned the already
accepted run instead of starting a new one.

Record the attempt on takeover, with the attempt number of the call
that timed out. Keep the attempt with the remembered call, and forget
the call once its run is finalized as failed.
@orswn

orswn commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

@cubic-dev-ai review

@cubic-dev-ai

cubic-dev-ai Bot commented Oct 7, 2026

Copy link
Copy Markdown

@cubic-dev-ai review

@orswn I have started the AI code review. It will take a few minutes to complete.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 4 files

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread src/agents/subagent-registry.ts Resolved
Comment thread src/agents/subagent-orphan-recovery.ts Resolved
Cover a resume that replaces a child's run while the boot loop awaits
the crashed mark of that same run. The loop iterates the live run map,
so it still reaches the replacement, finds it missing from the
snapshot of restored runs, and holds it. Only one completion wait is
armed for the new run.
@orswn
orswn merged commit cc8427e into boon Oct 7, 2026
143 of 145 checks passed
@orswn
orswn deleted the okka/ENG-20801/subagent-double-resume branch October 7, 2026 14:02
orswn added a commit that referenced this pull request Oct 7, 2026
…4-boon.3 (#271)

Cut the fork release that ships #269 (ENG-20801), the only commit on
boon since v2026.6.34-boon.2. An interrupted native sub-agent is now
resumed once after a gateway restart, instead of twice on a loaded host.

Bump root package.json and npm-shrinkwrap.json, all 135 plugin
manifests, and the version and openclaw peer floor in every extension
npm-shrinkwrap.json. Add the 2026.6.34-boon.3 CHANGELOG.md section.
No dependency or source changes.
@orswn

orswn commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator Author

Post-release check on 2026.6.34-boon.3 (#271), on an internal test host with Boon Web, in a private chat.

The parent spawns one sub-agent that runs sleep 90; echo <token>. While the command runs, the gateway is restarted with openclaw gateway restart. The same check on 2026.6.34-boon.2 is the one that showed the double resume.

boon.2 boon.3, run 1 boon.3, run 2
Second recovery scan resumed the child again, 1.6 s after the first resume already in progress, deferred, 1.5 s after the first resume already in progress, deferred, 1.4 s after the first
resumed orphaned session lines 2 1 1
Command runs after the restart 2 1 1
Parent answers 1, about 94 s late (lane wait exceeded, waitedMs=93571) 1 1
lane wait exceeded, lost context, recovery failed 1 0 0
Child session after the run abortedLastRun: false, automaticAttempts: 1 abortedLastRun: false, automaticAttempts: 1

Run 2 gateway log, UTC:

14:41:16.8  received SIGTERM; restart blocked by the active sub-agent task
14:41:46    new gateway process
14:41:58.5  marked crashed subagent session for restart resume
14:42:03.9  resumed orphaned session
14:42:05.3  skipping orphan recovery ...: resume already in progress
14:42:05.3  orphan recovery had 0 failure(s) and 1 deferred; retrying in 10000ms
14:42:06.7  orphan recovery complete: recovered=1 failed=0
14:43:47.9  parent answer posted

Sub-agent restart on 2026.6.34-boon.3: running before the restart, still running after it, one answer

Run 2 recording, 30 s, sped up:

ENG-20801-boon3-subagent-restart.mp4

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants