Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions cdk/src/constructs/concurrency-reconciler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions cdk/src/constructs/stranded-task-reconciler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -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);
Expand Down
3 changes: 2 additions & 1 deletion cdk/src/constructs/user-concurrency-table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
/**
Expand Down
93 changes: 10 additions & 83 deletions cdk/src/handlers/confirm-uploads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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({
Expand All @@ -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,
Expand All @@ -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;
}

Expand Down Expand Up @@ -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,
Expand All @@ -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);
}
Expand Down Expand Up @@ -732,8 +722,8 @@ async function buildScreeningConfig(): Promise<ScreeningConfig | undefined> {

/**
* 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<boolean> {
try {
Expand All @@ -745,7 +735,7 @@ async function preCheckConcurrency(userId: string): Promise<boolean> {
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', {
Expand All @@ -765,66 +755,3 @@ async function preCheckConcurrency(userId: string): Promise<boolean> {
throw err;
}
}

async function checkConcurrency(userId: string): Promise<boolean> {
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<void> {
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.',
);
}
}
}
9 changes: 7 additions & 2 deletions cdk/src/handlers/orchestrate-task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -95,7 +96,7 @@ const durableHandler: DurableExecutionHandler<OrchestrateTaskEvent, void> = 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;
}
Expand Down Expand Up @@ -131,13 +132,16 @@ const durableHandler: DurableExecutionHandler<OrchestrateTaskEvent, void> = 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;
}
Expand Down Expand Up @@ -166,6 +170,7 @@ const durableHandler: DurableExecutionHandler<OrchestrateTaskEvent, void> = asyn
});

if (!preflightPassed) {
await context.step('release-before-work', () => releaseTaskSlot(taskId, task.user_id));
return;
}

Expand Down
4 changes: 3 additions & 1 deletion cdk/src/handlers/reconcile-admission-queue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,9 @@ async function requeueAfterInvokeFailure(taskId: string): Promise<void> {
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' },
Expand Down
Loading
Loading