Skip to content

fix: settle restored subagent tasks - #136780

Merged
fuller-stack-dev merged 5 commits into
mainfrom
fix/task-restart-cancellation-settlement
Sep 4, 2026
Merged

fuller-stack-dev merged 5 commits into
mainfrom
fix/task-restart-cancellation-settlement

Conversation

@fuller-stack-dev

Copy link
Copy Markdown
Member

Summary

  • replay the terminal detached-task projection when restoring completed subagent runs
  • keep interrupted-recovery ownership fences intact
  • add a restart regression covering a completed child with a stale running task row

Root cause

Subagent completion and detached-task state are persisted separately. A Gateway restart could occur after the child result and cleanup state reached disk but before the task projection was finalized. During restore, resumeSubagentRun returned immediately for cleanup-complete rows, leaving the task permanently marked running.

Testing

  • pnpm test src/agents/subagents/registry/subagent-registry.test.ts (153 passed)
  • pnpm test:changed (153 passed)
  • pnpm check:changed
  • focused regression verified red before the fix and green after it

Worked on by

@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.

@fuller-stack-dev
fuller-stack-dev marked this pull request as ready for review September 3, 2026 00:57
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S maintainer Maintainer-authored PR labels Sep 3, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. 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, 3:07 AM ET / 07:07 UTC.

ClawSweeper review

What this changes

This PR restores completed subagent task status after a Gateway restart while leaving a steer-restarted successor task writable.

Regression provenance

Possible regression — probable (reproduction; reviewed change). No predecessor PR is attributed.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep open for normal maintainer merge: current main still lacks this repair, and the patch reuses the canonical terminal-task finalizer without bypassing restart or steer-restart ownership fences.

Priority: P1
Reviewed head: 5e11b54ef0a5b91019f7ee79ba2900bc62280e67

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, source-aligned recovery repair with real cold-start evidence and no supported correctness finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The changed owner is registry restoration, which invokes the production run-scoped task finalizer; the contributor’s isolated real Gateway seed/start/readback trace observes the repaired running-to-succeeded transition and preserves the steer-restart negative control.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): The changed owner is registry restoration, which invokes the production run-scoped task finalizer; the contributor’s isolated real Gateway seed/start/readback trace observes the repaired running-to-succeeded transition and preserves the steer-restart negative control.
Evidence reviewed 7 items Introduced restoration repair: The PR adds terminal-task replay before the existing cleanup-complete return, so a completed child can settle its stale running task during restoration.
Canonical finalization guard: The reused finalizer requires a terminal timestamp, outcome, and captured completion state before writing through existing run-scoped task APIs.
Recovery-owner fence: The restorer skips generic resume for restart-recovery, kill-intent, kill-reconciliation, and aborted-session rows, leaving those specialized owners in control.
Findings None None.
Security None None.

How this fits together

Subagent execution records and detached-task status are persisted separately. During Gateway startup, registry restoration must reconcile a completed child into the operator-visible task state without allowing a retired run to overwrite its successor.

flowchart LR
  A[Persisted subagent run] --> B[Gateway startup]
  B --> C[Registry restoration]
  C --> D{Captured terminal result?}
  D -->|Yes| E[Canonical task finalizer]
  D -->|Steer restart| F[Keep successor writable]
  E --> G[Visible terminal task]
  F --> H[Visible running successor]
Loading

Before merge

  • Resolve merge risk (P1) - This startup path mutates persisted task state; its safety depends on the existing generation-bounded task resolver continuing to select only the completed run’s canonical task.
Agent review details

Security

None.

PR surface

Source +11, Tests +111. Total +122 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 11 0 +11
Tests 1 111 0 +111
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 122 0 +122

Review metrics

Metric Value Why it matters
Production vs test delta production +11, tests +111 The production change is a single recovery-owner call into an existing finalizer; added tests cover terminal replay and the successor ownership fence.

Merge-risk options

Maintainer options:

  1. Accept the covered recovery transition (recommended)
    Land the patch with its completed-child and steer-restart cold-start evidence, which exercises the affected durable task-state boundary.

Technical review

Best possible solution:

Land the restoration replay through the existing run-scoped finalizer, retaining the steer-restart exclusion and the focused cold-start regression coverage.

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

