From c58eaa955fb09ef7df623225a5ed08dfd2091602 Mon Sep 17 00:00:00 2001 From: Abhiram Shaji Date: Tue, 24 Nov 2026 19:45:07 -0500 Subject: [PATCH 1/3] fix(cdk): settle a failed sub-task's issue once per task (#1073) --- cdk/src/handlers/orchestration-reconciler.ts | 24 ++++++++-- .../handlers/orchestration-reconciler.test.ts | 47 ++++++++++++++++++- 2 files changed, 67 insertions(+), 4 deletions(-) diff --git a/cdk/src/handlers/orchestration-reconciler.ts b/cdk/src/handlers/orchestration-reconciler.ts index 43df42216..64dae5439 100644 --- a/cdk/src/handlers/orchestration-reconciler.ts +++ b/cdk/src/handlers/orchestration-reconciler.ts @@ -535,6 +535,20 @@ async function reloadIterationScreenshot(taskId?: string): Promise<{ screenshotU } } +async function markSettled(orchestrationId: string, subIssueId: string, taskId: string): Promise { + try { + await ddb.send(new UpdateCommand({ + TableName: ORCHESTRATION_TABLE, + Key: { orchestration_id: orchestrationId, sub_issue_id: subIssueId }, + UpdateExpression: 'SET settled_task_id = :tid', + ConditionExpression: 'child_task_id = :tid', + ExpressionAttributeValues: { ':tid': taskId }, + })); + } catch (err) { + if (!isConditionalCheckFailed(err)) throw err; + } +} + /** Apply one terminal child's reconcile plan. */ async function reconcileTerminalChild(evt: TerminalTaskEvent): Promise { const orchestrationId = evt.orchestrationId!; @@ -582,6 +596,7 @@ async function reconcileTerminalChild(evt: TerminalTaskEvent): Promise { // child, or a retry reset it, and the row keeps the old task id until it // is released again. Such an event must not put the old verdict back. let stale = false; + let settled = false; for (const update of plan.statusUpdates) { // ``toRelease`` rows are handled by releaseChild below (which flips // them to released conditionally); skip them here to avoid a @@ -609,13 +624,15 @@ async function reconcileTerminalChild(evt: TerminalTaskEvent): Promise { condition = 'child_task_id = :tid AND (child_status = :running OR child_status = :s)'; } try { - await ddb.send(new UpdateCommand({ + const res = await ddb.send(new UpdateCommand({ TableName: ORCHESTRATION_TABLE, Key: { orchestration_id: orchestrationId, sub_issue_id: update.sub_issue_id }, UpdateExpression: 'SET child_status = :s, updated_at = :now', ConditionExpression: condition, ExpressionAttributeValues: values, + ...(!skipGuard && { ReturnValues: 'ALL_OLD' as const }), })); + if (!skipGuard) settled = res.Attributes?.settled_task_id === evt.taskId; } catch (err) { if (!isConditionalCheckFailed(err)) throw err; if (skipGuard) continue; // not a skippable source @@ -646,9 +663,9 @@ async function reconcileTerminalChild(evt: TerminalTaskEvent): Promise { // failure reason on the panel convey "it failed"; a reply re-runs it (the // retry re-drives the state not-started → running). Skip the integration // node (synthetic id, no real issue), and a stale event (the issue shows - // what a later run did). Best-effort; never throws. + // what a later run did). const settleChannel = channelForMeta(snapshot.meta); - if (settleChannel && !plan.terminalSucceeded && !stale && !isIntegrationNode(subIssueId)) { + if (settleChannel && !plan.terminalSucceeded && !stale && !settled && !isIntegrationNode(subIssueId)) { const channel = settleChannel; const childRef = issueRef(subIssueId, snapshot.meta.credentials_ref); try { @@ -684,6 +701,7 @@ async function reconcileTerminalChild(evt: TerminalTaskEvent): Promise { error: err instanceof Error ? err.message : String(err), }); } + await markSettled(orchestrationId, subIssueId, evt.taskId); } // 2. Re-evaluate releasability against a FRESH read, not the initial diff --git a/cdk/test/handlers/orchestration-reconciler.test.ts b/cdk/test/handlers/orchestration-reconciler.test.ts index 0164b658a..da288b6ac 100644 --- a/cdk/test/handlers/orchestration-reconciler.test.ts +++ b/cdk/test/handlers/orchestration-reconciler.test.ts @@ -2179,6 +2179,7 @@ function orchestrationStore( child_task_id?: string; child_branch_name?: string; failure_reason?: string; + settled_task_id?: string; }>, meta: StoreRow = {}, ) { @@ -2231,13 +2232,14 @@ function orchestrationStore( if (!conditionHolds(row, input.ConditionExpression, vals)) { throw Object.assign(new Error('The conditional request failed'), { name: 'ConditionalCheckFailedException' }); } + const old = { ...row }; const expression = String(input.UpdateExpression); for (const assignment of /SET (.+?)(?= REMOVE |$)/.exec(expression)?.[1].split(', ') ?? []) { const [attr, value] = assignment.split(' = '); row[attr] = vals[value]; } for (const attr of /REMOVE (.+?)(?= SET |$)/.exec(expression)?.[1].split(', ') ?? []) delete row[attr]; - return {}; + return input.ReturnValues === 'ALL_OLD' ? { Attributes: old } : {}; }); return { @@ -2383,6 +2385,49 @@ describe('orchestration-reconciler handler — an event of a task that no longer expect(createTaskCoreMock).not.toHaveBeenCalled(); }); + test('a later write of a failure that was already settled leaves the issue where a person put it', async () => { + const store = orchestrationStore([{ sub_issue_id: 'A', child_status: 'released', child_task_id: 'TA' }]); + await handler(lateFailure()); + await handler(lateFailure()); + await handler(lateFailure()); + + expect(store.status('A')).toBe('failed'); + expect(store.row('A').settled_task_id).toBe('TA'); + expect(revertIssueToNotStartedMock).toHaveBeenCalledTimes(1); + expect(swapIssueReactionMock.mock.calls.filter(([, id, emoji]) => id === 'A' && emoji === 'x')).toHaveLength(1); + }); + + test('a settle that could not reach the tracker is not repeated by a later write', async () => { + revertIssueToNotStartedMock.mockRejectedValueOnce(new Error('Linear is down')); + const store = orchestrationStore([{ sub_issue_id: 'A', child_status: 'released', child_task_id: 'TA' }]); + await handler(lateFailure()); + await handler(lateFailure()); + + expect(store.row('A').settled_task_id).toBe('TA'); + expect(revertIssueToNotStartedMock).toHaveBeenCalledTimes(1); + }); + + test('a settle of an earlier task of the row does not stop the settle of this one', async () => { + const store = orchestrationStore([ + { sub_issue_id: 'A', child_status: 'released', child_task_id: 'TA', settled_task_id: 'T-earlier' }, + ]); + await handler(lateFailure()); + + expect(store.row('A').settled_task_id).toBe('TA'); + expect(revertIssueToNotStartedMock).toHaveBeenCalledWith(expect.anything(), 'A'); + }); + + test('a row released to a new task while the failure settled is not marked for the old one', async () => { + const store = orchestrationStore([{ sub_issue_id: 'A', child_status: 'released', child_task_id: 'TA' }]); + revertIssueToNotStartedMock.mockImplementationOnce(async () => { + Object.assign(store.row('A'), { child_status: 'released', child_task_id: 'T2' }); + return true; + }); + await handler(lateFailure()); + + expect(store.row('A').settled_task_id).toBeUndefined(); + }); + test('a dependent that was released since the rows were read is not skipped; the rest of the failure still applies', async () => { // A refused skip is not a stale event: only that one dependent is left alone. const store = orchestrationStore([ From ceba069fd3287932f7e85d7fc6b9134c55802745 Mon Sep 17 00:00:00 2001 From: Abhiram Shaji Date: Wed, 25 Nov 2026 12:53:24 -0500 Subject: [PATCH 2/3] fix(cdk): claim the settle of a failed child before the tracker calls (#1073) A DynamoDB error on the marker write failed the record after the issue was already reverted, and the retry reverted it again. The marker is now claimed with a conditional write before the tracker calls, so a failed claim leaves the issue untouched and a retry after the claim never settles twice. Adds settled_task_id to the row type and the design doc. --- cdk/src/handlers/orchestration-reconciler.ts | 19 ++++---- .../handlers/shared/orchestration-store.ts | 1 + .../handlers/orchestration-reconciler.test.ts | 48 ++++++++++++++++--- docs/design/ORCHESTRATOR.md | 11 +++++ .../content/docs/architecture/Orchestrator.md | 11 +++++ 5 files changed, 75 insertions(+), 15 deletions(-) diff --git a/cdk/src/handlers/orchestration-reconciler.ts b/cdk/src/handlers/orchestration-reconciler.ts index 64dae5439..4baa75e3e 100644 --- a/cdk/src/handlers/orchestration-reconciler.ts +++ b/cdk/src/handlers/orchestration-reconciler.ts @@ -535,17 +535,19 @@ async function reloadIterationScreenshot(taskId?: string): Promise<{ screenshotU } } -async function markSettled(orchestrationId: string, subIssueId: string, taskId: string): Promise { +async function claimSettle(orchestrationId: string, subIssueId: string, taskId: string): Promise { try { await ddb.send(new UpdateCommand({ TableName: ORCHESTRATION_TABLE, Key: { orchestration_id: orchestrationId, sub_issue_id: subIssueId }, UpdateExpression: 'SET settled_task_id = :tid', - ConditionExpression: 'child_task_id = :tid', - ExpressionAttributeValues: { ':tid': taskId }, + ConditionExpression: 'child_task_id = :tid AND child_status = :failed AND (attribute_not_exists(settled_task_id) OR settled_task_id <> :tid)', + ExpressionAttributeValues: { ':tid': taskId, ':failed': 'failed' }, })); + return true; } catch (err) { if (!isConditionalCheckFailed(err)) throw err; + return false; } } @@ -596,7 +598,6 @@ async function reconcileTerminalChild(evt: TerminalTaskEvent): Promise { // child, or a retry reset it, and the row keeps the old task id until it // is released again. Such an event must not put the old verdict back. let stale = false; - let settled = false; for (const update of plan.statusUpdates) { // ``toRelease`` rows are handled by releaseChild below (which flips // them to released conditionally); skip them here to avoid a @@ -624,15 +625,13 @@ async function reconcileTerminalChild(evt: TerminalTaskEvent): Promise { condition = 'child_task_id = :tid AND (child_status = :running OR child_status = :s)'; } try { - const res = await ddb.send(new UpdateCommand({ + await ddb.send(new UpdateCommand({ TableName: ORCHESTRATION_TABLE, Key: { orchestration_id: orchestrationId, sub_issue_id: update.sub_issue_id }, UpdateExpression: 'SET child_status = :s, updated_at = :now', ConditionExpression: condition, ExpressionAttributeValues: values, - ...(!skipGuard && { ReturnValues: 'ALL_OLD' as const }), })); - if (!skipGuard) settled = res.Attributes?.settled_task_id === evt.taskId; } catch (err) { if (!isConditionalCheckFailed(err)) throw err; if (skipGuard) continue; // not a skippable source @@ -665,7 +664,10 @@ async function reconcileTerminalChild(evt: TerminalTaskEvent): Promise { // node (synthetic id, no real issue), and a stale event (the issue shows // what a later run did). const settleChannel = channelForMeta(snapshot.meta); - if (settleChannel && !plan.terminalSucceeded && !stale && !settled && !isIntegrationNode(subIssueId)) { + if ( + settleChannel && !plan.terminalSucceeded && !stale && !isIntegrationNode(subIssueId) + && await claimSettle(orchestrationId, subIssueId, evt.taskId) + ) { const channel = settleChannel; const childRef = issueRef(subIssueId, snapshot.meta.credentials_ref); try { @@ -701,7 +703,6 @@ async function reconcileTerminalChild(evt: TerminalTaskEvent): Promise { error: err instanceof Error ? err.message : String(err), }); } - await markSettled(orchestrationId, subIssueId, evt.taskId); } // 2. Re-evaluate releasability against a FRESH read, not the initial diff --git a/cdk/src/handlers/shared/orchestration-store.ts b/cdk/src/handlers/shared/orchestration-store.ts index 718649cb3..6f050f5d9 100644 --- a/cdk/src/handlers/shared/orchestration-store.ts +++ b/cdk/src/handlers/shared/orchestration-store.ts @@ -125,6 +125,7 @@ export interface OrchestrationChildRow { * normal case (a released child's reason comes from its task record). */ readonly failure_reason?: string; + readonly settled_task_id?: string; readonly created_at: string; readonly updated_at: string; /** TTL epoch (seconds) for eventual cleanup. */ diff --git a/cdk/test/handlers/orchestration-reconciler.test.ts b/cdk/test/handlers/orchestration-reconciler.test.ts index da288b6ac..7100d887a 100644 --- a/cdk/test/handlers/orchestration-reconciler.test.ts +++ b/cdk/test/handlers/orchestration-reconciler.test.ts @@ -2232,14 +2232,13 @@ function orchestrationStore( if (!conditionHolds(row, input.ConditionExpression, vals)) { throw Object.assign(new Error('The conditional request failed'), { name: 'ConditionalCheckFailedException' }); } - const old = { ...row }; const expression = String(input.UpdateExpression); for (const assignment of /SET (.+?)(?= REMOVE |$)/.exec(expression)?.[1].split(', ') ?? []) { const [attr, value] = assignment.split(' = '); row[attr] = vals[value]; } for (const attr of /REMOVE (.+?)(?= SET |$)/.exec(expression)?.[1].split(', ') ?? []) delete row[attr]; - return input.ReturnValues === 'ALL_OLD' ? { Attributes: old } : {}; + return {}; }); return { @@ -2273,6 +2272,10 @@ describe('orchestration-reconciler handler — an event of a task that no longer }); /** A later write to A's first task, which ended FAILED. */ + const sequencedFailure = () => ({ + Records: [taskRecord({ task_id: 'TA', status: 'FAILED', orchestration_id: 'orch_1', sequenceNumber: 'seq-TA' })], + }) as never; + const isClaim = (cmd: StoreCommand) => String(cmd.input.UpdateExpression).includes('settled_task_id'); const lateFailure = () => ({ Records: [taskRecord({ task_id: 'TA', status: 'FAILED', orchestration_id: 'orch_1' })], }) as never; @@ -2417,15 +2420,48 @@ describe('orchestration-reconciler handler — an event of a task that no longer expect(revertIssueToNotStartedMock).toHaveBeenCalledWith(expect.anything(), 'A'); }); - test('a row released to a new task while the failure settled is not marked for the old one', async () => { + test('a throttled claim fails the record before the issue is touched, and the retry settles it once', async () => { const store = orchestrationStore([{ sub_issue_id: 'A', child_status: 'released', child_task_id: 'TA' }]); - revertIssueToNotStartedMock.mockImplementationOnce(async () => { - Object.assign(store.row('A'), { child_status: 'released', child_task_id: 'T2' }); - return true; + store.before(isClaim, () => { + throw Object.assign(new Error('Rate exceeded'), { name: 'ThrottlingException' }); }); + const first = await handler(sequencedFailure()); + + expect(first.batchItemFailures).toEqual([{ itemIdentifier: 'seq-TA' }]); + expect(revertIssueToNotStartedMock).not.toHaveBeenCalled(); + + await handler(lateFailure()); + + expect(store.row('A').settled_task_id).toBe('TA'); + expect(revertIssueToNotStartedMock).toHaveBeenCalledTimes(1); + }); + + test('a delivery that fails after the settle is retried without settling the issue again', async () => { + const store = orchestrationStore([{ sub_issue_id: 'A', child_status: 'released', child_task_id: 'TA' }]); + store.before( + (cmd) => cmd._type === 'Query' && store.row('A').settled_task_id === 'TA', + () => { + throw Object.assign(new Error('Rate exceeded'), { name: 'ThrottlingException' }); + }, + ); + const first = await handler(sequencedFailure()); + await handler(lateFailure()); + + expect(first.batchItemFailures).toEqual([{ itemIdentifier: 'seq-TA' }]); + expect(revertIssueToNotStartedMock).toHaveBeenCalledTimes(1); + expect(swapIssueReactionMock.mock.calls.filter(([, id, emoji]) => id === 'A' && emoji === 'x')).toHaveLength(1); + }); + + test.each([ + ['released to a new task', { child_status: 'released', child_task_id: 'T2' }], + ['repaired', { child_status: 'succeeded' }], + ])('a row %s between the verdict and the claim keeps its issue as it is', async (_name, change) => { + const store = orchestrationStore([{ sub_issue_id: 'A', child_status: 'released', child_task_id: 'TA' }]); + store.before(isClaim, () => Object.assign(store.row('A'), change)); await handler(lateFailure()); expect(store.row('A').settled_task_id).toBeUndefined(); + expect(revertIssueToNotStartedMock).not.toHaveBeenCalled(); }); test('a dependent that was released since the rows were read is not skipped; the rest of the failure still applies', async () => { diff --git a/docs/design/ORCHESTRATOR.md b/docs/design/ORCHESTRATOR.md index 07b3309a4..004b4d642 100644 --- a/docs/design/ORCHESTRATOR.md +++ b/docs/design/ORCHESTRATOR.md @@ -466,3 +466,14 @@ Append-only audit log. See [OBSERVABILITY.md](./OBSERVABILITY.md). Increment: `SET active_count = active_count + 1` with `ConditionExpression: active_count < :max`. Decrement: `SET active_count = active_count - 1` with `ConditionExpression: active_count > 0`. + +### Orchestration table + +Backs the orchestration of an epic's child issues ([SURFACE_AGNOSTIC_ORCHESTRATION.md](./SURFACE_AGNOSTIC_ORCHESTRATION.md)), not the task lifecycle above: one row per child issue, keyed by `orchestration_id` (PK) and `sub_issue_id` (SK), plus one `#meta` row per epic. The row type is `OrchestrationChildRow` in `cdk/src/handlers/shared/orchestration-store.ts`. The fields the reconciler decides on: + +| Field | Type | Description | +|---|---|---| +| `child_status` | String | `blocked`, `ready`, `releasing`, `released`, `succeeded`, `failed` or `skipped` | +| `child_task_id` | String? | Task of the current run, key of `ChildTaskIndex`; a retry keeps it until the next release | +| `failure_reason` | String? | Why the last start was refused, when no task exists for that attempt | +| `settled_task_id` | String? | Task whose failure has already moved the issue back and set ❌. Claimed with a conditional write before the tracker calls, so a later write on that task record, or a retry of its stream record, leaves the issue where a person put it | diff --git a/docs/src/content/docs/architecture/Orchestrator.md b/docs/src/content/docs/architecture/Orchestrator.md index d25085964..a19ffb81e 100644 --- a/docs/src/content/docs/architecture/Orchestrator.md +++ b/docs/src/content/docs/architecture/Orchestrator.md @@ -468,3 +468,14 @@ Append-only audit log. See [OBSERVABILITY.md](/sample-autonomous-cloud-coding-ag Increment: `SET active_count = active_count + 1` with `ConditionExpression: active_count < :max`. Decrement: `SET active_count = active_count - 1` with `ConditionExpression: active_count > 0`. + +### Orchestration table + +Backs the orchestration of an epic's child issues ([SURFACE_AGNOSTIC_ORCHESTRATION.md](/sample-autonomous-cloud-coding-agents/architecture/surface-agnostic-orchestration)), not the task lifecycle above: one row per child issue, keyed by `orchestration_id` (PK) and `sub_issue_id` (SK), plus one `#meta` row per epic. The row type is `OrchestrationChildRow` in `cdk/src/handlers/shared/orchestration-store.ts`. The fields the reconciler decides on: + +| Field | Type | Description | +|---|---|---| +| `child_status` | String | `blocked`, `ready`, `releasing`, `released`, `succeeded`, `failed` or `skipped` | +| `child_task_id` | String? | Task of the current run, key of `ChildTaskIndex`; a retry keeps it until the next release | +| `failure_reason` | String? | Why the last start was refused, when no task exists for that attempt | +| `settled_task_id` | String? | Task whose failure has already moved the issue back and set ❌. Claimed with a conditional write before the tracker calls, so a later write on that task record, or a retry of its stream record, leaves the issue where a person put it | From 66fc2261f27b39f34bebdf4dc81ba285605e7efc Mon Sep 17 00:00:00 2001 From: Abhiram Shaji Date: Wed, 25 Nov 2026 13:01:12 -0500 Subject: [PATCH 3/3] test(cdk): keep the lateFailure comment on lateFailure --- cdk/test/handlers/orchestration-reconciler.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cdk/test/handlers/orchestration-reconciler.test.ts b/cdk/test/handlers/orchestration-reconciler.test.ts index 7100d887a..27b7d9e5d 100644 --- a/cdk/test/handlers/orchestration-reconciler.test.ts +++ b/cdk/test/handlers/orchestration-reconciler.test.ts @@ -2271,11 +2271,11 @@ describe('orchestration-reconciler handler — an event of a task that no longer revertIssueToNotStartedMock.mockReset().mockResolvedValue(true); }); - /** A later write to A's first task, which ended FAILED. */ const sequencedFailure = () => ({ Records: [taskRecord({ task_id: 'TA', status: 'FAILED', orchestration_id: 'orch_1', sequenceNumber: 'seq-TA' })], }) as never; const isClaim = (cmd: StoreCommand) => String(cmd.input.UpdateExpression).includes('settled_task_id'); + /** A later write to A's first task, which ended FAILED. */ const lateFailure = () => ({ Records: [taskRecord({ task_id: 'TA', status: 'FAILED', orchestration_id: 'orch_1' })], }) as never;