diff --git a/cdk/src/constructs/concurrency-reconciler.ts b/cdk/src/constructs/concurrency-reconciler.ts index c0fed93dd..b28a9e1b6 100644 --- a/cdk/src/constructs/concurrency-reconciler.ts +++ b/cdk/src/constructs/concurrency-reconciler.ts @@ -41,7 +41,7 @@ const RECONCILER_MEMORY_MB = 256; */ export interface ConcurrencyReconcilerProps { /** - * The DynamoDB task table (has UserStatusIndex GSI). + * The DynamoDB task table (reservations are scanned from the base table). */ readonly taskTable: dynamodb.ITable; @@ -59,8 +59,8 @@ export interface ConcurrencyReconcilerProps { /** * Scheduled Lambda that reconciles user concurrency counters by comparing - * the active_count in the concurrency table against actual active tasks - * in the task table. Corrects drift caused by orchestrator crashes. + * active_count against saved task reservations, including approval waits. + * Releases terminal reservations left behind by interrupted cleanup. */ export class ConcurrencyReconciler extends Construct { public readonly fn: lambda.NodejsFunction; @@ -89,6 +89,7 @@ export class ConcurrencyReconciler extends Construct { }); props.taskTable.grantReadData(this.fn); + props.taskTable.grant(this.fn, 'dynamodb:UpdateItem'); props.userConcurrencyTable.grantReadWriteData(this.fn); const schedule = props.schedule ?? Duration.minutes(DEFAULT_SCHEDULE_MINUTES); diff --git a/cdk/src/constructs/stranded-task-reconciler.ts b/cdk/src/constructs/stranded-task-reconciler.ts index cb3dbdbc6..45df79b13 100644 --- a/cdk/src/constructs/stranded-task-reconciler.ts +++ b/cdk/src/constructs/stranded-task-reconciler.ts @@ -55,7 +55,7 @@ export interface StrandedTaskReconcilerProps { /** TaskEventsTable (handler writes task_stranded + task_failed events). */ readonly taskEventsTable: dynamodb.ITable; - /** UserConcurrencyTable (handler decrements active_count on fail). */ + /** UserConcurrencyTable (handler releases the task-owned reservation on fail). */ readonly userConcurrencyTable: dynamodb.ITable; /** @@ -142,7 +142,7 @@ export class StrandedTaskReconciler extends Construct { props.taskTable.grantReadWriteData(this.fn); // TaskEvents: write task_stranded + task_failed events. props.taskEventsTable.grantWriteData(this.fn); - // Concurrency: decrement active_count on fail. + // Concurrency: read/release a task-owned reservation transactionally. props.userConcurrencyTable.grantReadWriteData(this.fn); const schedule = props.schedule ?? Duration.minutes(DEFAULT_SCHEDULE_MINUTES); diff --git a/cdk/src/constructs/user-concurrency-table.ts b/cdk/src/constructs/user-concurrency-table.ts index 223fd3213..200f6a890 100644 --- a/cdk/src/constructs/user-concurrency-table.ts +++ b/cdk/src/constructs/user-concurrency-table.ts @@ -49,7 +49,8 @@ export interface UserConcurrencyTableProps { * * Schema: user_id (PK). Each item holds an atomic counter (active_count) * representing the number of currently running tasks for the user. - * The application layer uses conditional updates for increment/decrement. + * The application layer changes the counter and its reservation_version in + * transactions with per-task reservation markers. */ export class UserConcurrencyTable extends Construct { /** diff --git a/cdk/src/handlers/confirm-uploads.ts b/cdk/src/handlers/confirm-uploads.ts index f1b24ba9a..a60d5c93c 100644 --- a/cdk/src/handlers/confirm-uploads.ts +++ b/cdk/src/handlers/confirm-uploads.ts @@ -152,7 +152,7 @@ export async function handler(event: APIGatewayProxyEvent, context: Context): Pr } // 6b. Pre-check concurrency before expensive screening (fail-fast). - // The actual atomic increment happens in transitionToSubmitted after screening + // The orchestrator reserves capacity atomically after successful submission. // passes. This read-only check avoids wasting Bedrock calls when the user is // already at their concurrency limit. const preCheckAdmitted = await preCheckConcurrency(task.user_id); @@ -439,13 +439,8 @@ async function transitionToSubmitted( const now = new Date().toISOString(); const taskId = task.task_id; - // Admission control — check concurrency before transitioning - const admitted = await checkConcurrency(task.user_id); - if (!admitted) { - return errorResponse(429, ErrorCode.RATE_LIMIT_EXCEEDED, - 'User concurrency limit reached. Wait for a running task to finish or cancel one, then retry.', requestId); - } - + // Submission does not reserve capacity. The orchestrator owns atomic + // admission for every task, including confirmed uploads and queue pickups. // Conditional DynamoDB write: status PENDING_UPLOADS → SUBMITTED try { await ddb.send(new UpdateCommand({ @@ -467,9 +462,7 @@ async function transitionToSubmitted( })); } catch (err: any) { if (err.name === 'ConditionalCheckFailedException') { - // Another caller already transitioned (e.g. cleanup Lambda cancelled - // the task). Roll back the concurrency counter we just incremented. - await decrementConcurrency(task.user_id); + // Another caller already transitioned (e.g. cleanup cancelled the task). // Return current state (idempotent) const current = await ddb.send(new GetCommand({ TableName: TABLE_NAME, @@ -480,9 +473,6 @@ async function transitionToSubmitted( } return errorResponse(404, ErrorCode.TASK_NOT_FOUND, 'Task not found.', requestId); } - // Roll back concurrency counter on any other DDB error (throttling, - // network timeout, etc.) to prevent permanent slot leaks. - await decrementConcurrency(task.user_id); throw err; } @@ -525,7 +515,7 @@ async function transitionToSubmitted( }); } catch (orchErr) { orchestratorInvokeFailed = true; - logger.error('Failed to invoke orchestrator after confirm-uploads — task will be picked up by StrandedTaskReconciler', { + logger.error('Orchestrator dispatch could not be confirmed after confirm-uploads; stranded-task cleanup fails tasks that remain stuck', { error: orchErr instanceof Error ? orchErr.message : String(orchErr), task_id: taskId, request_id: requestId, @@ -543,8 +533,8 @@ async function transitionToSubmitted( }; const responseBody = toTaskDetail(updatedTask); if (orchestratorInvokeFailed) { - (responseBody as any).warning = 'Task was submitted successfully but orchestration dispatch failed. ' + - 'The task will be picked up automatically within minutes by the background reconciler.'; + (responseBody as any).warning = 'Task was submitted, but starting the worker could not be confirmed. ' + + 'Check task status before retrying. Background cleanup marks tasks that remain stuck as failed.'; } return successResponse(200, responseBody, requestId); } @@ -732,8 +722,8 @@ async function buildScreeningConfig(): Promise { /** * Non-mutating read to check if the user is at their concurrency limit. - * Used as a fast pre-check before expensive screening; the actual atomic - * increment happens in checkConcurrency() during transitionToSubmitted. + * Used as an advisory pre-check before expensive screening. The orchestrator + * reserves capacity atomically after submission, queuing if capacity fills. */ async function preCheckConcurrency(userId: string): Promise { try { @@ -745,7 +735,7 @@ async function preCheckConcurrency(userId: string): Promise { return activeCount < MAX_CONCURRENT; } catch (err: any) { // Only swallow DDB throttling errors — these are transient and the atomic - // check in transitionToSubmitted is the authoritative gate. + // orchestrator admission transaction is the authoritative gate. const throttleErrors = ['ProvisionedThroughputExceededException', 'RequestLimitExceeded', 'ThrottlingException']; if (throttleErrors.includes(err?.name)) { logger.warn('Pre-check concurrency throttled — allowing request to proceed', { @@ -765,66 +755,3 @@ async function preCheckConcurrency(userId: string): Promise { throw err; } } - -async function checkConcurrency(userId: string): Promise { - try { - await ddb.send(new UpdateCommand({ - TableName: CONCURRENCY_TABLE_NAME, - Key: { user_id: userId }, - UpdateExpression: 'SET active_count = if_not_exists(active_count, :zero) + :one, updated_at = :now', - ConditionExpression: 'attribute_not_exists(active_count) OR active_count < :max', - ExpressionAttributeValues: { - ':zero': 0, - ':one': 1, - ':max': MAX_CONCURRENT, - ':now': new Date().toISOString(), - }, - })); - return true; - } catch (err: any) { - if (err.name === 'ConditionalCheckFailedException') { - return false; - } - throw err; - } -} - -async function decrementConcurrency(userId: string): Promise { - const maxAttempts = 3; - for (let attempt = 0; attempt < maxAttempts; attempt++) { - try { - await ddb.send(new UpdateCommand({ - TableName: CONCURRENCY_TABLE_NAME, - Key: { user_id: userId }, - UpdateExpression: 'SET active_count = active_count - :one, updated_at = :now', - ConditionExpression: 'attribute_exists(active_count) AND active_count > :zero', - ExpressionAttributeValues: { - ':one': 1, - ':zero': 0, - ':now': new Date().toISOString(), - }, - })); - return; - } catch (err: any) { - if (err.name === 'ConditionalCheckFailedException') { - // Counter already at 0 or doesn't exist — nothing to roll back - return; - } - if (attempt < maxAttempts - 1) { - // Retry transient DDB errors (throttling, network) with backoff - await new Promise(resolve => setTimeout(resolve, 100 * Math.pow(2, attempt))); - continue; - } - logger.error('Failed to decrement concurrency counter after retries (leak possible)', { - user_id: userId, - attempts: maxAttempts, - error: err instanceof Error ? err.message : String(err), - metric_type: 'concurrency_counter_leak', - }); - throw new Error( - `Concurrency counter decrement failed for user ${userId} after ${maxAttempts} attempts. ` + - 'Manual intervention may be required to reset the counter.', - ); - } - } -} diff --git a/cdk/src/handlers/orchestrate-task.ts b/cdk/src/handlers/orchestrate-task.ts index 3f448c133..cab4d55e4 100644 --- a/cdk/src/handlers/orchestrate-task.ts +++ b/cdk/src/handlers/orchestrate-task.ts @@ -43,6 +43,7 @@ import { runPreflightChecks } from './shared/preflight'; import { isAutoRetried, startSessionWithRetry } from './shared/session-start-retry'; import { deleteEcsPayload } from './shared/strategies/ecs-strategy'; import { deleteMicrovmPayload } from './shared/strategies/lambda-microvm-strategy'; +import { releaseTaskSlot } from './shared/task-concurrency'; import type { TaskRecord } from './shared/types'; import { workflowIsReadOnly, workflowRequiresRepo } from './shared/workflows'; @@ -95,7 +96,7 @@ const durableHandler: DurableExecutionHandler = asyn // up, flips QUEUED -> SUBMITTED, and re-invokes this orchestrator. const admitted = await context.step('admission-control', async () => { // Re-read status to detect external cancellation between steps - const current = await loadTask(taskId); + const current = await loadTask(taskId, true); if (TERMINAL_STATUSES.includes(current.status)) { return false; } @@ -131,13 +132,16 @@ const durableHandler: DurableExecutionHandler = asyn }); if (!admitted) { + // A task cancelled after its seat was taken returns it here; the marker + // makes this a no-op for a queued or never-admitted task. + await context.step('release-before-admission', () => releaseTaskSlot(taskId, task.user_id)); return; } // Step 2b: Pre-flight checks — verify external dependencies before consuming AgentCore runtime const preflightPassed = await context.step('pre-flight', async () => { try { - const current = await loadTask(taskId); + const current = await loadTask(taskId, true); if (TERMINAL_STATUSES.includes(current.status)) { return false; } @@ -166,6 +170,7 @@ const durableHandler: DurableExecutionHandler = asyn }); if (!preflightPassed) { + await context.step('release-before-work', () => releaseTaskSlot(taskId, task.user_id)); return; } diff --git a/cdk/src/handlers/reconcile-admission-queue.ts b/cdk/src/handlers/reconcile-admission-queue.ts index 0b08c48bf..849ca9785 100644 --- a/cdk/src/handlers/reconcile-admission-queue.ts +++ b/cdk/src/handlers/reconcile-admission-queue.ts @@ -213,7 +213,9 @@ async function requeueAfterInvokeFailure(taskId: string): Promise { TableName: TASK_TABLE, Key: { task_id: { S: taskId } }, UpdateExpression: 'SET #s = :queued, updated_at = :now, status_created_at = :sca', - ConditionExpression: '#s = :submitted', + // A lost invoke response may hide a successful admission. Never put a + // task that now holds capacity back into the no-reservation queue. + ConditionExpression: '#s = :submitted AND attribute_not_exists(concurrency_slot)', ExpressionAttributeNames: { '#s': 'status' }, ExpressionAttributeValues: { ':queued': { S: 'QUEUED' }, diff --git a/cdk/src/handlers/reconcile-concurrency.ts b/cdk/src/handlers/reconcile-concurrency.ts index 008f0e8a2..4e0828aee 100644 --- a/cdk/src/handlers/reconcile-concurrency.ts +++ b/cdk/src/handlers/reconcile-concurrency.ts @@ -17,108 +17,139 @@ * SOFTWARE. */ -import { DynamoDBClient, ScanCommand, QueryCommand, UpdateItemCommand } from '@aws-sdk/client-dynamodb'; +import { randomUUID } from 'node:crypto'; +import { ScanCommand, type ScanCommandOutput, UpdateCommand } from '@aws-sdk/lib-dynamodb'; +import { ACTIVE_STATUSES, TERMINAL_STATUSES } from '../constructs/task-status'; import { logger } from './shared/logger'; -import { makeClient } from './shared/ua'; +import { releaseTaskSlot, type ReservationTask } from './shared/task-concurrency'; +import { makeDocClient } from './shared/ua'; -const ddb = makeClient(DynamoDBClient); +const ddb = makeDocClient(); const TASK_TABLE = process.env.TASK_TABLE_NAME!; -const CONCURRENCY_TABLE = process.env.USER_CONCURRENCY_TABLE_NAME!; +const COUNTER_TABLE = process.env.USER_CONCURRENCY_TABLE_NAME!; -/** - * Count actual active tasks for a user by querying the UserStatusIndex GSI. - */ -async function countActiveTasks(userId: string): Promise { - let count = 0; - let lastKey: Record | undefined; - - do { - const resp = await ddb.send(new QueryCommand({ - TableName: TASK_TABLE, - IndexName: 'UserStatusIndex', - KeyConditionExpression: 'user_id = :uid', - FilterExpression: '#s IN (:s1, :s2, :s3, :s4)', - ExpressionAttributeNames: { '#s': 'status' }, - ExpressionAttributeValues: { - ':uid': { S: userId }, - ':s1': { S: 'SUBMITTED' }, - ':s2': { S: 'HYDRATING' }, - ':s3': { S: 'RUNNING' }, - ':s4': { S: 'FINALIZING' }, - }, - Select: 'COUNT', - ExclusiveStartKey: lastKey, - })); - count += resp.Count ?? 0; - lastKey = resp.LastEvaluatedKey; - } while (lastKey); +interface CounterSnapshot { + readonly user_id: string; + readonly active_count?: number; + readonly reservation_version?: string; +} - return count; +interface Reservations { + held: number; + ambiguous: boolean; + terminal: string[]; } /** - * Scheduled handler: scan the concurrency table and reconcile each user's - * active_count against actual active tasks in the task table. + * Read counters BEFORE scanning reservations. Every reservation mutation also + * changes its counter revision; a conditional repair then detects changes + * anywhere during the scan, including an increment/decrement with no net change. + * Strong base-table reads avoid the GSI lag that can hide a newly held slot. */ export async function handler(): Promise { logger.info('Concurrency reconciler started'); - let corrected = 0; - let scanned = 0; - let errors = 0; + const counters = new Map(); let lastKey: Record | undefined; - do { - const scanResp = await ddb.send(new ScanCommand({ - TableName: CONCURRENCY_TABLE, + const page: ScanCommandOutput = await ddb.send(new ScanCommand({ + TableName: COUNTER_TABLE, + ConsistentRead: true, + ProjectionExpression: 'user_id, active_count, reservation_version', ExclusiveStartKey: lastKey, })); + for (const row of page.Items ?? []) { + if (typeof row.user_id === 'string') counters.set(row.user_id, row as CounterSnapshot); + } + lastKey = page.LastEvaluatedKey; + } while (lastKey); - for (const rawItem of scanResp.Items ?? []) { - const userId = rawItem.user_id?.S; - const storedCount = Number(rawItem.active_count?.N ?? '0'); - if (!userId) continue; - scanned++; - - try { - const actualCount = await countActiveTasks(userId); + const reservations = new Map(); + do { + const page: ScanCommandOutput = await ddb.send(new ScanCommand({ + TableName: TASK_TABLE, + ConsistentRead: true, + ProjectionExpression: 'task_id, user_id, #status, concurrency_slot', + ExpressionAttributeNames: { '#status': 'status' }, + ExclusiveStartKey: lastKey, + })); + for (const row of page.Items ?? []) { + const task = row as ReservationTask; + if (!task.task_id || !task.user_id) continue; + const active = ACTIVE_STATUSES.some(status => status === task.status); + if (!task.concurrency_slot && !active) continue; + const owned = reservations.get(task.user_id) ?? { held: 0, ambiguous: false, terminal: [] }; + if (task.concurrency_slot?.state === 'held') { + // Terminal tasks still own their seat until release commits. Repair + // that total first, then release terminal reservations through the + // same transaction used by the orchestrator and stranded-task cleaner. + owned.held++; + if (TERMINAL_STATUSES.some(status => status === task.status)) owned.terminal.push(task.task_id); + } else if (active || (task.concurrency_slot && task.concurrency_slot.state !== 'released')) { + // Older active tasks and not-yet-admitted SUBMITTED tasks cannot be + // distinguished by status. Wait for them to settle; never guess a count. + owned.ambiguous = true; + } + reservations.set(task.user_id, owned); + } + lastKey = page.LastEvaluatedKey; + } while (lastKey); - if (storedCount !== actualCount) { - logger.info('Drift detected', { userId, storedCount, actualCount }); - try { - await ddb.send(new UpdateItemCommand({ - TableName: CONCURRENCY_TABLE, - Key: { user_id: { S: userId } }, - UpdateExpression: 'SET active_count = :count, updated_at = :now', - ConditionExpression: 'active_count = :stored', - ExpressionAttributeValues: { - ':count': { N: String(actualCount) }, - ':now': { S: new Date().toISOString() }, - ':stored': { N: String(storedCount) }, - }, - })); - corrected++; - } catch (updateErr: unknown) { - if (updateErr && typeof updateErr === 'object' && 'name' in updateErr && updateErr.name === 'ConditionalCheckFailedException') { - logger.info('Concurrent update detected, skipping', { userId }); - } else { - throw updateErr; - } + let corrected = 0; + let errors = 0; + const users = new Set([...counters.keys(), ...reservations.keys()]); + for (const userId of users) { + const snapshot = counters.get(userId); + const owned = reservations.get(userId) ?? { held: 0, ambiguous: false, terminal: [] }; + try { + const stored = snapshot?.active_count ?? 0; + if (!Number.isSafeInteger(stored)) throw new Error('Concurrency counter is not an integer'); + if (owned.ambiguous) { + logger.warn('Skipping capacity repair while task reservation ownership is ambiguous', { + user_id: userId, error_id: 'CONCURRENCY_RESERVATION_UNKNOWN', + }); + } else if (stored !== owned.held) { + const conditions: string[] = []; + const values: Record = { + ':count': owned.held, ':now': new Date().toISOString(), ':version': randomUUID(), + }; + if (!snapshot) { + conditions.push('attribute_not_exists(user_id)'); + } else { + conditions.push('attribute_exists(user_id)'); + if (snapshot.active_count === undefined) {conditions.push('attribute_not_exists(active_count)');} else { + conditions.push('active_count = :stored'); + values[':stored'] = stored; + } + if (snapshot.reservation_version === undefined) {conditions.push('attribute_not_exists(reservation_version)');} else { + conditions.push('reservation_version = :observed'); + values[':observed'] = snapshot.reservation_version; } } - } catch (err: unknown) { - errors++; - logger.warn('Per-user reconciliation failed, continuing', { - userId, - error: err instanceof Error ? err.message : String(err), - }); + try { + await ddb.send(new UpdateCommand({ + TableName: COUNTER_TABLE, + Key: { user_id: userId }, + UpdateExpression: 'SET active_count = :count, updated_at = :now, reservation_version = :version', + ConditionExpression: conditions.join(' AND '), + ExpressionAttributeValues: values, + })); + corrected++; + logger.info('Corrected capacity counter from saved reservations', { + user_id: userId, stored_count: stored, reservation_count: owned.held, + }); + } catch (error) { + if ((error as { name?: string })?.name !== 'ConditionalCheckFailedException') throw error; + logger.info('Capacity changed during reconciliation; skipped stale repair', { user_id: userId }); + } } + for (const taskId of owned.terminal) await releaseTaskSlot(taskId, userId); + } catch (error) { + errors++; + logger.warn('Per-user capacity reconciliation failed, continuing', { user_id: userId, error: String(error) }); } - - lastKey = scanResp.LastEvaluatedKey; - } while (lastKey); - - if (errors === scanned && scanned > 0) { - logger.error('All users failed reconciliation — possible systemic issue', { scanned, errors }); } - logger.info('Concurrency reconciler finished', { scanned, corrected, errors }); + if (errors === users.size && users.size > 0) { + logger.error('All users failed reconciliation — possible systemic issue', { scanned: users.size, errors }); + } + logger.info('Concurrency reconciler finished', { scanned: users.size, corrected, errors }); } diff --git a/cdk/src/handlers/reconcile-stranded-tasks.ts b/cdk/src/handlers/reconcile-stranded-tasks.ts index 4d5fa988f..040667ec9 100644 --- a/cdk/src/handlers/reconcile-stranded-tasks.ts +++ b/cdk/src/handlers/reconcile-stranded-tasks.ts @@ -48,12 +48,12 @@ import { } from '@aws-sdk/client-dynamodb'; import { ulid } from 'ulid'; import { logger } from './shared/logger'; +import { releaseTaskSlot } from './shared/task-concurrency'; import { makeClient } from './shared/ua'; const ddb = makeClient(DynamoDBClient); const TASK_TABLE = process.env.TASK_TABLE_NAME!; const EVENTS_TABLE = process.env.TASK_EVENTS_TABLE_NAME!; -const CONCURRENCY_TABLE = process.env.USER_CONCURRENCY_TABLE_NAME!; /** Stranded-task timeout. The orchestrator Lambda is async-invoked and * the agent runtime has a cold-start path; 1200 s covers Lambda retries @@ -286,32 +286,10 @@ async function failStrandedTask(task: StrandedCandidate): Promise { } } - // 3. Release the concurrency slot. Best-effort; drift is later corrected - // by the concurrency reconciler. - try { - await ddb.send(new UpdateItemCommand({ - TableName: CONCURRENCY_TABLE, - Key: { user_id: { S: task.user_id } }, - UpdateExpression: 'SET active_count = active_count - :one, updated_at = :now', - ConditionExpression: 'active_count > :zero', - ExpressionAttributeValues: { - ':one': { N: '1' }, - ':zero': { N: '0' }, - ':now': { S: now }, - }, - })); - } catch (decrErr: unknown) { - if (decrErr && typeof decrErr === 'object' && 'name' in decrErr - && decrErr.name !== 'ConditionalCheckFailedException') { - logger.warn('Failed to decrement concurrency for stranded task', { - task_id: task.task_id, - user_id: task.user_id, - error: decrErr instanceof Error ? decrErr.message : String(decrErr), - }); - } - // ConditionalCheckFailedException means the counter is already 0 — - // drift the concurrency reconciler will eventually catch. - } + // 3. Release this task's reservation. The marker makes the release exactly + // once even if the orchestrator finalizes the same task; a failure here + // leaves the seat held, which the concurrency reconciler then releases. + await releaseTaskSlot(task.task_id, task.user_id); return true; } diff --git a/cdk/src/handlers/shared/orchestrator.ts b/cdk/src/handlers/shared/orchestrator.ts index ec74f4aea..c2603b934 100644 --- a/cdk/src/handlers/shared/orchestrator.ts +++ b/cdk/src/handlers/shared/orchestrator.ts @@ -32,6 +32,7 @@ import { parseRef } from './registry/ref'; import { RegistryResolutionError, type ResolvedAsset } from './registry/types'; import { loadRepoConfig, type BlueprintConfig, type ComputeType } from './repo-config'; import { resolveUrlAttachments } from './resolve-url-attachments'; +import { acquireTaskSlot, releaseTaskSlot } from './task-concurrency'; import { APPROVAL_GATE_CAP_MAX, APPROVAL_GATE_CAP_MIN, type AgentAttachmentPayload, type AttachmentRecord, type TaskRecord } from './types'; import { makeClient, makeDocClient } from './ua'; import { computeTtlEpoch, DEFAULT_MAX_TURNS } from './validation'; @@ -41,7 +42,6 @@ const ddb = makeDocClient(); const TABLE_NAME = process.env.TASK_TABLE_NAME!; const EVENTS_TABLE_NAME = process.env.TASK_EVENTS_TABLE_NAME!; -const CONCURRENCY_TABLE_NAME = process.env.USER_CONCURRENCY_TABLE_NAME!; const RUNTIME_ARN = process.env.RUNTIME_ARN!; const MAX_CONCURRENT = Number(process.env.MAX_CONCURRENT_TASKS_PER_USER ?? '3'); const TASK_RETENTION_DAYS = Number(process.env.TASK_RETENTION_DAYS ?? '90'); @@ -180,10 +180,11 @@ function substrateNoun(computeType: ComputeType | undefined): string { * @returns the task record. * @throws Error if the task is not found. */ -export async function loadTask(taskId: string): Promise { +export async function loadTask(taskId: string, consistentRead = false): Promise { const result = await ddb.send(new GetCommand({ TableName: TABLE_NAME, Key: { task_id: taskId }, + ...(consistentRead && { ConsistentRead: true }), })); if (!result.Item) { throw new Error(`Task ${taskId} not found`); @@ -192,31 +193,12 @@ export async function loadTask(taskId: string): Promise { } /** - * Admission control: check user concurrency and increment counter. + * Admission control: acquire or recover this task's capacity reservation. * @param task - the task record. * @returns true if admitted, false if concurrency limit reached. */ export async function admissionControl(task: TaskRecord): Promise { - try { - await ddb.send(new UpdateCommand({ - TableName: CONCURRENCY_TABLE_NAME, - Key: { user_id: task.user_id }, - UpdateExpression: 'SET active_count = if_not_exists(active_count, :zero) + :one, updated_at = :now', - ConditionExpression: 'attribute_not_exists(active_count) OR active_count < :max', - ExpressionAttributeValues: { - ':zero': 0, - ':one': 1, - ':max': MAX_CONCURRENT, - ':now': new Date().toISOString(), - }, - })); - return true; - } catch (err: unknown) { - if (err && typeof err === 'object' && 'name' in err && err.name === 'ConditionalCheckFailedException') { - return false; - } - throw err; - } + return acquireTaskSlot(task.task_id, task.user_id, MAX_CONCURRENT); } /** @@ -267,11 +249,15 @@ export async function transitionTask( } } + // An admitted task holds a reservation; it must never be queued again. + const condition = fromStatus === TaskStatus.SUBMITTED && toStatus === TaskStatus.QUEUED + ? '#status = :fromStatus AND attribute_not_exists(concurrency_slot)' + : '#status = :fromStatus'; await ddb.send(new UpdateCommand({ TableName: TABLE_NAME, Key: { task_id: taskId }, UpdateExpression: updateExpression, - ConditionExpression: '#status = :fromStatus', + ConditionExpression: condition, ExpressionAttributeNames: expressionNames, ExpressionAttributeValues: expressionValues, })); @@ -1158,7 +1144,12 @@ export async function pollTaskStatus( } /** - * Finalize a task: write terminal status, emit events, release concurrency. + * Finalize a task: write terminal status, emit events, release its reservation. + * + * The reservation is released in ``finally`` and only once the task is + * terminal (``releaseTaskSlot`` checks its marker), so a crash, an event + * failure, a durable replay or a competing cleaner cannot release it twice, + * and a still-active task keeps its seat. * @param taskId - the task ID. * @param pollState - the final poll state. * @param userId - the user who owns the task. @@ -1168,7 +1159,14 @@ export async function finalizeTask( pollState: PollState, userId: string, ): Promise { - const task = await loadTask(taskId); + try { + await finalizeTaskOutcome(taskId, pollState, await loadTask(taskId, true)); + } finally { + await releaseTaskSlot(taskId, userId); + } +} + +async function finalizeTaskOutcome(taskId: string, pollState: PollState, task: TaskRecord): Promise { const currentStatus = task.status; // Correlation envelope on this function's own log lines too, not just the // events it emits — admission→terminal logs must join by {user_id, repo}. @@ -1202,7 +1200,7 @@ export async function finalizeTask( transitioned = true; } catch (err) { // Task may have transitioned concurrently (e.g. agent wrote terminal status). - // Re-read to avoid double-decrement or contradictory events. + // Re-read to report the terminal status that actually won. log.warn('Finalization transition to FAILED (heartbeat) failed, task may have transitioned concurrently', { error: err instanceof Error ? err.message : String(err), }); @@ -1212,21 +1210,19 @@ export async function finalizeTask( reason: 'agent_heartbeat_stale', poll_attempts: pollState.attempts, }, correlation); - await decrementConcurrency(userId); } else { // Transition failed — re-read task to determine actual state. // If already terminal the block below will handle TTL + concurrency. - const reread = await loadTask(taskId); + const reread = await loadTask(taskId, true); if (TERMINAL_STATUSES.includes(reread.status)) { log.info('Heartbeat path: task already terminal after failed transition', { status: reread.status }); await emitTaskEvent(taskId, `task_${reread.status.toLowerCase()}`, { final_status: reread.status, poll_attempts: pollState.attempts, }, correlation); - await decrementConcurrency(userId); } else { - log.warn('Heartbeat path: task in unexpected state after failed transition, releasing concurrency', { status: reread.status }); - await decrementConcurrency(userId); + log.warn('Heartbeat path: task in unexpected state after failed transition, keeping its reservation until terminal', { status: reread.status }); + throw new Error(`Heartbeat finalization left task ${taskId} active in ${reread.status}`); } } return; @@ -1293,21 +1289,20 @@ export async function finalizeTask( final_status: currentStatus, poll_attempts: pollState.attempts, }, correlation); - await decrementConcurrency(userId); return; } - // If still RUNNING / FINALIZING / AWAITING_APPROVAL after the poll - // window closes, transition to TIMED_OUT. AWAITING_APPROVAL uses the - // same transition — the stranded-approval reconciler is a secondary - // safety net with a longer timeout for tasks the orchestrator already - // lost track of. + // If still RUNNING / FINALIZING / AWAITING_APPROVAL after the poll window + // closes, terminate through an allowed transition: AWAITING_APPROVAL permits + // FAILED, not TIMED_OUT. The previous TIMED_OUT attempt for an approval wait + // was rejected by VALID_TRANSITIONS, left the task active, and still freed + // its seat. if ( currentStatus === TaskStatus.RUNNING || currentStatus === TaskStatus.FINALIZING || currentStatus === TaskStatus.AWAITING_APPROVAL ) { - const terminalStatus = TaskStatus.TIMED_OUT; + const terminalStatus = currentStatus === TaskStatus.AWAITING_APPROVAL ? TaskStatus.FAILED : TaskStatus.TIMED_OUT; try { await transitionTask(taskId, currentStatus, terminalStatus, { completed_at: new Date().toISOString(), @@ -1316,16 +1311,21 @@ export async function finalizeTask( : 'Orchestrator poll timeout exceeded', }); } catch (err) { - // Task may have transitioned concurrently — re-read and accept + // Accept a committed terminal winner; otherwise retry finalization. log.warn('Finalization transition failed, task may have transitioned concurrently', { error: err instanceof Error ? err.message : String(err) }); + const winner = await loadTask(taskId, true); + if (!TERMINAL_STATUSES.includes(winner.status)) throw err; + await emitTaskEvent(taskId, `task_${winner.status.toLowerCase()}`, { + final_status: winner.status, poll_attempts: pollState.attempts, + }, correlation); + return; } - await emitTaskEvent(taskId, 'task_timed_out', { + await emitTaskEvent(taskId, terminalStatus === TaskStatus.FAILED ? 'task_failed' : 'task_timed_out', { reason: currentStatus === TaskStatus.AWAITING_APPROVAL ? 'approval_poll_timeout' : 'poll_timeout', poll_attempts: pollState.attempts, }, correlation); - await decrementConcurrency(userId); return; } @@ -1339,18 +1339,23 @@ export async function finalizeTask( }); } catch (err) { log.warn('Finalization transition from HYDRATING failed, task may have transitioned concurrently', { error: err instanceof Error ? err.message : String(err) }); + const winner = await loadTask(taskId, true); + if (!TERMINAL_STATUSES.includes(winner.status)) throw err; + await emitTaskEvent(taskId, `task_${winner.status.toLowerCase()}`, { + final_status: winner.status, poll_attempts: pollState.attempts, + }, correlation); + return; } await emitTaskEvent(taskId, 'task_failed', { reason: 'session_never_started', poll_attempts: pollState.attempts, }, correlation); - await decrementConcurrency(userId); return; } - // Unexpected state — log and release concurrency + // Unexpected active state — retain its reservation until terminal. log.error('Unexpected task state during finalization', { status: currentStatus }); - await decrementConcurrency(userId); + throw new Error(`Cannot finalize task ${taskId} in ${currentStatus}`); } /** @@ -1406,7 +1411,7 @@ export async function queueTask(task: TaskRecord): Promise { * @param fromStatus - the current status. * @param errorMessage - the error reason. * @param userId - the user who owns the task. - * @param releaseConcurrency - whether to decrement the concurrency counter. + * @param releaseConcurrency - whether to release this task's held reservation. * @param repo - optional target repo (`owner/repo`) for the correlation * envelope; omit for repo-less workflows. */ @@ -1430,41 +1435,18 @@ export async function failTask( log.warn('Failed to transition task to FAILED', { error: err instanceof Error ? err.message : String(err), }); + // Only a committed terminal state may release; an active task keeps its seat. + const current = await loadTask(taskId, true); + if (!TERMINAL_STATUSES.includes(current.status)) throw err; } - // Only emit / release concurrency after a successful transition. Callers such as - // orchestrate-task rethrow after failTask; Durable Execution retries the step and - // would otherwise re-run emit + decrement while the task is already FAILED. - if (transitioned) { - await emitTaskEvent(taskId, 'task_failed', { error_message: errorMessage }, { user_id: userId, repo }); - if (releaseConcurrency) { - await decrementConcurrency(userId); - } - } -} - -/** - * Decrement the user's concurrency counter (best-effort). - * @param userId - the user ID. - */ -async function decrementConcurrency(userId: string): Promise { + // A replay may find the FAILED write already committed. Events remain + // transition-owned; releasing the marker-guarded reservation is safe to repeat. try { - await ddb.send(new UpdateCommand({ - TableName: CONCURRENCY_TABLE_NAME, - Key: { user_id: userId }, - UpdateExpression: 'SET active_count = active_count - :one, updated_at = :now', - ConditionExpression: 'active_count > :zero', - ExpressionAttributeValues: { - ':one': 1, - ':zero': 0, - ':now': new Date().toISOString(), - }, - })); - } catch (err: unknown) { - if (err && typeof err === 'object' && 'name' in err && err.name === 'ConditionalCheckFailedException') { - logger.info('Concurrency counter already at zero, nothing to decrement', { user_id: userId }); - } else { - logger.warn('Failed to decrement concurrency counter', { user_id: userId, error: err instanceof Error ? err.message : String(err) }); + if (transitioned) { + await emitTaskEvent(taskId, 'task_failed', { error_message: errorMessage }, { user_id: userId, repo }); } + } finally { + if (releaseConcurrency) await releaseTaskSlot(taskId, userId); } } diff --git a/cdk/src/handlers/shared/task-concurrency.ts b/cdk/src/handlers/shared/task-concurrency.ts new file mode 100644 index 000000000..638bd35d4 --- /dev/null +++ b/cdk/src/handlers/shared/task-concurrency.ts @@ -0,0 +1,232 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { randomUUID } from 'node:crypto'; +import { setTimeout as delay } from 'node:timers/promises'; +import { GetCommand, TransactWriteCommand } from '@aws-sdk/lib-dynamodb'; +import { logger } from './logger'; +import { makeDocClient } from './ua'; +import { ACTIVE_STATUSES, TaskStatus, TERMINAL_STATUSES } from '../../constructs/task-status'; + +/** Internal TaskTable data; a released task cannot acquire another reservation. */ +export interface ReservationTask { + readonly task_id: string; + readonly user_id: string; + readonly status: string; + readonly concurrency_slot?: { + readonly state: 'held' | 'released'; + readonly acquired_at: string; + readonly released_at?: string; + }; +} + +const ddb = makeDocClient(); +const TASK_TABLE = process.env.TASK_TABLE_NAME!; +const COUNTER_TABLE = process.env.USER_CONCURRENCY_TABLE_NAME!; + +function terminal(status: string): boolean { + return TERMINAL_STATUSES.some(value => value === status); +} + +async function readTask(taskId: string, userId: string): Promise { + const result = await ddb.send(new GetCommand({ + TableName: TASK_TABLE, Key: { task_id: taskId }, ConsistentRead: true, + })); + const task = result.Item as ReservationTask | undefined; + if (task && task.user_id !== userId) throw new Error('Concurrency reservation owner does not match task owner'); + return task; +} + +function conditionalFailure(error: unknown, index: number): boolean { + const failure = error as { name?: string; CancellationReasons?: { Code?: string }[] }; + return failure?.name === 'TransactionCanceledException' + && failure.CancellationReasons?.[index]?.Code === 'ConditionalCheckFailed'; +} + +/** + * The SDK does not retry TransactionCanceledException when another task is + * updating the same user's counter. Retry only explicit transaction conflicts; + * conditional failures still belong to the admission/release state machine. + */ +async function sendReservationTransaction( + command: TransactWriteCommand, + taskId: string, + userId: string, +): Promise { + const maxAttempts = 5; + const baseDelayMs = 50; + for (let attempt = 1; attempt <= maxAttempts; attempt++) { + try { + // Keep the exact transaction and client token across retries. + await ddb.send(command); + return; + } catch (error) { + const failure = error as { name?: string; CancellationReasons?: { Code?: string }[] }; + const codes = failure?.CancellationReasons?.map(reason => reason.Code); + const conflict = failure?.name === 'TransactionCanceledException' + && codes?.includes('TransactionConflict') + && codes.every(code => code === 'None' || code === 'TransactionConflict'); + if (!conflict) throw error; + if (attempt === maxAttempts) { + logger.warn('Capacity transaction contention exhausted bounded retries', { + task_id: taskId, + user_id: userId, + attempts: attempt, + error_id: 'CONCURRENCY_TRANSACTION_CONFLICT', + cancellation_codes: codes, + }); + throw error; + } + await delay(Math.floor(Math.random() * baseDelayMs * 2 ** (attempt - 1))); + } + } +} + +/** Reserve once per task, including after a lost transaction acknowledgement. */ +export async function acquireTaskSlot(taskId: string, userId: string, limit: number): Promise { + const current = await readTask(taskId, userId); + if (!current) throw new Error(`Cannot reserve capacity for missing task ${taskId}`); + if (current.concurrency_slot?.state === 'held') { + return ACTIVE_STATUSES.some(status => status === current.status); + } + if (current.status !== TaskStatus.SUBMITTED || current.concurrency_slot) return false; + + const now = new Date().toISOString(); + const revision = randomUUID(); + try { + await sendReservationTransaction(new TransactWriteCommand({ + ClientRequestToken: revision, + TransactItems: [ + { + Update: { + TableName: TASK_TABLE, + Key: { task_id: taskId }, + UpdateExpression: 'SET concurrency_slot = :slot', + ConditionExpression: 'user_id = :user AND #status = :submitted AND attribute_not_exists(concurrency_slot)', + ExpressionAttributeNames: { '#status': 'status' }, + ExpressionAttributeValues: { + ':slot': { state: 'held', acquired_at: now }, + ':user': userId, + ':submitted': TaskStatus.SUBMITTED, + }, + }, + }, + { + Update: { + TableName: COUNTER_TABLE, + Key: { user_id: userId }, + UpdateExpression: 'SET active_count = if_not_exists(active_count, :zero) + :one, ' + + 'updated_at = :now, reservation_version = :version', + ConditionExpression: 'attribute_not_exists(active_count) OR active_count < :max', + ExpressionAttributeValues: { + ':zero': 0, ':one': 1, ':max': limit, ':now': now, ':version': revision, + }, + }, + }, + ], + }), taskId, userId); + return true; + } catch (error) { + // A competing invocation or a lost successful response may have reserved it. + const latest = await readTask(taskId, userId); + if (latest?.concurrency_slot?.state === 'held') { + return ACTIVE_STATUSES.some(status => status === latest.status); + } + if (!latest || latest.status !== TaskStatus.SUBMITTED || latest.concurrency_slot) return false; + if (conditionalFailure(error, 1)) return false; // Capacity was full. + throw error; // Throttling/conflict/outage is not evidence that capacity is full. + } +} + +/** + * Return a terminal task's reservation atomically with its counter update. + * Never infer ownership from status alone: legacy/unadmitted tasks have no + * marker and cannot return another task's seat. Reconciliation handles drift. + */ +export async function releaseTaskSlot(taskId: string, userId: string): Promise { + const current = await readTask(taskId, userId); + if (!current || !terminal(current.status) || current.concurrency_slot?.state !== 'held') return false; + + let emptyCounter = false; + for (let attempt = 0; attempt < 2; attempt++) { + const now = new Date().toISOString(); + const revision = randomUUID(); + try { + await sendReservationTransaction(new TransactWriteCommand({ + ClientRequestToken: revision, + TransactItems: [ + { + Update: { + TableName: TASK_TABLE, + Key: { task_id: taskId }, + UpdateExpression: 'SET concurrency_slot.#state = :released, concurrency_slot.released_at = :now', + ConditionExpression: 'user_id = :user AND concurrency_slot.#state = :held ' + + 'AND #status IN (:completed, :failed, :cancelled, :timedOut)', + ExpressionAttributeNames: { '#state': 'state', '#status': 'status' }, + ExpressionAttributeValues: { + ':user': userId, + ':held': 'held', + ':released': 'released', + ':now': now, + ':completed': TaskStatus.COMPLETED, + ':failed': TaskStatus.FAILED, + ':cancelled': TaskStatus.CANCELLED, + ':timedOut': TaskStatus.TIMED_OUT, + }, + }, + }, + { + Update: { + TableName: COUNTER_TABLE, + Key: { user_id: userId }, + UpdateExpression: emptyCounter + ? 'SET active_count = if_not_exists(active_count, :zero), updated_at = :now, reservation_version = :version' + : 'SET active_count = active_count - :one, updated_at = :now, reservation_version = :version', + ConditionExpression: emptyCounter + ? 'attribute_not_exists(active_count) OR active_count >= :zero' + : 'active_count > :zero', + ExpressionAttributeValues: { + ':zero': 0, ...(!emptyCounter && { ':one': 1 }), ':now': now, ':version': revision, + }, + }, + }, + ], + }), taskId, userId); + if (emptyCounter) { + logger.warn('Released task reservation whose counter was already empty', { + task_id: taskId, user_id: userId, error_id: 'CONCURRENCY_EMPTY_COUNTER', + }); + } + return true; + } catch (error) { + const latest = await readTask(taskId, userId); + if (latest?.concurrency_slot?.state === 'released') return false; + if (!latest || !terminal(latest.status) || latest.concurrency_slot?.state !== 'held') return false; + if (!emptyCounter && conditionalFailure(error, 1)) { + // This attempt observed no positive count. Close its marker without + // subtracting from seats reserved since then. A concurrent repair may + // leave an overcount, which a later revision-guarded sweep can correct. + emptyCounter = true; + continue; + } + throw error; + } + } + throw new Error(`Could not release capacity reservation for task ${taskId}`); +} diff --git a/cdk/test/handlers/orchestrate-task.test.ts b/cdk/test/handlers/orchestrate-task.test.ts index d74d30c5a..717731057 100644 --- a/cdk/test/handlers/orchestrate-task.test.ts +++ b/cdk/test/handlers/orchestrate-task.test.ts @@ -19,6 +19,12 @@ // --- Mocks --- const mockDdbSend = jest.fn(); +const mockAcquireTaskSlot = jest.fn(); +const mockReleaseTaskSlot = jest.fn(); +jest.mock('../../src/handlers/shared/task-concurrency', () => ({ + acquireTaskSlot: (...args: unknown[]) => mockAcquireTaskSlot(...args), + releaseTaskSlot: (...args: unknown[]) => mockReleaseTaskSlot(...args), +})); jest.mock('@aws-sdk/client-dynamodb', () => ({ DynamoDBClient: jest.fn(() => ({})) })); jest.mock('@aws-sdk/lib-dynamodb', () => ({ DynamoDBDocumentClient: { from: jest.fn(() => ({ send: mockDdbSend })) }, @@ -109,6 +115,8 @@ beforeEach(() => { jest.clearAllMocks(); ulidCounter = 0; mockLoadRepoConfig.mockResolvedValue(null); + mockAcquireTaskSlot.mockReset().mockResolvedValue(true); + mockReleaseTaskSlot.mockReset().mockResolvedValue(true); }); describe('loadTask', () => { @@ -125,22 +133,16 @@ describe('loadTask', () => { }); describe('admissionControl', () => { - test('returns true when concurrency slot is available', async () => { - mockDdbSend.mockResolvedValueOnce({}); - const result = await admissionControl(baseTask as any); - expect(result).toBe(true); + test('reserves using the task identity and configured user limit', async () => { + expect(await admissionControl(baseTask as any)).toBe(true); + expect(mockAcquireTaskSlot).toHaveBeenCalledWith('TASK001', 'user-123', 3); }); - - test('returns false when concurrency limit reached', async () => { - const condErr = new Error('Conditional check failed'); - condErr.name = 'ConditionalCheckFailedException'; - mockDdbSend.mockRejectedValueOnce(condErr); - const result = await admissionControl(baseTask as any); - expect(result).toBe(false); + test('returns false when no reservation was acquired', async () => { + mockAcquireTaskSlot.mockResolvedValue(false); + expect(await admissionControl(baseTask as any)).toBe(false); }); - - test('throws on unexpected DDB errors', async () => { - mockDdbSend.mockRejectedValueOnce(new Error('DynamoDB error')); + test('propagates an outage so durable execution can retry', async () => { + mockAcquireTaskSlot.mockRejectedValue(new Error('DynamoDB error')); await expect(admissionControl(baseTask as any)).rejects.toThrow('DynamoDB error'); }); }); @@ -1317,34 +1319,33 @@ describe('finalizeTask', () => { expect(eventCall.input.Item.metadata.reason).toBe('session_never_started'); }); - test('releases concurrency for unexpected task state', async () => { + test('an unexpected active state keeps its reservation and is retried', async () => { mockDdbSend .mockResolvedValueOnce({ Item: { ...baseTask, status: 'SUBMITTED' } }) // loadTask - .mockResolvedValue({}); // decrementConcurrency - await finalizeTask('TASK001', { attempts: 5, lastStatus: 'SUBMITTED' }, 'user-123'); - // Should still call decrementConcurrency (UpdateCommand for user concurrency) - const lastCall = mockDdbSend.mock.calls[mockDdbSend.mock.calls.length - 1][0]; - expect(lastCall.input.Key).toEqual({ user_id: 'user-123' }); + .mockResolvedValue({}); + await expect(finalizeTask('TASK001', { attempts: 5, lastStatus: 'SUBMITTED' }, 'user-123')) + .rejects.toThrow('Cannot finalize task TASK001 in SUBMITTED'); + // Release is still attempted, but the marker keeps an active task's seat. + expect(mockReleaseTaskSlot).toHaveBeenCalledWith('TASK001', 'user-123'); }); - test('resolves without throwing when decrementConcurrency hits ConditionalCheckFailedException', async () => { - const condErr = new Error('Conditional check failed'); - condErr.name = 'ConditionalCheckFailedException'; + test('approval wait past the poll window fails (a valid transition) instead of timing out', async () => { mockDdbSend - .mockResolvedValueOnce({ Item: { ...baseTask, status: 'COMPLETED', memory_written: true } }) // loadTask - .mockResolvedValueOnce({}) // TTL stamp - .mockResolvedValueOnce({}) // emitTaskEvent - .mockRejectedValueOnce(condErr); // decrementConcurrency CCF - await expect(finalizeTask('TASK001', { attempts: 10, lastStatus: 'COMPLETED' }, 'user-123')).resolves.toBeUndefined(); + .mockResolvedValueOnce({ Item: { ...baseTask, status: 'AWAITING_APPROVAL' } }) // loadTask + .mockResolvedValue({}); + await finalizeTask('TASK001', { attempts: 5, lastStatus: 'AWAITING_APPROVAL' }, 'user-123'); + const transition = mockDdbSend.mock.calls.find(([command]) => command.input?.ExpressionAttributeValues?.[':toStatus'])?.[0]; + expect(transition.input.ExpressionAttributeValues[':toStatus']).toBe('FAILED'); + expect(mockReleaseTaskSlot).toHaveBeenCalledWith('TASK001', 'user-123'); }); - test('resolves without throwing when decrementConcurrency hits a non-CCF error', async () => { + test('a release failure propagates so durable execution retries finalization', async () => { mockDdbSend .mockResolvedValueOnce({ Item: { ...baseTask, status: 'COMPLETED', memory_written: true } }) // loadTask - .mockResolvedValueOnce({}) // TTL stamp - .mockResolvedValueOnce({}) // emitTaskEvent - .mockRejectedValueOnce(new Error('DDB timeout')); // decrementConcurrency non-CCF - await expect(finalizeTask('TASK001', { attempts: 10, lastStatus: 'COMPLETED' }, 'user-123')).resolves.toBeUndefined(); + .mockResolvedValue({}); + mockReleaseTaskSlot.mockRejectedValueOnce(new Error('DDB timeout')); + await expect(finalizeTask('TASK001', { attempts: 10, lastStatus: 'COMPLETED' }, 'user-123')) + .rejects.toThrow('DDB timeout'); }); }); @@ -1358,8 +1359,7 @@ describe('failTask', () => { test('releases concurrency when requested', async () => { mockDdbSend.mockResolvedValue({}); await failTask('TASK001', 'HYDRATING', 'hydration error', 'user-123', true); - // transitionTask + emitTaskEvent + decrementConcurrency = 3 calls - expect(mockDdbSend).toHaveBeenCalledTimes(3); + expect(mockReleaseTaskSlot).toHaveBeenCalledWith('TASK001', 'user-123'); }); test('transitions from HYDRATING to FAILED when called with HYDRATING status', async () => { @@ -1371,24 +1371,29 @@ describe('failTask', () => { expect(transitionCall.input.ExpressionAttributeValues[':toStatus']).toBe('FAILED'); }); - test('handles transition failure gracefully without emitting when not transitioned', async () => { - mockDdbSend.mockRejectedValueOnce(new Error('Condition failed')); // transitionTask only + test('a committed terminal winner is accepted without another failure event', async () => { + mockDdbSend.mockRejectedValueOnce(new Error('Condition failed')) + .mockResolvedValueOnce({ Item: { ...baseTask, status: 'CANCELLED' } }); await expect(failTask('TASK001', 'SUBMITTED', 'error', 'user-123', false)).resolves.toBeUndefined(); - expect(mockDdbSend).toHaveBeenCalledTimes(1); + expect(mockDdbSend.mock.calls.some(([command]) => command._type === 'Put')).toBe(false); + }); + + test('failure to persist a terminal state propagates without releasing an active task', async () => { + mockDdbSend.mockRejectedValueOnce(new Error('write unavailable')) + .mockResolvedValueOnce({ Item: { ...baseTask, status: 'HYDRATING' } }); + await expect(failTask('TASK001', 'HYDRATING', 'error', 'user-123', true)).rejects.toThrow('write unavailable'); + expect(mockReleaseTaskSlot).not.toHaveBeenCalled(); }); - test('second failTask does not re-emit or re-decrement when transition fails (idempotent under step retry)', async () => { + test('failure replay rechecks release without duplicating the failure event', async () => { mockDdbSend.mockResolvedValue({}); await failTask('TASK001', 'HYDRATING', 'first failure', 'user-123', true); - expect(mockDdbSend).toHaveBeenCalledTimes(3); // transition + emit + decrement - mockDdbSend.mockClear(); - const condErr = new Error('The conditional request failed'); - condErr.name = 'ConditionalCheckFailedException'; - mockDdbSend.mockRejectedValueOnce(condErr); // already FAILED — transition no-ops - - await expect(failTask('TASK001', 'HYDRATING', 'durable replay', 'user-123', true)).resolves.toBeUndefined(); - expect(mockDdbSend).toHaveBeenCalledTimes(1); // transition attempt only; no Put, no concurrency Update + mockDdbSend.mockRejectedValueOnce(new Error('already FAILED')) + .mockResolvedValueOnce({ Item: { ...baseTask, status: 'FAILED' } }); + await expect(failTask('TASK001', 'HYDRATING', 'replay', 'user-123', true)).resolves.toBeUndefined(); + expect(mockDdbSend.mock.calls.some(([command]) => command._type === 'Put')).toBe(false); + expect(mockReleaseTaskSlot).toHaveBeenCalledTimes(2); }); }); @@ -1637,9 +1642,8 @@ describe('finalizeTask — memory fallback', () => { // Should not throw — the try-catch in finalizeTask prevents crash await finalizeTask('TASK001', { attempts: 10, lastStatus: 'COMPLETED' }, 'user-123'); expect(mockWriteMinimalEpisode).toHaveBeenCalled(); - // decrementConcurrency should still be called (last UpdateCommand for user concurrency) - const lastCall = mockDdbSend.mock.calls[mockDdbSend.mock.calls.length - 1][0]; - expect(lastCall.input.Key).toEqual({ user_id: 'user-123' }); + // The reservation is still released after the fail-open memory write. + expect(mockReleaseTaskSlot).toHaveBeenCalledWith('TASK001', 'user-123'); }); test('converts string duration_s and cost_usd to numbers', async () => { diff --git a/cdk/test/handlers/reconcile-admission-queue.test.ts b/cdk/test/handlers/reconcile-admission-queue.test.ts index 6d3983fe3..38f4894de 100644 --- a/cdk/test/handlers/reconcile-admission-queue.test.ts +++ b/cdk/test/handlers/reconcile-admission-queue.test.ts @@ -279,7 +279,7 @@ describe('reconcile-admission-queue — races and failures', () => { expect(updates[0].input.ConditionExpression).toBe('#s = :queued'); expect(updates[0].input.ExpressionAttributeValues[':submitted']).toEqual({ S: 'SUBMITTED' }); // Restore: guarded on SUBMITTED, sets QUEUED with a fresh QUEUED# status key. - expect(updates[1].input.ConditionExpression).toBe('#s = :submitted'); + expect(updates[1].input.ConditionExpression).toBe('#s = :submitted AND attribute_not_exists(concurrency_slot)'); expect(updates[1].input.ExpressionAttributeValues[':queued']).toEqual({ S: 'QUEUED' }); expect(updates[1].input.ExpressionAttributeValues[':sca'].S).toMatch(/^QUEUED#/); }); diff --git a/cdk/test/handlers/reconcile-concurrency.test.ts b/cdk/test/handlers/reconcile-concurrency.test.ts index d93e1bf9d..ae58dc687 100644 --- a/cdk/test/handlers/reconcile-concurrency.test.ts +++ b/cdk/test/handlers/reconcile-concurrency.test.ts @@ -17,214 +17,127 @@ * SOFTWARE. */ -// --- Mocks --- -const mockDdbSend = jest.fn(); -jest.mock('@aws-sdk/client-dynamodb', () => ({ - DynamoDBClient: jest.fn(() => ({ send: mockDdbSend })), - ScanCommand: jest.fn((input: unknown) => ({ _type: 'Scan', input })), - QueryCommand: jest.fn((input: unknown) => ({ _type: 'Query', input })), - UpdateItemCommand: jest.fn((input: unknown) => ({ _type: 'UpdateItem', input })), +const mockSend = jest.fn(); +const mockRelease = jest.fn(); +jest.mock('@aws-sdk/lib-dynamodb', () => ({ + ScanCommand: jest.fn((input: unknown) => ({ kind: 'scan', input })), + UpdateCommand: jest.fn((input: unknown) => ({ kind: 'update', input })), +})); +jest.mock('../../src/handlers/shared/ua', () => ({ makeDocClient: () => ({ send: mockSend }) })); +jest.mock('../../src/handlers/shared/task-concurrency', () => ({ + releaseTaskSlot: (...args: unknown[]) => mockRelease(...args), })); - -// Set env vars before importing process.env.TASK_TABLE_NAME = 'Tasks'; -process.env.USER_CONCURRENCY_TABLE_NAME = 'UserConcurrency'; - +process.env.USER_CONCURRENCY_TABLE_NAME = 'Counters'; import { handler } from '../../src/handlers/reconcile-concurrency'; +function held(id: string, user = 'user', status = 'RUNNING') { + return { task_id: id, user_id: user, status, concurrency_slot: { state: 'held' } }; +} +function seed(counters: object[], tasks: object[]) { + mockSend.mockResolvedValueOnce({ Items: counters }).mockResolvedValueOnce({ Items: tasks }).mockResolvedValue({}); +} +function updates() { + return mockSend.mock.calls.filter(([command]) => command.kind === 'update').map(([command]) => command.input); +} beforeEach(() => { - jest.clearAllMocks(); + mockSend.mockReset(); + mockRelease.mockReset().mockResolvedValue(true); }); -describe('reconcile-concurrency handler', () => { - test('completes without errors when no users exist', async () => { - mockDdbSend.mockResolvedValueOnce({ Items: [], LastEvaluatedKey: undefined }); - await handler(); - expect(mockDdbSend).toHaveBeenCalledTimes(1); - }); - - test('no update when stored count matches actual count', async () => { - // Scan returns one user with active_count=2 - mockDdbSend - .mockResolvedValueOnce({ - Items: [{ user_id: { S: 'user-1' }, active_count: { N: '2' } }], - LastEvaluatedKey: undefined, - }) - // Query returns count=2 (matching) - .mockResolvedValueOnce({ Count: 2, LastEvaluatedKey: undefined }); - - await handler(); - - // 1 scan + 1 query = 2 calls, no UpdateItemCommand - expect(mockDdbSend).toHaveBeenCalledTimes(2); - const calls = mockDdbSend.mock.calls; - const updateCalls = calls.filter((c: any[]) => c[0]._type === 'UpdateItem'); - expect(updateCalls).toHaveLength(0); - }); - - test('fires UpdateItemCommand with ConditionExpression when count drifts', async () => { - // Scan returns one user with active_count=5 - mockDdbSend - .mockResolvedValueOnce({ - Items: [{ user_id: { S: 'user-1' }, active_count: { N: '5' } }], - LastEvaluatedKey: undefined, - }) - // Query returns actual count=2 (drift) - .mockResolvedValueOnce({ Count: 2, LastEvaluatedKey: undefined }) - // Update succeeds - .mockResolvedValueOnce({}); - - await handler(); - - // 1 scan + 1 query + 1 update = 3 calls - expect(mockDdbSend).toHaveBeenCalledTimes(3); - const updateCall = mockDdbSend.mock.calls[2][0]; - expect(updateCall._type).toBe('UpdateItem'); - // Verify ConditionExpression for TOCTOU protection - expect(updateCall.input.ConditionExpression).toBe('active_count = :stored'); - expect(updateCall.input.ExpressionAttributeValues[':stored']).toEqual({ N: '5' }); - expect(updateCall.input.ExpressionAttributeValues[':count']).toEqual({ N: '2' }); - }); - - test('continues to next user on ConditionalCheckFailedException', async () => { - const condErr = new Error('Conditional check failed'); - condErr.name = 'ConditionalCheckFailedException'; - - mockDdbSend - // Scan returns two users - .mockResolvedValueOnce({ - Items: [ - { user_id: { S: 'user-1' }, active_count: { N: '5' } }, - { user_id: { S: 'user-2' }, active_count: { N: '3' } }, - ], - LastEvaluatedKey: undefined, - }) - // User-1: query returns 2 (drift) - .mockResolvedValueOnce({ Count: 2, LastEvaluatedKey: undefined }) - // User-1: update fails with CCF - .mockRejectedValueOnce(condErr) - // User-2: query returns 1 (drift) - .mockResolvedValueOnce({ Count: 1, LastEvaluatedKey: undefined }) - // User-2: update succeeds - .mockResolvedValueOnce({}); - - await handler(); - - // 1 scan + 2 queries + 2 updates = 5 calls - expect(mockDdbSend).toHaveBeenCalledTimes(5); - }); - - test('continues to next user when query fails', async () => { - mockDdbSend - // Scan returns two users - .mockResolvedValueOnce({ - Items: [ - { user_id: { S: 'user-1' }, active_count: { N: '2' } }, - { user_id: { S: 'user-2' }, active_count: { N: '3' } }, - ], - LastEvaluatedKey: undefined, - }) - // User-1: query throws - .mockRejectedValueOnce(new Error('DynamoDB timeout')) - // User-2: query returns 3 (matches) - .mockResolvedValueOnce({ Count: 3, LastEvaluatedKey: undefined }); - - await handler(); - - // 1 scan + 2 queries (one failed) = 3 calls - expect(mockDdbSend).toHaveBeenCalledTimes(3); - }); +test('empty tables complete without writes', async () => { + seed([], []); + await handler(); + expect(updates()).toEqual([]); + expect(mockRelease).not.toHaveBeenCalled(); +}); - test('handles scan pagination', async () => { - mockDdbSend - // First scan page - .mockResolvedValueOnce({ - Items: [{ user_id: { S: 'user-1' }, active_count: { N: '1' } }], - LastEvaluatedKey: { user_id: { S: 'user-1' } }, - }) - // User-1 query - .mockResolvedValueOnce({ Count: 1, LastEvaluatedKey: undefined }) - // Second scan page - .mockResolvedValueOnce({ - Items: [{ user_id: { S: 'user-2' }, active_count: { N: '2' } }], - LastEvaluatedKey: undefined, - }) - // User-2 query - .mockResolvedValueOnce({ Count: 2, LastEvaluatedKey: undefined }); +test('approval waits count as held seats and a matching counter needs no repair', async () => { + seed([{ user_id: 'user', active_count: 2, reservation_version: 'v1' }], + [held('one'), held('two', 'user', 'AWAITING_APPROVAL')]); + await handler(); + expect(updates()).toEqual([]); + expect(mockRelease).not.toHaveBeenCalled(); +}); - await handler(); +test('repairs drift only while the observed count and reservation revision still match', async () => { + seed([{ user_id: 'user', active_count: 5, reservation_version: 'v1' }], [held('one'), held('two')]); + await handler(); + expect(updates()).toEqual([expect.objectContaining({ + Key: { user_id: 'user' }, + ConditionExpression: 'attribute_exists(user_id) AND active_count = :stored AND reservation_version = :observed', + ExpressionAttributeValues: expect.objectContaining({ ':count': 2, ':stored': 5, ':observed': 'v1' }), + })]); +}); - // 2 scans + 2 queries = 4 calls - expect(mockDdbSend).toHaveBeenCalledTimes(4); +test('missing counters are recreated only if no reservation writer has created them meanwhile', async () => { + seed([], [held('one')]); + await handler(); + expect(updates()[0]).toMatchObject({ + ConditionExpression: 'attribute_not_exists(user_id)', + ExpressionAttributeValues: { ':count': 1 }, }); +}); - test('handles query pagination for countActiveTasks', async () => { - mockDdbSend - // Scan - .mockResolvedValueOnce({ - Items: [{ user_id: { S: 'user-1' }, active_count: { N: '0' } }], - LastEvaluatedKey: undefined, - }) - // First query page: count=3, has more - .mockResolvedValueOnce({ - Count: 3, - LastEvaluatedKey: { user_id: { S: 'user-1' }, task_id: { S: 'T3' } }, - }) - // Second query page: count=2, done - .mockResolvedValueOnce({ Count: 2, LastEvaluatedKey: undefined }) - // Update (drift: stored=0 vs actual=5) - .mockResolvedValueOnce({}); - - await handler(); +test('legacy counter repair checks that a version has not been installed concurrently', async () => { + seed([{ user_id: 'user', active_count: 4 }], [held('one')]); + await handler(); + expect(updates()[0].ConditionExpression).toContain('attribute_not_exists(reservation_version)'); +}); - // 1 scan + 2 queries + 1 update = 4 calls - expect(mockDdbSend).toHaveBeenCalledTimes(4); - const updateCall = mockDdbSend.mock.calls[3][0]; - expect(updateCall._type).toBe('UpdateItem'); - expect(updateCall.input.ExpressionAttributeValues[':count']).toEqual({ N: '5' }); - }); +test('ambiguous legacy active tasks prevent guessing a count', async () => { + seed([{ user_id: 'user', active_count: 5 }], [{ task_id: 'legacy', user_id: 'user', status: 'AWAITING_APPROVAL' }]); + await handler(); + expect(updates()).toEqual([]); +}); - test('skips items without user_id', async () => { - mockDdbSend.mockResolvedValueOnce({ - Items: [{ active_count: { N: '1' } }], // no user_id - LastEvaluatedKey: undefined, - }); +test('queued and unadmitted terminal tasks do not inflate the count', async () => { + seed([{ user_id: 'user', active_count: 3 }], [ + { task_id: 'queued', user_id: 'user', status: 'QUEUED' }, + { task_id: 'failed', user_id: 'user', status: 'FAILED' }, + ]); + await handler(); + expect(updates()[0].ExpressionAttributeValues[':count']).toBe(0); +}); - await handler(); +test('counts terminal held markers before asking shared cleanup to release them', async () => { + seed([{ user_id: 'user', active_count: 0, reservation_version: 'v1' }], [held('done', 'user', 'FAILED'), held('live')]); + await handler(); + expect(updates()[0].ExpressionAttributeValues[':count']).toBe(2); + expect(mockRelease).toHaveBeenCalledWith('done', 'user'); + expect(mockSend.mock.invocationCallOrder.at(-1)!).toBeLessThan(mockRelease.mock.invocationCallOrder[0]); +}); - // Only the scan call, no query or update - expect(mockDdbSend).toHaveBeenCalledTimes(1); - }); +test('a changed revision skips stale repair and still tries terminal cleanup', async () => { + seed([{ user_id: 'user', active_count: 3, reservation_version: 'v1' }], [held('done', 'user', 'FAILED')]); + mockSend.mockRejectedValueOnce(Object.assign(new Error('changed'), { name: 'ConditionalCheckFailedException' })); + await handler(); + expect(updates()).toHaveLength(1); + expect(mockRelease).toHaveBeenCalledWith('done', 'user'); +}); - test('continues to next user when UpdateItemCommand fails with non-CCF error', async () => { - mockDdbSend - // Scan returns two users with drift - .mockResolvedValueOnce({ - Items: [ - { user_id: { S: 'user-1' }, active_count: { N: '5' } }, - { user_id: { S: 'user-2' }, active_count: { N: '4' } }, - ], - LastEvaluatedKey: undefined, - }) - // User-1: query returns 2 (drift) - .mockResolvedValueOnce({ Count: 2, LastEvaluatedKey: undefined }) - // User-1: update fails with non-CCF error - .mockRejectedValueOnce(new Error('InternalServerError')) - // User-2: query returns 1 (drift) - .mockResolvedValueOnce({ Count: 1, LastEvaluatedKey: undefined }) - // User-2: update succeeds - .mockResolvedValueOnce({}); +test('one user repair failure does not stop the next user', async () => { + seed([{ user_id: 'one', active_count: 3 }, { user_id: 'two', active_count: 3 }], []); + mockSend.mockRejectedValueOnce(new Error('unavailable')); + await handler(); + expect(updates().map(update => update.Key.user_id)).toEqual(['one', 'two']); +}); - await handler(); +test('scans every counter page before strongly scanning every task page', async () => { + mockSend.mockResolvedValueOnce({ Items: [{ user_id: 'user', active_count: 2 }], LastEvaluatedKey: { user_id: 'user' } }) + .mockResolvedValueOnce({ Items: [] }) + .mockResolvedValueOnce({ Items: [held('one')], LastEvaluatedKey: { task_id: 'one' } }) + .mockResolvedValueOnce({ Items: [held('two')] }); + await handler(); + expect(mockSend.mock.calls.map(([command]) => [command.input.TableName, command.input.ConsistentRead])) + .toEqual([['Counters', true], ['Counters', true], ['Tasks', true], ['Tasks', true]]); + expect(mockSend.mock.calls[3][0].input.ExclusiveStartKey).toEqual({ task_id: 'one' }); +}); - // 1 scan + 2 queries + 2 updates = 5 calls - expect(mockDdbSend).toHaveBeenCalledTimes(5); - // Verify user-2's update was still attempted and succeeded - const updateCalls = mockDdbSend.mock.calls.filter((c: any[]) => c[0]._type === 'UpdateItem'); - expect(updateCalls).toHaveLength(2); - // User-2's update should have the correct values - const user2Update = updateCalls[1][0]; - expect(user2Update.input.Key).toEqual({ user_id: { S: 'user-2' } }); - expect(user2Update.input.ExpressionAttributeValues[':count']).toEqual({ N: '1' }); - }); +test('an incomplete task scan aborts before any partial count is installed', async () => { + mockSend.mockResolvedValueOnce({ Items: [{ user_id: 'user', active_count: 2 }] }) + .mockResolvedValueOnce({ Items: [held('one')], LastEvaluatedKey: { task_id: 'one' } }) + .mockRejectedValueOnce(new Error('scan unavailable')); + await expect(handler()).rejects.toThrow('scan unavailable'); + expect(updates()).toEqual([]); }); diff --git a/cdk/test/handlers/reconcile-stranded-tasks.test.ts b/cdk/test/handlers/reconcile-stranded-tasks.test.ts index 8c2346c5c..93f2aa0f9 100644 --- a/cdk/test/handlers/reconcile-stranded-tasks.test.ts +++ b/cdk/test/handlers/reconcile-stranded-tasks.test.ts @@ -19,6 +19,11 @@ // --- Mocks --- const mockDdbSend = jest.fn(); +const mockRelease = jest.fn(); +jest.mock('../../src/handlers/shared/task-concurrency', () => ({ + releaseTaskSlot: (...args: unknown[]) => mockRelease(...args), +})); +beforeEach(() => mockRelease.mockReset().mockResolvedValue(true)); jest.mock('@aws-sdk/client-dynamodb', () => ({ DynamoDBClient: jest.fn(() => ({ send: mockDdbSend })), QueryCommand: jest.fn((input: unknown) => ({ _type: 'Query', input })), @@ -89,7 +94,7 @@ describe('reconcile-stranded-tasks', () => { expect(mockDdbSend).toHaveBeenCalledTimes(3); }); - test('task older than 1200s → fails + emits events + decrements concurrency', async () => { + test('task older than 1200s → fails + emits events + releases its reservation', async () => { const ancient = new Date(Date.now() - 25 * 60 * 1000).toISOString(); // 25 min ago primeResponses([ // Query SUBMITTED returns one stranded candidate. @@ -103,7 +108,6 @@ describe('reconcile-stranded-tasks', () => { {}, // conditional UpdateItem → FAILED {}, // PutItem task_stranded event {}, // PutItem task_failed event - {}, // UpdateItem decrement concurrency { Items: [] }, // Query HYDRATING { Items: [] }, // Query AWAITING_APPROVAL ]); @@ -132,10 +136,12 @@ describe('reconcile-stranded-tasks', () => { }); expect(eventTypes).toEqual(expect.arrayContaining(['task_stranded', 'task_failed'])); - // Concurrency decrement. - const decrementCall = (mockDdbSend.mock.calls as [{ _type: string; input: Record }][]) - .find(([c]) => c._type === 'UpdateItem' && String(c.input.UpdateExpression).includes('active_count')); - expect(decrementCall).toBeDefined(); + // The task-owned reservation is released through the marker-guarded path, + // never by decrementing the shared counter directly. + expect(mockRelease).toHaveBeenCalledTimes(1); + const directDecrement = (mockDdbSend.mock.calls as [{ _type: string; input: Record }][]) + .find(([c]) => String(c.input.UpdateExpression ?? '').includes('active_count')); + expect(directDecrement).toBeUndefined(); }); test('#441: task with old created_at but FRESH status_created_at is NOT failed (freshly picked up from the queue)', async () => { @@ -162,8 +168,9 @@ describe('reconcile-stranded-tasks', () => { await handler(); // Only the 3 status queries — the fresh task is filtered in-code, so - // NO transition / event / decrement writes fire. + // NO transition / event / release writes fire. expect(mockDdbSend).toHaveBeenCalledTimes(3); + expect(mockRelease).not.toHaveBeenCalled(); }); test('#441: task with old created_at AND old status_created_at is still failed (genuinely stranded)', async () => { @@ -180,7 +187,6 @@ describe('reconcile-stranded-tasks', () => { {}, // conditional UpdateItem → FAILED {}, // PutItem task_stranded event {}, // PutItem task_failed event - {}, // UpdateItem decrement concurrency { Items: [] }, // HYDRATING { Items: [] }, // AWAITING_APPROVAL ]); @@ -215,7 +221,6 @@ describe('reconcile-stranded-tasks', () => { {}, // conditional UpdateItem → FAILED {}, // PutItem task_stranded event {}, // PutItem task_failed event - {}, // UpdateItem decrement concurrency { Items: [] }, // HYDRATING { Items: [] }, // AWAITING_APPROVAL ]); @@ -274,7 +279,6 @@ describe('reconcile-stranded-tasks', () => { {}, // PutItem task_stranded event {}, // PutItem task_failed event {}, // PutItem approval_stranded milestone (Chunk 10 new) - {}, // UpdateItem decrement concurrency ]); await handler(); @@ -427,7 +431,7 @@ describe('reconcile-stranded-tasks', () => { }); test('test_logs_WARN_with_RECONCILER_PARTIAL_FAILURE_when_some_tasks_fail', async () => { - // One success (4 writes), one failure (throws on UpdateItem). + // One success (3 writes), one failure (throws on UpdateItem). const ancient = new Date(Date.now() - 25 * 60 * 1000).toISOString(); const ddbErr = Object.assign(new Error('DDB throttled'), { name: 'ProvisionedThroughputExceededException' }); primeResponses([ @@ -441,7 +445,6 @@ describe('reconcile-stranded-tasks', () => { {}, // UpdateItem t-ok (transition) → success {}, // PutItem task_stranded event {}, // PutItem task_failed event - {}, // UpdateItem decrement concurrency ddbErr, // UpdateItem t-fail (transition) → throws { Items: [] }, // HYDRATING query { Items: [] }, // AWAITING_APPROVAL query @@ -467,8 +470,8 @@ describe('reconcile-stranded-tasks', () => { mockTaskRow({ task_id: 't-2', user_id: 'u-b', created_at: ancient }), ], }, - {}, {}, {}, {}, // t-1: transition + 2 events + decrement - {}, {}, {}, {}, // t-2: transition + 2 events + decrement + {}, {}, {}, // t-1: transition + 2 events + {}, {}, {}, // t-2: transition + 2 events { Items: [] }, // HYDRATING { Items: [] }, // AWAITING_APPROVAL ]); diff --git a/cdk/test/handlers/shared/task-concurrency-local.test.ts b/cdk/test/handlers/shared/task-concurrency-local.test.ts new file mode 100644 index 000000000..e669fca56 --- /dev/null +++ b/cdk/test/handlers/shared/task-concurrency-local.test.ts @@ -0,0 +1,320 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * Opt-in real DynamoDB Local tests: + * ABCA_DDB_LOCAL_ENDPOINT=http://127.0.0.1: mise run testf -- task-concurrency-local + * The endpoint is restricted to loopback and every client uses dummy credentials. + */ +import { randomUUID } from 'node:crypto'; +import { CreateTableCommand, DeleteTableCommand, DynamoDBClient } from '@aws-sdk/client-dynamodb'; +import { DeleteCommand, DynamoDBDocumentClient, GetCommand, PutCommand, ScanCommand, UpdateCommand } from '@aws-sdk/lib-dynamodb'; + +const endpoint = process.env.ABCA_DDB_LOCAL_ENDPOINT; +if (endpoint && (new URL(endpoint).hostname !== '127.0.0.1' || new URL(endpoint).protocol !== 'http:')) { + throw new Error('Capacity integration tests require an http://127.0.0.1 DynamoDB Local endpoint'); +} +const mockBeforeSend = jest.fn(); +const mockAfterSend = jest.fn(); +const mockClients: DynamoDBDocumentClient[] = []; +jest.mock('../../../src/handlers/shared/ua', () => { + const actual = jest.requireActual('../../../src/handlers/shared/ua'); + return { + ...actual, + makeDocClient: () => { + const client = actual.makeDocClient({ + endpoint: process.env.ABCA_DDB_LOCAL_ENDPOINT ?? 'http://127.0.0.1:1', + region: 'us-east-1', + credentials: { accessKeyId: 'local', secretAccessKey: 'local' }, + }); + const send = client.send.bind(client); + client.send = async (command: unknown) => { + await mockBeforeSend(command); + const result = await send(command); + await mockAfterSend(command, result); + return result; + }; + mockClients.push(client); + return client; + }, + }; +}); + +const suffix = randomUUID(); +const tasks = `capacity-tasks-${suffix}`; +const counters = `capacity-counters-${suffix}`; +const events = `capacity-events-${suffix}`; +Object.assign(process.env, { + TASK_TABLE_NAME: tasks, + USER_CONCURRENCY_TABLE_NAME: counters, + TASK_EVENTS_TABLE_NAME: events, + MEMORY_ID: '', +}); + +import { handler as reconcile } from '../../../src/handlers/reconcile-concurrency'; +import { failTask, finalizeTask } from '../../../src/handlers/shared/orchestrator'; +import { acquireTaskSlot, releaseTaskSlot } from '../../../src/handlers/shared/task-concurrency'; + +const raw = new DynamoDBClient({ + endpoint: endpoint ?? 'http://127.0.0.1:1', + region: 'us-east-1', + credentials: { accessKeyId: 'local', secretAccessKey: 'local' }, +}); +const admin = DynamoDBDocumentClient.from(raw); +const local = endpoint ? describe : describe.skip; +jest.setTimeout(30_000); + +local('task capacity against DynamoDB Local', () => { + beforeAll(async () => { + for (const [name, key] of [[tasks, 'task_id'], [counters, 'user_id'], [events, 'task_id']]) { + await raw.send(new CreateTableCommand({ + TableName: name, + BillingMode: 'PAY_PER_REQUEST', + AttributeDefinitions: [ + { AttributeName: key, AttributeType: 'S' }, + ...(name === events ? [{ AttributeName: 'event_id', AttributeType: 'S' as const }] : []), + ], + KeySchema: [ + { AttributeName: key, KeyType: 'HASH' }, + ...(name === events ? [{ AttributeName: 'event_id', KeyType: 'RANGE' as const }] : []), + ], + })); + } + }); + beforeEach(async () => { + mockBeforeSend.mockReset(); + mockAfterSend.mockReset(); + for (const [name, key] of [[tasks, 'task_id'], [counters, 'user_id'], [events, 'task_id']]) { + const page = await admin.send(new ScanCommand({ TableName: name })); + for (const item of page.Items ?? []) { + await admin.send(new DeleteCommand({ + TableName: name, + Key: { [key]: item[key], ...(name === events && { event_id: item.event_id }) }, + })); + } + } + }); + afterAll(async () => { + for (const name of [tasks, counters, events]) await raw.send(new DeleteTableCommand({ TableName: name })); + for (const client of mockClients) client.destroy(); + raw.destroy(); + }); + + async function seed(id: string, initialStatus = 'SUBMITTED', user = 'user') { + await admin.send(new PutCommand({ + TableName: tasks, + Item: { + task_id: id, user_id: user, status: initialStatus, memory_written: true, + }, + })); + } + async function status(id: string, value: string) { + await admin.send(new UpdateCommand({ + TableName: tasks, + Key: { task_id: id }, + UpdateExpression: 'SET #status = :status', + ExpressionAttributeNames: { '#status': 'status' }, + ExpressionAttributeValues: { ':status': value }, + })); + } + async function task(id: string) { + return (await admin.send(new GetCommand({ + TableName: tasks, Key: { task_id: id }, ConsistentRead: true, + }))).Item!; + } + async function count() { + return (await admin.send(new GetCommand({ + TableName: counters, Key: { user_id: 'user' }, ConsistentRead: true, + }))).Item?.active_count ?? 0; + } + async function twoSeats() { + await seed('one'); + await seed('two'); + await acquireTaskSlot('one', 'user', 3); + await acquireTaskSlot('two', 'user', 3); + } + + test('crash replay of real finalization preserves the other task reservation', async () => { + await twoSeats(); + await status('one', 'COMPLETED'); + await finalizeTask('one', { attempts: 10 }, 'user'); + await finalizeTask('one', { attempts: 10 }, 'user'); + expect(await count()).toBe(1); + expect((await task('one')).concurrency_slot.state).toBe('released'); + expect((await task('two')).concurrency_slot.state).toBe('held'); + }); + + test('simultaneous admission of one task creates exactly one reservation', async () => { + await seed('one'); + const results = await Promise.allSettled(Array.from({ length: 5 }, () => acquireTaskSlot('one', 'user', 3))); + expect(results.some(result => result.status === 'fulfilled' && result.value)).toBe(true); + expect(await acquireTaskSlot('one', 'user', 3)).toBe(true); + expect(await count()).toBe(1); + }); + + test('different tasks cannot exceed the admission cap', async () => { + const ids = ['a', 'b', 'c', 'd']; + for (const id of ids) await seed(id); + await Promise.allSettled(ids.map(id => acquireTaskSlot(id, 'user', 2))); + // Retry any transaction conflicts serially, as durable execution does. + for (const id of ids) await acquireTaskSlot(id, 'user', 2); + expect(await count()).toBe(2); + // Four fixed fixture reads; no input-dependent fan-out. + // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism + const rows = await Promise.all([task('a'), task('b'), task('c'), task('d')]); + expect(rows.filter(row => row.concurrency_slot?.state === 'held')).toHaveLength(2); + }); + + test.each(['acquire', 'release'])('a lost committed %s response is recovered from the marker', async (operation) => { + await seed('one'); + if (operation === 'release') { + await acquireTaskSlot('one', 'user', 3); + await status('one', 'FAILED'); + } + mockAfterSend.mockImplementationOnce((command) => { + if (command.constructor.name === 'GetCommand') { + mockAfterSend.mockImplementationOnce(() => { throw new Error('transaction response lost'); }); + } + }); + if (operation === 'acquire') await acquireTaskSlot('one', 'user', 3); + else await releaseTaskSlot('one', 'user'); + expect(await count()).toBe(operation === 'acquire' ? 1 : 0); + expect((await task('one')).concurrency_slot.state).toBe(operation === 'acquire' ? 'held' : 'released'); + }); + + test('competing finalizers and direct cleanup only release once', async () => { + await twoSeats(); + await status('one', 'CANCELLED'); + await Promise.allSettled([ + finalizeTask('one', { attempts: 0 }, 'user'), + finalizeTask('one', { attempts: 0 }, 'user'), + releaseTaskSlot('one', 'user'), + ]); + await releaseTaskSlot('one', 'user'); + expect(await count()).toBe(1); + }); + + test('start failure and replay release a held slot once', async () => { + await twoSeats(); + await status('one', 'HYDRATING'); + await failTask('one', 'HYDRATING', 'start failed', 'user', true); + await failTask('one', 'HYDRATING', 'start failed', 'user', true); + expect(await count()).toBe(1); + expect((await task('one')).status).toBe('FAILED'); + }); + + test('approval waits retain capacity through reconciliation', async () => { + await twoSeats(); + await status('one', 'AWAITING_APPROVAL'); + expect(await releaseTaskSlot('one', 'user')).toBe(false); + await reconcile(); + expect(await count()).toBe(2); + }); + + test('queued and unadmitted terminal tasks cannot release another reservation', async () => { + await seed('running'); + await acquireTaskSlot('running', 'user', 3); + await seed('queued', 'QUEUED'); + await seed('cancelled', 'CANCELLED'); + expect(await acquireTaskSlot('queued', 'user', 3)).toBe(false); + await releaseTaskSlot('queued', 'user'); + await releaseTaskSlot('cancelled', 'user'); + expect(await count()).toBe(1); + }); + + test('owner mismatch changes neither the reservation nor counter', async () => { + await seed('one'); + await expect(acquireTaskSlot('one', 'someone-else', 3)).rejects.toThrow('owner'); + expect(await count()).toBe(0); + expect((await task('one')).concurrency_slot).toBeUndefined(); + }); + + test('cancellation between the read and admission transaction wins', async () => { + await seed('one'); + mockBeforeSend.mockImplementation(async (command) => { + if (command.constructor.name === 'TransactWriteCommand') { + mockBeforeSend.mockReset(); + await status('one', 'CANCELLED'); + } + }); + expect(await acquireTaskSlot('one', 'user', 3)).toBe(false); + expect(await count()).toBe(0); + }); + + test('an empty counter release preserves an admission that races into the empty-counter branch', async () => { + await seed('one'); + await acquireTaskSlot('one', 'user', 3); + await status('one', 'FAILED'); + await admin.send(new DeleteCommand({ TableName: counters, Key: { user_id: 'user' } })); + await seed('two'); + mockBeforeSend.mockImplementation(async (command) => { + if (command.constructor.name === 'TransactWriteCommand' + && command.input.TransactItems[1].Update.UpdateExpression.includes('if_not_exists')) { + mockBeforeSend.mockReset(); + await acquireTaskSlot('two', 'user', 3); + } + }); + await releaseTaskSlot('one', 'user'); + expect(await count()).toBe(1); + expect((await task('one')).concurrency_slot.state).toBe('released'); + expect((await task('two')).concurrency_slot.state).toBe('held'); + }); + + test('periodic cleanup recovers a crash between terminal status and release', async () => { + await twoSeats(); + await status('one', 'TIMED_OUT'); + await reconcile(); + await finalizeTask('one', { attempts: 10 }, 'user'); + expect(await count()).toBe(1); + }); + + test('an ambiguous legacy active task prevents guessing a replacement count', async () => { + await twoSeats(); + await seed('legacy', 'AWAITING_APPROVAL'); + await reconcile(); + expect(await count()).toBe(2); + expect((await task('legacy')).concurrency_slot).toBeUndefined(); + }); + + test('a revision change blocks stale repair even when the counter returns to its original number', async () => { + await seed('one'); + await acquireTaskSlot('one', 'user', 3); + await admin.send(new UpdateCommand({ + TableName: counters, + Key: { user_id: 'user' }, + UpdateExpression: 'SET active_count = :zero', + ExpressionAttributeValues: { ':zero': 0 }, + })); + mockAfterSend.mockImplementation(async (command) => { + if (command.constructor.name === 'ScanCommand' && command.input.TableName === tasks) { + mockAfterSend.mockReset(); + await seed('two'); + await acquireTaskSlot('two', 'user', 3); + await status('one', 'COMPLETED'); + await releaseTaskSlot('one', 'user'); + } + }); + await reconcile(); + // Admission then release brought the count back to zero, but changed its + // revision. The old scan must not write its answer into this new state. + expect(await count()).toBe(0); + await reconcile(); + expect(await count()).toBe(1); + }); +}); diff --git a/cdk/test/handlers/shared/task-concurrency.test.ts b/cdk/test/handlers/shared/task-concurrency.test.ts new file mode 100644 index 000000000..95b5e9f5a --- /dev/null +++ b/cdk/test/handlers/shared/task-concurrency.test.ts @@ -0,0 +1,205 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +const mockSend = jest.fn(); +jest.mock('node:timers/promises', () => ({ + setTimeout: jest.fn().mockResolvedValue(undefined), +})); +jest.mock('@aws-sdk/lib-dynamodb', () => ({ + GetCommand: jest.fn((input: unknown) => ({ kind: 'get', input })), + TransactWriteCommand: jest.fn((input: unknown) => ({ kind: 'transaction', input })), +})); +jest.mock('../../../src/handlers/shared/ua', () => ({ + makeDocClient: () => ({ send: mockSend }), +})); +process.env.TASK_TABLE_NAME = 'Tasks'; +process.env.USER_CONCURRENCY_TABLE_NAME = 'Counters'; + +import { setTimeout as delay } from 'node:timers/promises'; +import { acquireTaskSlot, releaseTaskSlot } from '../../../src/handlers/shared/task-concurrency'; + +const base = { task_id: 'task', user_id: 'user', status: 'SUBMITTED' }; +const held = { state: 'held', acquired_at: '2026-09-13T00:00:00Z' }; +function cancelled(index: number) { + return Object.assign(new Error('transaction cancelled'), { + name: 'TransactionCanceledException', + CancellationReasons: [0, 1].map(i => ({ Code: i === index ? 'ConditionalCheckFailed' : 'None' })), + }); +} +beforeEach(() => { + mockSend.mockReset(); + jest.mocked(delay).mockClear(); +}); + +function conflict(codes = ['None', 'TransactionConflict']) { + return Object.assign(new Error('transaction conflict'), { + name: 'TransactionCanceledException', + CancellationReasons: codes.map(Code => ({ Code })), + }); +} + +test.each(['acquire', 'release'])('%s retries counter contention with the identical guarded transaction', async operation => { + mockSend.mockResolvedValueOnce({ + Item: operation === 'acquire' ? base : { ...base, status: 'COMPLETED', concurrency_slot: held }, + }).mockRejectedValueOnce(conflict()).mockRejectedValueOnce(conflict()).mockResolvedValueOnce({}); + const result = operation === 'acquire' + ? await acquireTaskSlot('task', 'user', 10) + : await releaseTaskSlot('task', 'user'); + expect(result).toBe(true); + const transactions = mockSend.mock.calls.filter(([command]) => command.kind === 'transaction'); + expect(transactions).toHaveLength(3); + expect(transactions[1][0]).toBe(transactions[0][0]); + expect(transactions[2][0]).toBe(transactions[0][0]); + expect(delay).toHaveBeenCalledTimes(2); +}); + +test('persistent contention stays bounded and propagates the original error', async () => { + const error = conflict(); + mockSend.mockImplementation(async command => { + if (command.kind === 'get') return { Item: { ...base, status: 'COMPLETED', concurrency_slot: held } }; + throw error; + }); + await expect(releaseTaskSlot('task', 'user')).rejects.toBe(error); + expect(mockSend.mock.calls.filter(([command]) => command.kind === 'transaction')).toHaveLength(5); + expect(delay).toHaveBeenCalledTimes(4); + for (const [index, call] of jest.mocked(delay).mock.calls.entries()) { + expect(call[0]).toBeGreaterThanOrEqual(0); + expect(call[0]).toBeLessThan(50 * 2 ** index); + } +}); + +test('a mixed conflict and capacity condition failure follows normal admission without retrying', async () => { + mockSend.mockResolvedValueOnce({ Item: base }) + .mockRejectedValueOnce(conflict(['TransactionConflict', 'ConditionalCheckFailed'])) + .mockResolvedValueOnce({ Item: base }); + expect(await acquireTaskSlot('task', 'user', 10)).toBe(false); + expect(delay).not.toHaveBeenCalled(); +}); + +test('admission atomically ties a counter increment to an owned SUBMITTED task', async () => { + mockSend.mockResolvedValueOnce({ Item: base }).mockResolvedValueOnce({}); + expect(await acquireTaskSlot('task', 'user', 3)).toBe(true); + const transaction = mockSend.mock.calls[1][0].input; + expect(transaction.TransactItems).toHaveLength(2); + expect(transaction.TransactItems[0].Update).toMatchObject({ + TableName: 'Tasks', + Key: { task_id: 'task' }, + ConditionExpression: 'user_id = :user AND #status = :submitted AND attribute_not_exists(concurrency_slot)', + ExpressionAttributeValues: { ':slot': { state: 'held' }, ':user': 'user', ':submitted': 'SUBMITTED' }, + }); + expect(transaction.TransactItems[1].Update).toMatchObject({ + TableName: 'Counters', + Key: { user_id: 'user' }, + ConditionExpression: 'attribute_not_exists(active_count) OR active_count < :max', + ExpressionAttributeValues: { ':max': 3, ':version': transaction.ClientRequestToken }, + }); +}); + +test.each(['SUBMITTED', 'HYDRATING', 'RUNNING', 'AWAITING_APPROVAL', 'FINALIZING'])( + 'replaying admission in %s reuses the held reservation', async (status) => { + mockSend.mockResolvedValueOnce({ Item: { ...base, status, concurrency_slot: held } }); + expect(await acquireTaskSlot('task', 'user', 3)).toBe(true); + expect(mockSend).toHaveBeenCalledTimes(1); + }, +); + +test('a full counter declines admission without leaving a marker', async () => { + mockSend.mockResolvedValueOnce({ Item: base }).mockRejectedValueOnce(cancelled(1)) + .mockResolvedValueOnce({ Item: base }); + expect(await acquireTaskSlot('task', 'user', 3)).toBe(false); +}); + +test('a transaction outage is not misreported as a full counter', async () => { + mockSend.mockResolvedValueOnce({ Item: base }).mockRejectedValueOnce(new Error('throttled')) + .mockResolvedValueOnce({ Item: base }); + await expect(acquireTaskSlot('task', 'user', 3)).rejects.toThrow('throttled'); +}); + +test('a lost admission response recovers the committed held marker', async () => { + mockSend.mockResolvedValueOnce({ Item: base }).mockRejectedValueOnce(new Error('response lost')) + .mockResolvedValueOnce({ Item: { ...base, concurrency_slot: held } }); + expect(await acquireTaskSlot('task', 'user', 3)).toBe(true); +}); + +test('a cancelled task cannot acquire capacity', async () => { + mockSend.mockResolvedValueOnce({ Item: { ...base, status: 'CANCELLED' } }); + expect(await acquireTaskSlot('task', 'user', 3)).toBe(false); +}); + +test('a released task cannot reacquire even if its status is changed', async () => { + mockSend.mockResolvedValueOnce({ Item: { ...base, concurrency_slot: { ...held, state: 'released' } } }); + expect(await acquireTaskSlot('task', 'user', 3)).toBe(false); +}); + +test('owner mismatch never writes', async () => { + mockSend.mockResolvedValueOnce({ Item: base }); + await expect(acquireTaskSlot('task', 'other', 3)).rejects.toThrow('owner'); + expect(mockSend).toHaveBeenCalledTimes(1); +}); + +test.each(['COMPLETED', 'FAILED', 'CANCELLED', 'TIMED_OUT'])( + '%s releases the marker and count in one guarded transaction', async (status) => { + mockSend.mockResolvedValueOnce({ Item: { ...base, status, concurrency_slot: held } }) + .mockResolvedValueOnce({}); + expect(await releaseTaskSlot('task', 'user')).toBe(true); + const transaction = mockSend.mock.calls[1][0].input; + expect(transaction.TransactItems[0].Update).toMatchObject({ + ConditionExpression: 'user_id = :user AND concurrency_slot.#state = :held AND #status IN (:completed, :failed, :cancelled, :timedOut)', + ExpressionAttributeValues: { ':released': 'released', ':held': 'held' }, + }); + expect(transaction.TransactItems[1].Update).toMatchObject({ + UpdateExpression: 'SET active_count = active_count - :one, updated_at = :now, reservation_version = :version', + ConditionExpression: 'active_count > :zero', + }); + }, +); + +test('an active task retains its slot', async () => { + mockSend.mockResolvedValueOnce({ Item: { ...base, status: 'AWAITING_APPROVAL', concurrency_slot: held } }); + expect(await releaseTaskSlot('task', 'user')).toBe(false); + expect(mockSend).toHaveBeenCalledTimes(1); +}); + +test('unadmitted or legacy terminal tasks do not return another task seat', async () => { + mockSend.mockResolvedValueOnce({ Item: { ...base, status: 'FAILED' } }); + expect(await releaseTaskSlot('task', 'user')).toBe(false); +}); + +test('release recovers a competing commit or lost successful response', async () => { + mockSend.mockResolvedValueOnce({ Item: { ...base, status: 'FAILED', concurrency_slot: held } }) + .mockRejectedValueOnce(new Error('response lost')) + .mockResolvedValueOnce({ Item: { ...base, status: 'FAILED', concurrency_slot: { ...held, state: 'released' } } }); + expect(await releaseTaskSlot('task', 'user')).toBe(false); +}); + +test('an empty counter closes the marker without subtracting from later admissions', async () => { + const row = { Item: { ...base, status: 'FAILED', concurrency_slot: held } }; + mockSend.mockResolvedValueOnce(row).mockRejectedValueOnce(cancelled(1)) + .mockResolvedValueOnce(row).mockResolvedValueOnce({}); + expect(await releaseTaskSlot('task', 'user')).toBe(true); + const update = mockSend.mock.calls[3][0].input.TransactItems[1].Update; + expect(update.UpdateExpression).toBe('SET active_count = if_not_exists(active_count, :zero), updated_at = :now, reservation_version = :version'); + expect(update.ExpressionAttributeValues).not.toHaveProperty(':one'); +}); + +test('a release outage propagates with the held marker intact', async () => { + const row = { Item: { ...base, status: 'FAILED', concurrency_slot: held } }; + mockSend.mockResolvedValueOnce(row).mockRejectedValueOnce(new Error('unavailable')).mockResolvedValueOnce(row); + await expect(releaseTaskSlot('task', 'user')).rejects.toThrow('unavailable'); +}); diff --git a/docs/design/ORCHESTRATOR.md b/docs/design/ORCHESTRATOR.md index 2f1bec0de..c7d4ea387 100644 --- a/docs/design/ORCHESTRATOR.md +++ b/docs/design/ORCHESTRATOR.md @@ -343,10 +343,18 @@ Each task runs in its own isolated compute session with no shared mutable state ### Counter management -- **UserConcurrency** - DynamoDB item per user with `active_count`. Incremented atomically (`active_count < max`) at admission, decremented at finalization. +- **UserConcurrency** - DynamoDB item per user with `active_count` and a `reservation_version` that changes on every reservation mutation. +- **Per-task reservation marker** - each admitted task carries `concurrency_slot` (`held` → `released`, with timestamps). The seat is taken and returned only in a DynamoDB transaction that changes the marker and the counter together (`shared/task-concurrency.ts`): + - **Acquire** requires the task to be `SUBMITTED` with no marker and the counter below the cap. A lost successful response is recovered by re-reading the marker, and a task can never acquire twice. + - **Release** requires the marker to be `held` and the task terminal. Every caller (finalization, `failTask`, the stranded-task reconciler, the concurrency reconciler) can therefore attempt it, and exactly one transaction returns the seat. An active task, including one in `AWAITING_APPROVAL`, keeps its seat. + - A task that holds a marker can never be moved back to `QUEUED`. - **SystemConcurrency** - Single DynamoDB item, same pattern. -Concurrency is always released in `finalizeTask` (step 6), never inside the poll loop. ECS poll failure paths call `failTask` with `releaseConcurrency: false` to transition the task to `FAILED` without decrementing — `finalizeTask` handles the single decrement after re-reading the task state. The heartbeat-detected crash path also guards against double-decrement by only releasing the counter after a successful state transition. If the transition fails (task already terminal), it re-reads and acts accordingly. +Finalization releases in a `finally` block after writing the outcome, so a crash, a failed event write or a durable replay still releases exactly once. A finalization that cannot reach a terminal state throws and is retried, and the task keeps its seat. An approval wait that outlives the poll window finalizes to `FAILED` (a valid transition from `AWAITING_APPROVAL`). Previously it attempted the invalid `TIMED_OUT` and freed the seat of a task that was still active. + +**Reconciliation** reads the counters first, then strongly reads every reservation, and repairs a counter only with a condition on the `reservation_version` it observed, so concurrent admissions and releases are never overwritten. It also releases terminal reservations left by interrupted cleanup. A user with an active task that has no marker (admitted before this scheme, or not yet admitted) is skipped until it settles. The reconciler never guesses a count. + +**Upgrading** a stack: tasks admitted by the previous code have no marker, so no release path returns a seat on their behalf, and the reconciler skips their user while they are active. Drain in-flight tasks before deploying, or expect those users' counters to be corrected only after their old tasks finish. ## Implementation diff --git a/docs/src/content/docs/architecture/Orchestrator.md b/docs/src/content/docs/architecture/Orchestrator.md index a2d7c018b..530d7c6ca 100644 --- a/docs/src/content/docs/architecture/Orchestrator.md +++ b/docs/src/content/docs/architecture/Orchestrator.md @@ -345,10 +345,18 @@ Each task runs in its own isolated compute session with no shared mutable state ### Counter management -- **UserConcurrency** - DynamoDB item per user with `active_count`. Incremented atomically (`active_count < max`) at admission, decremented at finalization. +- **UserConcurrency** - DynamoDB item per user with `active_count` and a `reservation_version` that changes on every reservation mutation. +- **Per-task reservation marker** - each admitted task carries `concurrency_slot` (`held` → `released`, with timestamps). The seat is taken and returned only in a DynamoDB transaction that changes the marker and the counter together (`shared/task-concurrency.ts`): + - **Acquire** requires the task to be `SUBMITTED` with no marker and the counter below the cap. A lost successful response is recovered by re-reading the marker, and a task can never acquire twice. + - **Release** requires the marker to be `held` and the task terminal. Every caller (finalization, `failTask`, the stranded-task reconciler, the concurrency reconciler) can therefore attempt it, and exactly one transaction returns the seat. An active task, including one in `AWAITING_APPROVAL`, keeps its seat. + - A task that holds a marker can never be moved back to `QUEUED`. - **SystemConcurrency** - Single DynamoDB item, same pattern. -Concurrency is always released in `finalizeTask` (step 6), never inside the poll loop. ECS poll failure paths call `failTask` with `releaseConcurrency: false` to transition the task to `FAILED` without decrementing — `finalizeTask` handles the single decrement after re-reading the task state. The heartbeat-detected crash path also guards against double-decrement by only releasing the counter after a successful state transition. If the transition fails (task already terminal), it re-reads and acts accordingly. +Finalization releases in a `finally` block after writing the outcome, so a crash, a failed event write or a durable replay still releases exactly once. A finalization that cannot reach a terminal state throws and is retried, and the task keeps its seat. An approval wait that outlives the poll window finalizes to `FAILED` (a valid transition from `AWAITING_APPROVAL`). Previously it attempted the invalid `TIMED_OUT` and freed the seat of a task that was still active. + +**Reconciliation** reads the counters first, then strongly reads every reservation, and repairs a counter only with a condition on the `reservation_version` it observed, so concurrent admissions and releases are never overwritten. It also releases terminal reservations left by interrupted cleanup. A user with an active task that has no marker (admitted before this scheme, or not yet admitted) is skipped until it settles. The reconciler never guesses a count. + +**Upgrading** a stack: tasks admitted by the previous code have no marker, so no release path returns a seat on their behalf, and the reconciler skips their user while they are active. Drain in-flight tasks before deploying, or expect those users' counters to be corrected only after their old tasks finish. ## Implementation