Yes. The supplied isolated Gateway restart trace shows the stale-running baseline and the patched terminal result; current main retains the same missing finalizer replay in the inspected restoration branch.

Is this the best way to solve the issue?

Yes. The patch calls the existing canonical finalizer at the restoration owner rather than duplicating task-status logic, and explicitly preserves the steer-restart ownership boundary.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The changed owner is registry restoration, which invokes the production run-scoped task finalizer; the contributor’s isolated real Gateway seed/start/readback trace observes the repaired running-to-succeeded transition and preserves the steer-restart negative control.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P1: A completed subagent can remain visibly running after restart, leaving operators with incorrect active task state.
  • merge-risk: 🚨 session-state: The PR changes how persisted subagent completion is reconciled into durable detached-task state at startup.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The changed owner is registry restoration, which invokes the production run-scoped task finalizer; the contributor’s isolated real Gateway seed/start/readback trace observes the repaired running-to-succeeded transition and preserves the steer-restart negative control.
  • proof: sufficient: Contributor real behavior proof is sufficient. The changed owner is registry restoration, which invokes the production run-scoped task finalizer; the contributor’s isolated real Gateway seed/start/readback trace observes the repaired running-to-succeeded transition and preserves the steer-restart negative control.

Evidence

What I checked:

Likely related people:

  • Jacqueline Henriksen: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Mert Başar: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-09-03T01:04:16.570Z sha 8c63688 :: blocked before merge. :: [P1] Skip task finalization for restored steer-restart rows
  • reviewed 2026-09-03T10:03:57.955Z sha e8b933c :: blocked before merge. :: none
  • reviewed 2026-09-03T10:41:53.076Z sha 494f4f8 :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 3, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. labels Sep 3, 2026
@fuller-stack-dev

Copy link
Copy Markdown
Member Author

Restart proof and review disposition — head 5e11b54

Responding to the restart-trace request. The implementation still uses the canonical run-scoped task finalizer; this recovery also hardens the steer-restart negative control.

  • Current-main baseline: fa38d78. Its relevant registry/task/startup behavior is unchanged in the PR's refreshed main parent c084611.
  • Published head: 5e11b54 (GitHub reports verified signature).
  • Focused gate: native scripts/pr review-tests 136780 src/agents/subagents/registry/subagent-registry.test.ts, 154/154 passed on this head.
  • Negative control repaired: the retired predecessor fixture now has resultText: null, capturedAt: endedAt. Without completed capture, the previous test could pass without exercising the ownership fence. Removing the fence now fails with expected running, received failed; restoring it passes all 154 tests.

Real cold-start boundary

Ran separate seed, actual Gateway, and readback Node processes with an empty isolated HOME/state/config, no inherited credentials, plugins, channels, or scheduled work. The seed uses production session/task/subagent SQLite APIs. Before-state is read through the read-only SQLite loader, without initializing task runtime. The next process starts production startGatewayServer, waits for startupSettled, checks health HTTP 200 and retained fixture runs, and observes task status. After a clean Gateway close, a third process confirms the persisted result.

Case Baseline after startup/readback Published head after startup/readback
Completed child with cleanup already complete incorrectly stays running succeeded, original endedAt and result preserved
Capture-complete retired steer-restart predecessor running, no endedAt running, no endedAt

Baseline processes: seed 46360, Gateway 46390, readback 46546. Published-head processes: seed 54398, Gateway 54571, readback 54773. All phases exited 0 under their expected baseline/head assertions. Only the isolated proof Gateway was started/stopped.

Scope: this proves recovery from seeded, crash-consistent durable state, not a timed live-provider crash. The negative control proves that the retired predecessor cannot terminalize its task; it does not claim execution of a real replacement successor. No production deployment or daemon change was performed.

Raw baseline task observation
{
  "before": [
    {
      "runId": "proof-completed-child",
      "status": "running"
    },
    {
      "runId": "proof-retired-predecessor",
      "status": "running"
    }
  ],
  "after": [
    {
      "runId": "proof-completed-child",
      "status": "running"
    },
    {
      "runId": "proof-retired-predecessor",
      "status": "running"
    }
  ]
}
Raw published-head task observation
{
  "before": [
    {
      "runId": "proof-completed-child",
      "status": "running"
    },
    {
      "runId": "proof-retired-predecessor",
      "status": "running"
    }
  ],
  "after": [
    {
      "runId": "proof-completed-child",
      "status": "succeeded",
      "endedAt": 1788504208967,
      "summary": "synthetic completed result"
    },
    {
      "runId": "proof-retired-predecessor",
      "status": "running"
    }
  ]
}
Reproduction harness (synthetic state only)

