From 25ca0c9e804e6d204b46067324c8bbaeaf031032 Mon Sep 17 00:00:00 2001 From: latte271 Date: Sun, 20 Sep 2026 01:15:52 +0700 Subject: [PATCH 1/2] fix(orchestration): keep a wrongly-stopped worker's dispatch capability MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit beginWorkerStop revokes the dispatch capability on intent, before the stop outcome is known. When the stop closes nothing — an external or otherwise unreachable terminal — it settles as stop_unknown, but the revocation stays: sends to the dispatch are still accepted while the worker's own reports are rejected, muting a worker that is still running. An unproven stop now takes nobody's authority. markWorkerStopUnknown hands the capability back while the dispatch is still pending or dispatched, the same principle as failWorkerStart's retainCapability (#16095): a worker that may still be running keeps the way to report. settleWorkerReport accepts a report from a stop_unknown worker the way it already accepts start_unknown — first-hand evidence outranks the unproven inference — gaining a stop_unknown -> ready edge and clearing the stale stop reason on re-entry. The remote attachment mirror cannot restore a nulled capability_hash (the token lives only with the worker), so the hash now survives the stop intent and is cleared only by proven outcomes: settleRemoteAttachmentStop and the relay settle. verifyRemoteAttachmentAuthority gains a stopping-state guard to keep the in-flight fence the nulled hash used to provide, and both relay settle paths — the modern ack settle and the legacy-protocol enqueue — admit stop_unknown. reconcileFederatedWorkerStop re-asserts revocation when a late remote report proves the stop after all, so a restored capability cannot still verify on a failed dispatch. --- .../db-worker-stop-capability-restore.test.ts | 293 ++++++++++++++++++ .../worker-report-settlement.ts | 32 +- .../db/federation/federation-relay-enqueue.ts | 4 +- .../db/federation/federation-relay-item.ts | 8 +- .../remote-dispatch-attachment-authority.ts | 5 + .../remote-dispatch-attachment-stop.ts | 6 +- .../orchestration/db/lifecycle-transition.ts | 3 +- .../worker-dispatch/worker-dispatch-stop.ts | 19 +- .../lifecycle-caller-edges.test.ts | 2 + 9 files changed, 352 insertions(+), 20 deletions(-) create mode 100644 src/main/runtime/orchestration/db-worker-stop-capability-restore.test.ts diff --git a/src/main/runtime/orchestration/db-worker-stop-capability-restore.test.ts b/src/main/runtime/orchestration/db-worker-stop-capability-restore.test.ts new file mode 100644 index 000000000000..45564bc3d55a --- /dev/null +++ b/src/main/runtime/orchestration/db-worker-stop-capability-restore.test.ts @@ -0,0 +1,293 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { OrchestrationDb } from './db' + +const PANE_W = 'tab_w:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' +const PANE_R = 'tab_r:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' + +describe('an unproven worker stop', () => { + let db: OrchestrationDb + beforeEach(() => { + db = new OrchestrationDb(':memory:') + }) + afterEach(() => db.close()) + + function localWorker() { + const task = db.createTask({ runId: 'run_legacy_local', spec: 'local work' }) + const { dispatch } = db.createStartingWorkerDispatch({ + taskId: task.id, + startOptions: {}, + creator: { kind: 'system' }, + maxDepth: 9 + }) + const capability = db.prepareStartingWorkerAuthority({ + dispatchId: dispatch.id, + handle: 'term_w', + paneKey: PANE_W, + processIncarnation: 'inc1', + worktreeId: 'wt', + effects: [], + setupState: 'not_configured' + }) + db.markWorkerDispatchReady(dispatch.id) + return { task, dispatch, capability } + } + + function verifyLocal(dispatchId: string, capability: string) { + return db.verifyDispatchCapability({ + dispatchId, + capability, + paneKey: PANE_W, + processIncarnation: 'inc1' + }) + } + + it('keeps the in-flight stop fence, then hands the capability back on stop_unknown', () => { + const { dispatch, capability } = localWorker() + + db.beginWorkerStop(dispatch.id, 'epoch_home') + // Intent still fences the worker while the stop is in flight. + expect(verifyLocal(dispatch.id, capability)).toMatchObject({ valid: false }) + expect(db.getDispatchContextById(dispatch.id)?.capability_revoked_at).toBeTruthy() + + db.markWorkerStopUnknown(dispatch.id, 'the worker terminal is external; no terminal was closed') + expect(db.getDispatchContextById(dispatch.id)?.capability_revoked_at).toBeNull() + expect(verifyLocal(dispatch.id, capability)).toEqual({ valid: true }) + }) + + it('keeps the revocation when the stop is proven', () => { + const { dispatch, capability } = localWorker() + + db.beginWorkerStop(dispatch.id, 'epoch_home') + db.settleWorkerStop(dispatch.id) + + expect(db.getDispatchContextById(dispatch.id)?.capability_revoked_at).toBeTruthy() + expect(verifyLocal(dispatch.id, capability)).toMatchObject({ valid: false }) + }) + + it('does not restore the capability onto an already settled dispatch', () => { + const { dispatch } = localWorker() + + db.beginWorkerStop(dispatch.id, 'epoch_home') + // A racing event settled the dispatch while the worker row still reads stopping. + db.db.prepare("UPDATE dispatch_contexts SET status = 'failed' WHERE id = ?").run(dispatch.id) + db.markWorkerStopUnknown(dispatch.id, 'the execution host did not answer') + + expect(db.getDispatchContextById(dispatch.id)?.capability_revoked_at).toBeTruthy() + }) + + it('lets a succeeded worker report settle a dispatch the unproven stop left blocked', () => { + const { task, dispatch } = localWorker() + + db.beginWorkerStop(dispatch.id, 'epoch_home') + db.markWorkerStopUnknown(dispatch.id, 'the worker terminal is external; no terminal was closed') + + expect( + db.settleWorkerReport({ + taskId: task.id, + dispatchId: dispatch.id, + outcome: 'succeeded', + result: '{"summary":"done"}' + }) + ).toMatchObject({ action: 'settled' }) + expect(db.getTask(task.id)?.status).toBe('completed') + expect(db.getDispatchContextById(dispatch.id)?.status).toBe('completed') + expect(db.getWorkerDispatch(dispatch.id)).toMatchObject({ + state: 'succeeded', + last_error: null + }) + }) + + it('lets a failed worker report settle a dispatch the unproven stop left blocked', () => { + const { task, dispatch } = localWorker() + + db.beginWorkerStop(dispatch.id, 'epoch_home') + db.markWorkerStopUnknown(dispatch.id, 'the worker terminal is external; no terminal was closed') + + expect( + db.settleWorkerReport({ + taskId: task.id, + dispatchId: dispatch.id, + outcome: 'failed', + result: 'worker crashed' + }) + ).toMatchObject({ action: 'settled' }) + expect(db.getTask(task.id)?.status).toBe('failed') + expect(db.getWorkerDispatch(dispatch.id)?.state).toBe('failed') + }) + + it('still rejects a worker report while the stop is in flight', () => { + const { task, dispatch } = localWorker() + + db.beginWorkerStop(dispatch.id, 'epoch_home') + + expect( + db.settleWorkerReport({ + taskId: task.id, + dispatchId: dispatch.id, + outcome: 'succeeded', + result: '{}' + }) + ).toMatchObject({ action: 'rejected', code: 'inactive_dispatch' }) + }) +}) + +describe('an unproven remote attachment stop', () => { + let db: OrchestrationDb + let remoteSequence = 0 + beforeEach(() => { + db = new OrchestrationDb(':memory:') + remoteSequence = 0 + }) + afterEach(() => db.close()) + + function remoteAttachment() { + const dispatchId = `ctx_remote_${++remoteSequence}` + db.createRemoteDispatchAttachment({ + runId: 'run-home', + dispatchId, + taskId: `task_${dispatchId}`, + homePeerFingerprint: 'home_peer', + protocolVersion: 1, + runtimeEpoch: 'worker_epoch', + mutationReceipt: { + callerFingerprint: 'home_peer', + requestId: `req_${dispatchId}`, + method: 'orchestration.federationAttachStart', + payloadHash: `hash_${dispatchId}` + } + }) + const capability = db.prepareRemoteAttachmentAuthority({ + dispatchId, + paneKey: PANE_R, + processIncarnation: 'inc_remote', + worktreeId: 'wt_remote', + terminalHandle: 'term_remote', + setupState: 'not_applicable', + effects: [] + }) + db.markRemoteAttachmentReady(dispatchId) + return { dispatchId, capability } + } + + function verifyRemote(dispatchId: string, capability: string) { + return db.verifyRemoteAttachmentAuthority({ + dispatchId, + capability, + paneKey: PANE_R, + processIncarnation: 'inc_remote' + }) + } + + it('keeps the capability hash through the intent and fences it on state instead', () => { + const { dispatchId, capability } = remoteAttachment() + + db.beginRemoteAttachmentStop(dispatchId) + const stopping = db.getRemoteDispatchAttachment(dispatchId) + expect(stopping?.state).toBe('stopping') + expect(stopping?.capability_hash).toBeTruthy() + // The in-flight stop is fenced by state, not by a missing hash. + expect(verifyRemote(dispatchId, capability)).toBe(false) + }) + + it('un-mutes the worker when the stop proves nothing', () => { + const { dispatchId, capability } = remoteAttachment() + + db.beginRemoteAttachmentStop(dispatchId) + db.markRemoteAttachmentStopUnknown( + dispatchId, + 'the worker terminal is external; no terminal was closed' + ) + + expect(verifyRemote(dispatchId, capability)).toBe(true) + }) + + it('clears the hash when the stop is proven', () => { + const { dispatchId, capability } = remoteAttachment() + + db.beginRemoteAttachmentStop(dispatchId) + db.settleRemoteAttachmentStop(dispatchId) + + expect(db.getRemoteDispatchAttachment(dispatchId)?.capability_hash).toBeNull() + expect(verifyRemote(dispatchId, capability)).toBe(false) + }) + + it('lets a worker_done relay settle a stop_unknown attachment', () => { + const { dispatchId } = remoteAttachment() + + db.beginRemoteAttachmentStop(dispatchId) + db.markRemoteAttachmentStopUnknown(dispatchId, 'no terminal was closed') + db.settleRemoteAttachmentInRelayTransaction(dispatchId, 'succeeded') + + expect(db.getRemoteDispatchAttachment(dispatchId)).toMatchObject({ + state: 'succeeded', + capability_hash: null, + last_error: null + }) + }) + + it('still refuses a relay settle while the stop is in flight', () => { + const { dispatchId } = remoteAttachment() + + db.beginRemoteAttachmentStop(dispatchId) + + expect(() => db.settleRemoteAttachmentInRelayTransaction(dispatchId, 'succeeded')).toThrowError( + expect.objectContaining({ code: 'request_mismatch' }) + ) + }) + + it('accepts a legacy-protocol worker_done enqueue from a stop_unknown attachment', () => { + const { dispatchId } = remoteAttachment() + + db.beginRemoteAttachmentStop(dispatchId) + db.markRemoteAttachmentStopUnknown(dispatchId, 'no terminal was closed') + + expect(() => + db.enqueueFederationRelay({ + dispatchId, + direction: 'to_home', + kind: 'worker_done', + payload: '{"outcome":"succeeded"}', + settleRemoteOutcome: 'succeeded' + }) + ).not.toThrow() + expect(db.getRemoteDispatchAttachment(dispatchId)?.state).toBe('succeeded') + }) + + it('re-asserts revocation when a late remote report proves the stop after all', () => { + const task = db.createTask({ runId: 'run_legacy_local', spec: 'federated work' }) + const { dispatch } = db.createStartingWorkerDispatch({ + taskId: task.id, + startOptions: {}, + creator: { kind: 'system' }, + maxDepth: 9 + }) + db.prepareStartingWorkerAuthority({ + dispatchId: dispatch.id, + handle: 'term_w', + paneKey: PANE_W, + processIncarnation: 'inc1', + worktreeId: 'wt', + effects: [], + setupState: 'not_configured' + }) + db.markWorkerDispatchReady(dispatch.id) + db.db + .prepare( + `INSERT INTO federated_dispatches (dispatch_id, environment_id, environment_name, peer_fingerprint) + VALUES (?, 'env_1', 'remote env', 'peer_1')` + ) + .run(dispatch.id) + + db.beginWorkerStop(dispatch.id, 'epoch_home') + db.markWorkerStopUnknown(dispatch.id, 'the remote did not answer') + expect(db.getDispatchContextById(dispatch.id)?.capability_revoked_at).toBeNull() + + db.reconcileFederatedWorkerStop(dispatch.id) + expect(db.getWorkerDispatch(dispatch.id)?.state).toBe('stopped') + expect(db.getDispatchContextById(dispatch.id)).toMatchObject({ + status: 'failed', + last_failure: 'stopped' + }) + expect(db.getDispatchContextById(dispatch.id)?.capability_revoked_at).toBeTruthy() + }) +}) diff --git a/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts b/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts index ddb0e383143c..ada432625ec3 100644 --- a/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts +++ b/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts @@ -105,22 +105,25 @@ export function settleWorkerReportInTransaction( recordAcceptedReportFact(this, params) return { action: 'settled', outcome: params.outcome, duplicate: true } } - const reconnectingStart = + // Both `start_unknown` and `stop_unknown` are unproven inferences about the worker that left + // the same shape behind: dispatch active, task blocked. The worker's own report is first-hand + // evidence it is alive and outranks either guess. + const reconnectingWorker = (dispatch.status === 'pending' || dispatch.status === 'dispatched') && task.status === 'blocked' && - reportingWorker?.state === 'start_unknown' + (reportingWorker?.state === 'start_unknown' || reportingWorker?.state === 'stop_unknown') const reportingStart = dispatch.status === 'pending' && task.status === 'dispatched' && reportingWorker?.state === 'starting' const previousDispatchStatus = settledByUnobservedPrompt ? 'failed' - : reconnectingStart || reportingStart + : reconnectingWorker || reportingStart ? dispatch.status : 'dispatched' const previousTaskStatus = settledByUnobservedPrompt ? 'failed' - : reconnectingStart + : reconnectingWorker ? 'blocked' : 'dispatched' if (dispatch.status !== previousDispatchStatus || task.status !== previousTaskStatus) { @@ -191,7 +194,7 @@ export function settleWorkerReportInTransaction( dispatchUpdate = { changes: dispatchTransition.changed ? 1 : 0 } taskUpdate = { changes: taskTransition.changed ? 1 : 0 } } else { - if (reconnectingStart) { + if (reconnectingWorker) { transitionLifecycleWithDb(this.db, { entity: 'task', id: params.taskId, @@ -202,7 +205,7 @@ export function settleWorkerReportInTransaction( const dispatchTransition = transitionLifecycleWithDb(this.db, { entity: 'dispatch', id: params.dispatchId, - from: reconnectingStart || reportingStart ? ['pending', 'dispatched'] : 'dispatched', + from: reconnectingWorker || reportingStart ? ['pending', 'dispatched'] : 'dispatched', to: expectedDispatchStatus, projection: { completed_at: new Date().toISOString(), @@ -238,12 +241,15 @@ export function settleWorkerReportInTransaction( projection: { stage: 'settled', updated_at: new Date().toISOString() }, correction: 'unobserved_prompt_report' }) - } else if ((reconnectingStart || reportingStart) && params.outcome === 'succeeded') { + } else if ((reconnectingWorker || reportingStart) && params.outcome === 'succeeded') { transitionLifecycleWithDb(this.db, { entity: 'worker', id: params.dispatchId, - from: reportingStart ? 'starting' : 'start_unknown', - to: 'ready' + from: reportingStart ? 'starting' : ['start_unknown', 'stop_unknown'], + to: 'ready', + // The report disproves the recorded uncertainty; keep its reason from shadowing a + // succeeded worker. + projection: { last_error: null } }) transitionLifecycleWithDb(this.db, { entity: 'worker', @@ -256,8 +262,12 @@ export function settleWorkerReportInTransaction( transitionLifecycleWithDb(this.db, { entity: 'worker', id: params.dispatchId, - // A start_unknown success report reconnects through 'ready' above; only failure settles here. - from: params.outcome === 'succeeded' ? 'ready' : ['ready', 'start_unknown', 'starting'], + // An unproven-start/stop success report reconnects through 'ready' above; only failure + // settles here. + from: + params.outcome === 'succeeded' + ? 'ready' + : ['ready', 'start_unknown', 'stop_unknown', 'starting'], to: params.outcome === 'succeeded' ? 'succeeded' : 'failed', projection: { stage: 'settled', updated_at: new Date().toISOString() } }) diff --git a/src/main/runtime/orchestration/db/federation/federation-relay-enqueue.ts b/src/main/runtime/orchestration/db/federation/federation-relay-enqueue.ts index 28841f44e6e0..3f0b1187ba19 100644 --- a/src/main/runtime/orchestration/db/federation/federation-relay-enqueue.ts +++ b/src/main/runtime/orchestration/db/federation/federation-relay-enqueue.ts @@ -31,7 +31,9 @@ export function enqueueFederationRelay( try { if (params.settleRemoteOutcome) { const attachment = this.getRemoteDispatchAttachment(params.dispatchId) - if (!attachment || attachment.state !== 'ready') { + // `stop_unknown` is admissible on legacy-protocol peers: their worker_done settles at + // enqueue, and an unproven stop must not mute the report that disproves it. + if (!attachment || !['ready', 'stop_unknown'].includes(attachment.state)) { throw new OrchestrationError( 'dispatch_inactive', `Remote Dispatch ${params.dispatchId} is not active.` diff --git a/src/main/runtime/orchestration/db/federation/federation-relay-item.ts b/src/main/runtime/orchestration/db/federation/federation-relay-item.ts index 1ae13b6b6ae0..27e313578f8d 100644 --- a/src/main/runtime/orchestration/db/federation/federation-relay-item.ts +++ b/src/main/runtime/orchestration/db/federation/federation-relay-item.ts @@ -40,7 +40,9 @@ export function settleRemoteAttachmentInRelayTransaction( if (attachment.state === state) { return } - if (attachment.state !== 'ready') { + // `stop_unknown` settles too: the report is first-hand evidence that the unproven stop never + // landed. An in-flight `stopping` still loses to the stop fence, as on the home side. + if (!['ready', 'stop_unknown'].includes(attachment.state)) { throw new OrchestrationError( 'request_mismatch', `Remote Dispatch ${dispatchId} cannot settle as ${state} from ${attachment.state}.` @@ -49,9 +51,9 @@ export function settleRemoteAttachmentInRelayTransaction( this.db .prepare( `UPDATE remote_dispatch_attachments - SET state = ?, stage = ?, capability_hash = NULL, + SET state = ?, stage = ?, capability_hash = NULL, last_error = NULL, updated_at = datetime('now') - WHERE dispatch_id = ? AND state = 'ready'` + WHERE dispatch_id = ? AND state IN ('ready', 'stop_unknown')` ) .run(state, stage, dispatchId) } diff --git a/src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-authority.ts b/src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-authority.ts index ac85fc7c3c99..f2723aed3775 100644 --- a/src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-authority.ts +++ b/src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-authority.ts @@ -172,6 +172,11 @@ export function verifyRemoteAttachmentAuthority( } ): boolean { const attachment = this.getRemoteDispatchAttachment(params.dispatchId) + // The hash now survives the stop intent, so the state is what fences an in-flight stop — + // matching the home side, where beginWorkerStop's revocation does it. + if (attachment?.state === 'stopping') { + return false + } if ( !attachment?.capability_hash || !params.capability || diff --git a/src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-stop.ts b/src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-stop.ts index c34bea09aade..eae3d5949086 100644 --- a/src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-stop.ts +++ b/src/main/runtime/orchestration/db/federation/remote-dispatch-attachment-stop.ts @@ -28,8 +28,7 @@ export function beginRemoteAttachmentStop( this.db .prepare( `UPDATE remote_dispatch_attachments - SET state = 'stopping', stage = 'stop_requested', capability_hash = NULL, - updated_at = datetime('now') + SET state = 'stopping', stage = 'stop_requested', updated_at = datetime('now') WHERE dispatch_id = ? AND state IN ('ready', 'start_unknown')` ) .run(dispatchId) @@ -43,7 +42,8 @@ export function settleRemoteAttachmentStop( this.db .prepare( `UPDATE remote_dispatch_attachments - SET state = 'stopped', stage = 'process_stopped', updated_at = datetime('now') + SET state = 'stopped', stage = 'process_stopped', capability_hash = NULL, + updated_at = datetime('now') WHERE dispatch_id = ? AND state = 'stopping'` ) .run(dispatchId) diff --git a/src/main/runtime/orchestration/db/lifecycle-transition.ts b/src/main/runtime/orchestration/db/lifecycle-transition.ts index 6fcc40f19131..5b9f103efa55 100644 --- a/src/main/runtime/orchestration/db/lifecycle-transition.ts +++ b/src/main/runtime/orchestration/db/lifecycle-transition.ts @@ -89,7 +89,8 @@ const LEGAL_TRANSITIONS: Record Date: Sun, 20 Sep 2026 01:41:06 +0700 Subject: [PATCH 2/2] fix(orchestration): settle an unproven worker's success report under a dispatched task The stop_unknown/start_unknown reconnect routed a succeeded report through ready only when the task was blocked. A legacy or context-only sibling dispatch can hold the task at dispatched through the unproven stop, so the report fell through to the ready-only fallback and threw lifecycle_conflict, losing first-hand evidence the worker never stopped. Key the worker-level ready -> succeeded reconnect on the worker's own unproven state instead of the task marker; the blocked -> dispatched task transition stays gated on the blocked shape. --- .../db-worker-stop-capability-restore.test.ts | 29 +++++++++++++++++++ .../worker-report-settlement.ts | 13 +++++---- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/src/main/runtime/orchestration/db-worker-stop-capability-restore.test.ts b/src/main/runtime/orchestration/db-worker-stop-capability-restore.test.ts index 45564bc3d55a..13d7cb6ec1af 100644 --- a/src/main/runtime/orchestration/db-worker-stop-capability-restore.test.ts +++ b/src/main/runtime/orchestration/db-worker-stop-capability-restore.test.ts @@ -97,6 +97,35 @@ describe('an unproven worker stop', () => { }) }) + it('lets a succeeded report settle while a legacy sibling keeps the task dispatched', () => { + const { task, dispatch } = localWorker() + + // A fresh DB cannot open two dispatches on one task, but a migrated row can hold the + // shape: the context-only sibling keeps the task dispatched through the unproven stop. + db.db + .prepare( + "INSERT INTO dispatch_contexts (id, task_id, status, depth) VALUES (?, ?, 'dispatched', 0)" + ) + .run('ctx_sibling', task.id) + db.beginWorkerStop(dispatch.id, 'epoch_home') + db.markWorkerStopUnknown(dispatch.id, 'the execution host did not answer') + expect(db.getTask(task.id)?.status).toBe('dispatched') + + expect( + db.settleWorkerReport({ + taskId: task.id, + dispatchId: dispatch.id, + outcome: 'succeeded', + result: '{"summary":"done"}' + }) + ).toMatchObject({ action: 'settled' }) + expect(db.getTask(task.id)?.status).toBe('completed') + expect(db.getWorkerDispatch(dispatch.id)).toMatchObject({ + state: 'succeeded', + last_error: null + }) + }) + it('lets a failed worker report settle a dispatch the unproven stop left blocked', () => { const { task, dispatch } = localWorker() diff --git a/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts b/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts index ada432625ec3..9b5670b5106f 100644 --- a/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts +++ b/src/main/runtime/orchestration/db/dispatch-context/worker-report-settlement.ts @@ -105,13 +105,16 @@ export function settleWorkerReportInTransaction( recordAcceptedReportFact(this, params) return { action: 'settled', outcome: params.outcome, duplicate: true } } - // Both `start_unknown` and `stop_unknown` are unproven inferences about the worker that left - // the same shape behind: dispatch active, task blocked. The worker's own report is first-hand - // evidence it is alive and outranks either guess. + // Both `start_unknown` and `stop_unknown` are unproven inferences about the worker; its own + // report is first-hand evidence it is alive and outranks either guess. The task is normally + // `blocked` behind that shape, but a legacy sibling dispatch can hold it at `dispatched` — + // the worker reconnect below cannot key on the task marker alone. + const unprovenWorker = + reportingWorker?.state === 'start_unknown' || reportingWorker?.state === 'stop_unknown' const reconnectingWorker = (dispatch.status === 'pending' || dispatch.status === 'dispatched') && task.status === 'blocked' && - (reportingWorker?.state === 'start_unknown' || reportingWorker?.state === 'stop_unknown') + unprovenWorker const reportingStart = dispatch.status === 'pending' && task.status === 'dispatched' && @@ -241,7 +244,7 @@ export function settleWorkerReportInTransaction( projection: { stage: 'settled', updated_at: new Date().toISOString() }, correction: 'unobserved_prompt_report' }) - } else if ((reconnectingWorker || reportingStart) && params.outcome === 'succeeded') { + } else if (params.outcome === 'succeeded' && (reconnectingWorker || reportingStart || unprovenWorker)) { transitionLifecycleWithDb(this.db, { entity: 'worker', id: params.dispatchId,