diff --git a/cdk/src/handlers/orchestration-reconciler.ts b/cdk/src/handlers/orchestration-reconciler.ts index 43df42216..4baa75e3e 100644 --- a/cdk/src/handlers/orchestration-reconciler.ts +++ b/cdk/src/handlers/orchestration-reconciler.ts @@ -535,6 +535,22 @@ async function reloadIterationScreenshot(taskId?: string): Promise<{ screenshotU } } +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 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; + } +} + /** Apply one terminal child's reconcile plan. */ async function reconcileTerminalChild(evt: TerminalTaskEvent): Promise { const orchestrationId = evt.orchestrationId!; @@ -646,9 +662,12 @@ 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 && !isIntegrationNode(subIssueId) + && await claimSettle(orchestrationId, subIssueId, evt.taskId) + ) { const channel = settleChannel; const childRef = issueRef(subIssueId, snapshot.meta.credentials_ref); try { 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 0164b658a..27b7d9e5d 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 = {}, ) { @@ -2270,6 +2271,10 @@ describe('orchestration-reconciler handler — an event of a task that no longer revertIssueToNotStartedMock.mockReset().mockResolvedValue(true); }); + 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' })], @@ -2383,6 +2388,82 @@ 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 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' }]); + 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 () => { // A refused skip is not a stale event: only that one dependent is left alone. const store = orchestrationStore([ 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 |