Save as restart-proof.mjs outside the checkout. In a disposable environment with dependencies installed, use a fresh HOME/state directory for each checkout and a minimal local Gateway config with plugins/controlUi/cron disabled. Set OPENCLAW_STATE_DIR and OPENCLAW_CONFIG_PATH to those isolated paths, then run three separate processes:

node --import tsx /absolute/path/restart-proof.mjs "$PWD" seed running 21467
node --import tsx /absolute/path/restart-proof.mjs "$PWD" gateway running 21467
node --import tsx /absolute/path/restart-proof.mjs "$PWD" readback running 21467

Use succeeded rather than running on the patched checkout. Do not point this fixture at a real Gateway state directory.

import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import { pathToFileURL } from 'node:url';

const [repo, mode, expected, portText] = process.argv.slice(2);
const load = (relative) => import(pathToFileURL(path.join(repo, relative)).href);
const terminalRunId = 'proof-completed-child';
const predecessorRunId = 'proof-retired-predecessor';
const requesterSessionKey = 'agent:main:proof-requester';
const cases = [terminalRunId, predecessorRunId];
const startedAt = Date.now() - 5000;
const endedAt = startedAt + 1000;

const { loadTaskRegistryStateFromSqliteReadOnly } = await load('src/tasks/task-registry.store.sqlite.ts');
const snapshot = () => cases.map((runId) => {
  const task = [...loadTaskRegistryStateFromSqliteReadOnly().tasks.values()].find((record) => record.runId === runId);
  assert.ok(task, `missing task ${runId}`);
  return { runId, status: task.status, endedAt: task.endedAt, summary: task.progressSummary };
});

