Repository navigation
fix: settle restored subagent tasks - #136780
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: blocked before merge. Reviewed September 4, 2026, 3:07 AM ET / 07:07 UTC. ClawSweeper reviewWhat this changesThis PR restores completed subagent task status after a Gateway restart while leaving a steer-restarted successor task writable. Regression provenancePossible 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 Review scores
Verification
How this fits togetherSubagent 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]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +11, Tests +111. Total +122 across 2 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Technical reviewBest 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. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (3 earlier review cycles) |
Restart proof and review disposition — head 5e11b54Responding to the restart-trace request. The implementation still uses the canonical run-scoped task finalizer; this recovery also hardens the steer-restart negative control.
Real cold-start boundaryRan 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
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 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 21467Use 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 |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
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 |
|
Merged via squash.
|
* 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]>
Summary
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,
resumeSubagentRunreturned immediately for cleanup-complete rows, leaving the task permanently markedrunning.Testing
pnpm test src/agents/subagents/registry/subagent-registry.test.ts(153 passed)pnpm test:changed(153 passed)pnpm check:changedWorked on by