if (mode === 'seed') {
  const { createRunningTaskRun } = await load('src/tasks/detached-task-runtime.ts');
  const { saveSubagentRegistryToSqlite } = await load('src/agents/subagents/registry/subagent-registry.store.sqlite.ts');
  const { ensureSessionEntrySync } = await load('src/config/sessions/session-accessor.ts');
  ensureSessionEntrySync({ sessionKey: requesterSessionKey }, { sessionId: 'proof-requester-session', updatedAt: startedAt });
  const records = new Map();
  for (const runId of cases) {
    const childSessionKey = `agent:main:subagent:${runId}`;
    assert.ok(ensureSessionEntrySync({ sessionKey: childSessionKey }, { sessionId: `${runId}-session`, updatedAt: startedAt, lifecycleRevision: `${runId}-revision` }));
    assert.ok(createRunningTaskRun({ runtime: 'subagent', requesterSessionKey, ownerKey: requesterSessionKey, scopeKind: 'session', childSessionKey, runId, task: runId, notifyPolicy: 'silent', startedAt }));
    const isPredecessor = runId === predecessorRunId;
    records.set(runId, {
      runId, childSessionKey, requesterSessionKey, requesterDisplayKey: requesterSessionKey,
      requesterAgentId: 'main', task: runId, cleanup: 'keep', createdAt: startedAt,
      execution: { status: 'terminal', startedAt, endedAt, outcome: isPredecessor ? { status: 'error', error: 'replaced after steer' } : { status: 'ok' } },
      completion: { required: false, resultText: isPredecessor ? null : 'synthetic completed result', capturedAt: endedAt },
      delivery: { status: 'not_required' }, expectsCompletionMessage: false,
      cleanupCompletedAt: endedAt, cleanupHandled: true,
      endedReason: isPredecessor ? 'subagent-killed' : 'subagent-complete',
      ...(isPredecessor ? { suppressAnnounceReason: 'steer-restart' } : {}),
    });
  }
  saveSubagentRegistryToSqlite(records);
  await fs.writeFile(path.join(process.env.OPENCLAW_STATE_DIR, 'proof-fixture.json'), JSON.stringify({ endedAt }));
  console.log(JSON.stringify({ phase: 'seeded', pid: process.pid, tasks: snapshot() }));
} else if (mode === 'gateway') {
  const before = snapshot();
  assert.equal(before[0].status, 'running');
  const { startGatewayServer } = await load('src/gateway/server.ts');
  const server = await startGatewayServer(Number(portText), { bind: 'loopback', auth: { mode: 'none' }, controlUiEnabled: false });
  try {
    await server.startupSettled;
    const { getSubagentRunByRunId } = await load('src/agents/subagents/registry/subagent-registry.ts');
    for (const runId of cases) assert.ok(getSubagentRunByRunId(runId), `fixture was pruned instead of restored: ${runId}`);
    const health = await fetch(`http://127.0.0.1:${portText}/healthz`);
    assert.equal(health.status, 200);
    const after = snapshot();
    const { findTaskByRunIdForStatus } = await load('src/tasks/task-status-access.ts');
    for (const task of after) assert.equal(findTaskByRunIdForStatus(task.runId)?.status, task.status);
    console.log(JSON.stringify({ phase: 'gateway-restored', pid: process.pid, health: health.status, before, after }));
    await fs.writeFile(path.join(process.env.OPENCLAW_STATE_DIR, 'proof-result.json'), JSON.stringify({ before, after }, null, 2));
    assert.equal(after[0].status, expected);
    if (expected === 'succeeded') {
      const fixture = JSON.parse(await fs.readFile(path.join(process.env.OPENCLAW_STATE_DIR, 'proof-fixture.json'), 'utf8'));
      assert.equal(after[0].endedAt, fixture.endedAt);
      assert.equal(after[0].summary, 'synthetic completed result');
    }
    assert.equal(after[1].status, 'running');
    assert.equal(after[1].endedAt, undefined);
  } finally {
    await server.close({ reason: 'isolated PR136780 proof complete', drainTimeoutMs: 1000 });
  }
} else if (mode === 'readback') {
  const tasks = snapshot();
  console.log(JSON.stringify({ phase: 'fresh-process-readback', pid: process.pid, tasks }));
  assert.equal(tasks[0].status, expected);
  assert.equal(tasks[1].status, 'running');
  assert.equal(tasks[1].endedAt, undefined);
  if (expected === 'succeeded') {
    const fixture = JSON.parse(await fs.readFile(path.join(process.env.OPENCLAW_STATE_DIR, 'proof-fixture.json'), 'utf8'));
    assert.equal(tasks[0].endedAt, fixture.endedAt);
    assert.equal(tasks[0].summary, 'synthetic completed result');
  }
} else {
  throw new Error(`unknown mode ${mode}`);
}
process.exit(0);

Required CI is running on this new head; the old failed runs are not landing evidence. Release-note impact: settle completed subagent tasks after restart without letting a retired steer-restart row finish the successor's task.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Sep 4, 2026
@fuller-stack-dev

Copy link
Copy Markdown
Member Author

Disposition for the fresh review's remaining merge-risk decision: under the explicit maintainer-authorized LAND scope for this restart/ownership repair, accept the recommended covered recovery transition.

No new task lookup policy is introduced. Restoration calls the existing captured-terminal-state finalizer and its existing run/session-scoped task resolver. The specialized recovery owners retain their earlier return, and the explicit steer-restart fence prevents a retired predecessor from terminalizing its successor's writable task. The strengthened capture-complete negative control fails if that fence is removed.

The review reports no correctness or security finding and accepts the isolated cold-start proof. Exact head 5e11b54ef0a5b91019f7ee79ba2900bc62280e67 has 154 passing registry tests, successful first-attempt hosted CI (125 completed jobs), successful native preparation, and successful native merge verification. Proceeding with an exact-head deterministic squash merge; no admin bypass, auto-merge, runtime deployment, or worktree deletion.

@fuller-stack-dev
fuller-stack-dev merged commit cda2d90 into main Sep 4, 2026
180 checks passed
@fuller-stack-dev
fuller-stack-dev deleted the fix/task-restart-cancellation-settlement branch September 4, 2026 07:10
@fuller-stack-dev

Copy link
Copy Markdown
Member Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 5, 2026
* fix: settle restored subagent tasks

* fix: preserve steer-restart task ownership

* test: exercise captured steer restart results during restore

---------

Co-authored-by: Jason Sy <[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 maintainer Maintainer-authored PR merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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