diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 9df6d2f5..13f21a81 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1462,7 +1462,7 @@ export interface components { workspace_name: string; agent_kind: string; /** @enum {string} */ - state: "queued" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored"; + state: "queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored"; provider: string; backend_kind: string; capabilities: string[]; @@ -1489,7 +1489,7 @@ export interface components { workspace_name: string; agent_kind: string; /** @enum {string} */ - state: "queued" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored"; + state: "queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored"; provider: string; backend_kind: string; capabilities: string[]; @@ -3862,7 +3862,7 @@ export interface operations { agentKind: string; concurrencyLimit: number; runningCount: number; - lastRunState: ("queued" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored") | null; + lastRunState: ("queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored") | null; createdAt: string; updatedAt: string; }[]; @@ -3959,7 +3959,7 @@ export interface operations { runningCount: number; currentRuns: number; maxConcurrency: number; - lastRunState: ("queued" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored") | null; + lastRunState: ("queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored") | null; triggers: ({ /** Format: uuid */ id: string; @@ -4127,7 +4127,7 @@ export interface operations { runningCount: number; currentRuns: number; maxConcurrency: number; - lastRunState: ("queued" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored") | null; + lastRunState: ("queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored") | null; triggers: ({ /** Format: uuid */ id: string; @@ -4328,7 +4328,7 @@ export interface operations { 401: components["responses"]["Error401"]; 403: components["responses"]["Error403"]; 404: components["responses"]["Error404"]; - /** @description queue_full — this job already has one queued run. Retry after it starts. Duplicate idempotency keys return the original run. */ + /** @description queue_full — all execution slots are reserved or occupied and one waiting run already exists. Duplicate idempotency keys return the original run. */ 409: components["responses"]["Error409"]; 415: components["responses"]["Error415"]; 429: components["responses"]["Error429"]; @@ -4467,7 +4467,7 @@ export interface operations { runningCount: number; currentRuns: number; maxConcurrency: number; - lastRunState: ("queued" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored") | null; + lastRunState: ("queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored") | null; triggers: ({ /** Format: uuid */ id: string; @@ -4736,7 +4736,7 @@ export interface operations { runningCount: number; currentRuns: number; maxConcurrency: number; - lastRunState: ("queued" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored") | null; + lastRunState: ("queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped" | "done" | "ignored") | null; triggers: ({ /** Format: uuid */ id: string; @@ -4899,7 +4899,7 @@ export interface operations { parameters: { query?: { jobId?: string; - state?: "queued" | "starting" | "running" | "done" | "blocked" | "failed" | "ignored" | "succeeded" | "stopping" | "stopped"; + state?: "queued" | "reserved" | "starting" | "running" | "done" | "blocked" | "failed" | "ignored" | "succeeded" | "stopping" | "stopped"; contextQuery?: string; sort?: "job" | "run" | "status" | "created" | "agent"; direction?: "asc" | "desc"; @@ -5072,7 +5072,7 @@ export interface operations { id: string; job_id: string; /** @enum {string} */ - state: "queued" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped"; + state: "queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped"; run_name: string; job_name: string; destination_url: string | null; diff --git a/packages/api/migrations/0015_reserved_execution_slots.sql b/packages/api/migrations/0015_reserved_execution_slots.sql new file mode 100644 index 00000000..e0240435 --- /dev/null +++ b/packages/api/migrations/0015_reserved_execution_slots.sql @@ -0,0 +1,19 @@ +-- Admission reservations are durable capacity claims. They are converted to +-- starting by the scheduler, while queued remains the single waiting slot. +ALTER TABLE app.job_runs DROP CONSTRAINT IF EXISTS job_runs_state_check; +ALTER TABLE app.job_runs ADD CONSTRAINT job_runs_state_check CHECK (state IN ('queued','reserved','starting','running','blocked','stopping','succeeded','failed','stopped')); +CREATE INDEX IF NOT EXISTS job_runs_reserved ON app.job_runs (created_at,id) WHERE state='reserved'; + +-- Keep a durable reservation visible to the alarm coordinator even if the +-- wake hint was consumed by a scheduler that crashed before claiming it. +CREATE OR REPLACE FUNCTION app.next_wake_at() RETURNS timestamptz LANGUAGE sql STABLE AS $$ + SELECT min(candidate) FROM ( + SELECT min(not_before) candidate FROM app.wake_hints + UNION ALL SELECT min(next_run_at) FROM app.schedule_state + UNION ALL SELECT min(next_attempt_at) FROM app.pending_verifications + UNION ALL SELECT min(created_at) FROM app.job_runs WHERE state='reserved' + UNION ALL SELECT min(launch_lease_expires_at) FROM app.job_runs WHERE state='starting' + UNION ALL SELECT min(next_poll_at) FROM app.job_runs WHERE state IN ('running','blocked','stopping') + UNION ALL SELECT min(cleanup_next_at) FROM app.runs WHERE NOT vm_cleanup_complete + ) wakes +$$; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 1781a773..ec5fc43b 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -706,7 +706,7 @@ export const API_ROUTES: RouteContract[] = [ }, "409": { description: - "queue_full \u2014 this job already has one queued run. Retry after it starts. Duplicate idempotency keys return the original run.", + "queue_full \u2014 all execution slots are reserved or occupied and one waiting run already exists. Duplicate idempotency keys return the original run.", }, }, }, diff --git a/packages/api/src/execution.ts b/packages/api/src/execution.ts index 20986b50..11e791d9 100644 --- a/packages/api/src/execution.ts +++ b/packages/api/src/execution.ts @@ -1,5 +1,5 @@ import type { TraceSource, TraceSources } from "./trace-source"; -export type ExecutionState = "queued" | "starting" | "running" | "blocked" | "stopping" | "stopped" | "succeeded" | "failed"; +export type ExecutionState = "queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "stopped" | "succeeded" | "failed"; export type ExecutionCapability = "output" | "prompt-delivery" | "recovery" | "stop"; export type PromptDeliveryState = "pending" | "submitting" | "accepted" | "ambiguous" | "failed"; @@ -60,7 +60,7 @@ export interface ExecutionBackend { /** Maps persisted execution states onto the public contract. */ export function normalizeExecutionState(state: unknown): ExecutionState { switch (String(state)) { - case "queued": case "starting": case "running": case "blocked": case "stopping": case "stopped": case "succeeded": case "failed": return String(state) as ExecutionState; + case "queued": case "reserved": case "starting": case "running": case "blocked": case "stopping": case "stopped": case "succeeded": case "failed": return String(state) as ExecutionState; case "done": return "succeeded"; case "cancelled": return "stopped"; default: return "failed"; diff --git a/packages/api/src/flow-schemas.ts b/packages/api/src/flow-schemas.ts index 77a362b5..310431f9 100644 --- a/packages/api/src/flow-schemas.ts +++ b/packages/api/src/flow-schemas.ts @@ -2,7 +2,7 @@ import { z } from "zod"; import { conditionsSchema, preparedWebhookSchema } from "./webhook-conditions"; export const scopeSchema = z.enum(["flows:read", "flows:write", "runs:read", "runs:write"]); -export const runStateSchema = z.enum(["queued", "starting", "running", "done", "blocked", "failed", "ignored", "succeeded", "stopping", "stopped"]); +export const runStateSchema = z.enum(["queued", "reserved", "starting", "running", "done", "blocked", "failed", "ignored", "succeeded", "stopping", "stopped"]); export const matchRuleSchema = z.object({ type: z.enum(["owner", "creator", "status", "label", "assignee"]), targetId: z.string().min(1), diff --git a/packages/api/src/flow-service.ts b/packages/api/src/flow-service.ts index da4e8862..8ecf2a02 100644 --- a/packages/api/src/flow-service.ts +++ b/packages/api/src/flow-service.ts @@ -87,7 +87,7 @@ export class ApiService { WITH selected_runs AS ( SELECT job_id,state,created_at,id FROM app.job_runs WHERE tenant_id=$1 AND job_id=ANY($2::uuid[]) ), counts AS ( - SELECT job_id,count(*) FILTER (WHERE state IN ('starting','running','blocked','stopping'))::text running_count + SELECT job_id,count(*) FILTER (WHERE state IN ('reserved','starting','running','blocked','stopping'))::text running_count FROM selected_runs GROUP BY job_id ), latest AS ( SELECT DISTINCT ON (job_id) job_id,state FROM selected_runs ORDER BY job_id,created_at DESC,id DESC diff --git a/packages/api/src/job-contracts.ts b/packages/api/src/job-contracts.ts index 609649d9..4e04401c 100644 --- a/packages/api/src/job-contracts.ts +++ b/packages/api/src/job-contracts.ts @@ -12,7 +12,7 @@ export const jobSelectorItem = z.object({ id: z.guid(), name: z.string(), slug: export const jobSummary = jobSelectorItem.extend({ model: z.string(), effort: z.string(), agentKind: z.string(), concurrencyLimit: z.number().int(), runningCount: z.number().int(), - lastRunState: z.enum(["queued", "starting", "running", "blocked", "stopping", "succeeded", "failed", "stopped", "done", "ignored"]).nullable(), createdAt: z.string(), updatedAt: z.string(), + lastRunState: z.enum(["queued", "reserved", "starting", "running", "blocked", "stopping", "succeeded", "failed", "stopped", "done", "ignored"]).nullable(), createdAt: z.string(), updatedAt: z.string(), }); export const jobSummaryPage = z.object({ items: z.array(jobSummary), nextCursor: z.guid().nullable() }); export const jobSelectorPage = z.object({ items: z.array(jobSelectorItem), nextCursor: z.guid().nullable() }); @@ -34,7 +34,7 @@ export const jobResponse = z.object({ promptTemplate: z.string(), runNameTemplate: z.string(), model: z.string(), effort: z.string().optional(), executionTarget: z.object({ connectionId: z.string(), workspace: z.string().optional(), cwd: z.string().optional(), agentKind: z.string() }), executionTargetId: z.string(), agentKind: z.string(), concurrencyLimit: z.number().int(), - runningCount: z.number().int(), currentRuns: z.number().int(), maxConcurrency: z.number().int(), lastRunState: z.enum(["queued", "starting", "running", "blocked", "stopping", "succeeded", "failed", "stopped", "done", "ignored"]).nullable(), + runningCount: z.number().int(), currentRuns: z.number().int(), maxConcurrency: z.number().int(), lastRunState: z.enum(["queued", "reserved", "starting", "running", "blocked", "stopping", "succeeded", "failed", "stopped", "done", "ignored"]).nullable(), triggers: z.array(triggerResponse), createdAt: z.string(), updatedAt: z.string(), }); diff --git a/packages/api/src/job-domain.ts b/packages/api/src/job-domain.ts index 565ccba0..0dda2739 100644 --- a/packages/api/src/job-domain.ts +++ b/packages/api/src/job-domain.ts @@ -3,7 +3,7 @@ import { renderTextTemplate } from "./text-template"; export type TriggerKind = "manual" | "schedule" | "webhook" | "jobLifecycle"; export type InvocationSource = "manual" | TriggerKind; -export type JobRunState = "queued" | "running" | "succeeded" | "failed" | "stopped"; +export type JobRunState = "queued" | "reserved" | "running" | "succeeded" | "failed" | "stopped"; export interface ExecutionTarget { connectionId: string; @@ -79,7 +79,7 @@ export interface InvocationResult { invocation: Invocation; run: JobRun; duplica export interface JobRepository { getJob(id: string): Promise; findInvocation(jobId: string, claimKey: string): Promise<{ invocation: Invocation; run: JobRun } | null>; - /** Atomically enforce one queued run per job; reject overflow with queue_full. */ + /** Atomically reserve a free slot, retaining at most one waiting run. */ insertInvocationAndRun(invocation: Invocation, run: JobRun): Promise; countActiveRuns(jobId: string): Promise; markRunRunning(runId: string, startedAt: string): Promise; diff --git a/packages/api/src/postgres/automation-scheduler.ts b/packages/api/src/postgres/automation-scheduler.ts index 357e8ac6..f53f89cb 100644 --- a/packages/api/src/postgres/automation-scheduler.ts +++ b/packages/api/src/postgres/automation-scheduler.ts @@ -103,7 +103,7 @@ export class AutomationScheduler { const result = await new InvocationService(this.repository(row.tenant_id), value => encrypt(value, this.env.CREDENTIAL_ENCRYPTION_KEY)).invoke(row.job_id, { source: "webhook", triggerId: row.trigger_id, claimKey: `webhook:${row.trigger_id}:${invocation.claimKey}`, context: { [row.trigger_slug]: context }, occurrence: { ...invocation.occurrence, metadata: { ...invocation.occurrence.metadata, triggerId: row.trigger_id, mergeable: false } } }); await finish(result.duplicate ? "duplicate" : "accepted", result.duplicate ? "Verified occurrence was already claimed." : "Merge-conflicted pull request queued through canonical job invocation."); } catch (error) { - if (error instanceof InvocationError && error.code === "queue_full") { await finish("queue_full", "Job already has a queued run; occurrence skipped."); continue; } + if (error instanceof InvocationError && error.code === "queue_full") { await finish("queue_full", "Job has no free execution slot and already has a waiting run; occurrence skipped."); continue; } const attempt = Number(row.attempt) + 1, detail = error instanceof Error ? error.message : "GitHub verification failed"; if (attempt >= 8) await finish("verification_failed", detail); else await this.database.pool.query("UPDATE app.pending_verifications SET attempt=$3,next_attempt_at=now()+make_interval(secs=>least(60,5*$3)) WHERE tenant_id=$1 AND id=$2", [row.tenant_id, row.id, attempt]); } diff --git a/packages/api/src/postgres/invocation-repository.ts b/packages/api/src/postgres/invocation-repository.ts index 297b6b33..06cadf63 100644 --- a/packages/api/src/postgres/invocation-repository.ts +++ b/packages/api/src/postgres/invocation-repository.ts @@ -1,4 +1,4 @@ -import { lockJobQueue, requireQueueCapacity } from "./queue-admission"; +import { lockJobQueue, reserveExecutionSlot } from "./queue-admission"; import type { Invocation, JobRun } from "../job-domain"; import type { Database, DatabaseClient } from "./database"; @@ -59,7 +59,7 @@ export class InvocationRepository { async create(invocation: Invocation, run: JobRun, wakeAt = new Date()): Promise { return this.database.transaction(async (client) => { - await lockJobQueue(client, this.tenantId, invocation.jobId); + const concurrencyLimit = await lockJobQueue(client, this.tenantId, invocation.jobId); const inserted = await client.query<{ id: string }>(` INSERT INTO app.invocations(tenant_id,id,job_id,source,claim_key,trigger_id,context,occurrence,created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) @@ -67,7 +67,7 @@ export class InvocationRepository { [this.tenantId, invocation.id, invocation.jobId, invocation.source, invocation.claimKey, invocation.triggerId, invocation.context, invocation.occurrence ?? null, invocation.createdAt]); if (inserted.rowCount) { - await requireQueueCapacity(client, this.tenantId, invocation.jobId); + await reserveExecutionSlot(client, this.tenantId, invocation.jobId, run, concurrencyLimit); await client.query(` INSERT INTO app.job_runs(tenant_id,id,job_id,invocation_id,state,encrypted_prompt,run_name,created_at,updated_at,started_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, diff --git a/packages/api/src/postgres/job-repository.ts b/packages/api/src/postgres/job-repository.ts index 8d0ef9fb..b6a13b87 100644 --- a/packages/api/src/postgres/job-repository.ts +++ b/packages/api/src/postgres/job-repository.ts @@ -1,4 +1,4 @@ -import { lockJobQueue, requireQueueCapacity } from "./queue-admission"; +import { lockJobQueue, reserveExecutionSlot } from "./queue-admission"; import type { Invocation, Job, JobRepository, JobRun, Trigger } from "../job-domain"; import type { Database, DatabaseClient } from "./database"; import { nextOccurrence, validateScheduleConfig } from "../schedule"; @@ -117,10 +117,10 @@ export class PostgresJobRepository implements JobRepository { } async insertInvocationAndRun(invocation: Invocation, run: JobRun): Promise { return this.database.transaction(async client => { - await lockJobQueue(client, this.tenantId, invocation.jobId); + const concurrencyLimit = await lockJobQueue(client, this.tenantId, invocation.jobId); const inserted = await client.query("INSERT INTO app.invocations(tenant_id,id,job_id,source,claim_key,trigger_id,context,occurrence,created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) ON CONFLICT (tenant_id,job_id,claim_key) DO NOTHING", [this.tenantId, invocation.id, invocation.jobId, invocation.source, invocation.claimKey, invocation.triggerId, invocation.context, invocation.occurrence ?? null, invocation.createdAt]); if (!inserted.rowCount) return false; - await requireQueueCapacity(client, this.tenantId, invocation.jobId); + await reserveExecutionSlot(client, this.tenantId, invocation.jobId, run, concurrencyLimit); await client.query("INSERT INTO app.job_runs(tenant_id,id,job_id,invocation_id,state,encrypted_prompt,run_name,created_at,updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)", [this.tenantId, run.id, run.jobId, run.invocationId, run.state, run.encryptedPrompt, run.runName ?? "", run.createdAt, run.updatedAt]); await client.query(`INSERT INTO app.runs(tenant_id,id,job_id,invocation_id,provider,issue_id,run_name,agent_name,workspace_name,agent_kind,state,execution_backend_kind,execution_capabilities,created_at,updated_at) SELECT $1,$2,$3,$4,$5,$6,$8,'',j.slug,j.execution_target->>'agentKind',$7, @@ -131,7 +131,7 @@ export class PostgresJobRepository implements JobRepository { return true; }); } - async countActiveRuns(jobId: string): Promise { return Number((await this.database.pool.query<{ count: string }>("SELECT count(*)::text count FROM app.job_runs WHERE tenant_id=$1 AND job_id=$2 AND state IN ('starting','running','blocked','stopping')", [this.tenantId, jobId])).rows[0]?.count ?? 0); } + async countActiveRuns(jobId: string): Promise { return Number((await this.database.pool.query<{ count: string }>("SELECT count(*)::text count FROM app.job_runs WHERE tenant_id=$1 AND job_id=$2 AND state IN ('reserved','starting','running','blocked','stopping')", [this.tenantId, jobId])).rows[0]?.count ?? 0); } async markRunRunning(runId: string, startedAt: string): Promise { const row = (await this.database.pool.query("UPDATE app.job_runs SET state='running',started_at=$3,updated_at=$3 WHERE tenant_id=$1 AND id=$2 AND state='queued' RETURNING *", [this.tenantId, runId, startedAt])).rows[0]; if (!row) throw new Error("Run is no longer queued"); diff --git a/packages/api/src/postgres/job-summary-repository.ts b/packages/api/src/postgres/job-summary-repository.ts index 95358d69..15c5af77 100644 --- a/packages/api/src/postgres/job-summary-repository.ts +++ b/packages/api/src/postgres/job-summary-repository.ts @@ -24,7 +24,7 @@ export class JobSummaryRepository { ) SELECT p.*,s.running_count,s.last_run_state FROM page p ${selector ? "LEFT JOIN LATERAL (SELECT '0'::text running_count,NULL::text last_run_state) s ON true" : `LEFT JOIN ( - SELECT r.job_id,count(*) FILTER (WHERE r.state IN ('starting','running','blocked','stopping'))::text running_count, + SELECT r.job_id,count(*) FILTER (WHERE r.state IN ('reserved','starting','running','blocked','stopping'))::text running_count, (array_agg(r.state ORDER BY r.created_at DESC,r.id DESC))[1] last_run_state FROM app.job_runs r JOIN page ON page.id=r.job_id WHERE r.tenant_id=$1 GROUP BY r.job_id ) s ON s.job_id=p.id`} diff --git a/packages/api/src/postgres/queue-admission.ts b/packages/api/src/postgres/queue-admission.ts index 73d66d06..13178f33 100644 --- a/packages/api/src/postgres/queue-admission.ts +++ b/packages/api/src/postgres/queue-admission.ts @@ -2,12 +2,29 @@ import { InvocationError } from "../job-domain"; import type { DatabaseClient } from "./database"; /** Hold until commit. All admission writers serialize on the tenant-qualified job. */ -export async function lockJobQueue(client: DatabaseClient, tenantId: string, jobId: string): Promise { - await client.query("SELECT id FROM app.jobs WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [tenantId, jobId]); +export async function lockJobQueue(client: DatabaseClient, tenantId: string, jobId: string): Promise { + const result = await client.query<{ concurrency_limit: number }>("SELECT concurrency_limit FROM app.jobs WHERE tenant_id=$1 AND id=$2 FOR UPDATE", [tenantId, jobId]); + return result.rows[0]?.concurrency_limit ?? 1; } /** Check after claiming the occurrence so duplicate retries still return their original run. */ -export async function requireQueueCapacity(client: DatabaseClient, tenantId: string, jobId: string): Promise { +export async function reserveExecutionSlot(client: DatabaseClient, tenantId: string, jobId: string, run: { state: string }, concurrencyLimit: number): Promise { + const activeStates = "('reserved','starting','running','blocked','stopping')"; + + // A newly free slot belongs to the oldest waiter before it belongs to a new arrival. + while (true) { + const active = await client.query<{ count: string }>(`SELECT count(*)::text count FROM app.job_runs WHERE tenant_id=$1 AND job_id=$2 AND state IN ${activeStates}`, [tenantId, jobId]); + if (Number(active.rows[0]?.count ?? 0) >= concurrencyLimit) break; + const promoted = await client.query(`UPDATE app.job_runs SET state='reserved',updated_at=now() WHERE tenant_id=$1 AND id=(SELECT id FROM app.job_runs WHERE tenant_id=$1 AND job_id=$2 AND state='queued' ORDER BY created_at,id FOR UPDATE SKIP LOCKED LIMIT 1) RETURNING id`, [tenantId, jobId]); + if (!promoted.rowCount) break; + } + + const active = await client.query<{ count: string }>(`SELECT count(*)::text count FROM app.job_runs WHERE tenant_id=$1 AND job_id=$2 AND state IN ${activeStates}`, [tenantId, jobId]); + if (Number(active.rows[0]?.count ?? 0) < concurrencyLimit) { + run.state = "reserved"; + return; + } const queued = await client.query("SELECT id FROM app.job_runs WHERE tenant_id=$1 AND job_id=$2 AND state='queued' LIMIT 1", [tenantId, jobId]); - if (queued.rows.length) throw new InvocationError("queue_full", "This job already has a queued run. Try again after it starts."); + if (queued.rows.length) throw new InvocationError("queue_full", "This job has no free execution slot and already has one waiting run. Try again after capacity is released."); + run.state = "queued"; } diff --git a/packages/api/src/postgres/run-query-repository.ts b/packages/api/src/postgres/run-query-repository.ts index 5dd63d85..9d78c020 100644 --- a/packages/api/src/postgres/run-query-repository.ts +++ b/packages/api/src/postgres/run-query-repository.ts @@ -58,5 +58,13 @@ export class RunQueryRepository { return { ...row, created_at: row.created_at.toISOString(), updated_at: row.updated_at.toISOString(), started_at: row.started_at?.toISOString() ?? null }; } async activity(runId: string) { return (await this.database.pool.query("SELECT action,detail,created_at FROM app.run_activity WHERE tenant_id=$1 AND run_id=$2 ORDER BY created_at,id", [this.tenantId, runId])).rows; } - async stop(runId: string) { return (await this.database.pool.query("UPDATE app.job_runs SET state='stopping',next_poll_at=now(),updated_at=now() WHERE tenant_id=$1 AND id=$2 AND state IN ('starting','running','blocked') RETURNING id,state", [this.tenantId, runId])).rows[0] ?? null; } + async stop(runId: string) { + return this.database.transaction(async client => { + const result = await client.query("UPDATE app.job_runs SET state=CASE WHEN state='reserved' THEN 'stopped' ELSE 'stopping' END,next_poll_at=CASE WHEN state='reserved' THEN NULL ELSE now() END,updated_at=now() WHERE tenant_id=$1 AND id=$2 AND state IN ('reserved','starting','running','blocked') RETURNING id,state", [this.tenantId, runId]); + const row = result.rows[0]; + if (row?.state === "stopped") await client.query("UPDATE app.runs SET state='stopped',claim_released=true,vm_cleanup_complete=true,updated_at=now() WHERE tenant_id=$1 AND id=$2", [this.tenantId, runId]); + if (row) await client.query("INSERT INTO app.wake_hints(key,not_before) VALUES ('global',now()) ON CONFLICT (key) DO UPDATE SET not_before=least(app.wake_hints.not_before,excluded.not_before),updated_at=now()"); + return row ?? null; + }); + } } diff --git a/packages/api/src/postgres/run-repository.ts b/packages/api/src/postgres/run-repository.ts index c45fd02f..a7a72281 100644 --- a/packages/api/src/postgres/run-repository.ts +++ b/packages/api/src/postgres/run-repository.ts @@ -29,7 +29,8 @@ export class RunRepository { const result = await client.query(`WITH candidate AS ( SELECT r.tenant_id,r.id FROM app.job_runs r JOIN app.jobs j ON j.tenant_id=r.tenant_id AND j.id=r.job_id WHERE j.enabled AND ((r.state='starting' AND r.launch_lease_expires_at().notNull(), claimKey: text("claim_key").notNull(), triggerId: uuid("trigger_id").notNull(), context: jsonb("context").$type>().notNull(), occurrence: jsonb("occurrence").$type(), createdAt: createdAt(), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.jobId, t.claimKey), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.triggerId], foreignColumns: [triggers.tenantId, triggers.id] }), check("invocations_source_check", sql`${t.source} in ('manual','schedule','webhook','jobLifecycle')`)]); export const jobRuns = app.table("job_runs", { - tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), invocationId: uuid("invocation_id").notNull(), state: text("state").notNull(), encryptedPrompt: text("encrypted_prompt").notNull(), runName: text("run_name").notNull().default(""), launchLeaseExpiresAt: timestamp("launch_lease_expires_at", { withTimezone: true }), nextPollAt: timestamp("next_poll_at", { withTimezone: true }), createdAt: createdAt(), updatedAt: updatedAt(), startedAt: timestamp("started_at", { withTimezone: true }), + tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), invocationId: uuid("invocation_id").notNull(), state: text("state").$type<"queued" | "reserved" | "starting" | "running" | "blocked" | "stopping" | "succeeded" | "failed" | "stopped">().notNull(), encryptedPrompt: text("encrypted_prompt").notNull(), runName: text("run_name").notNull().default(""), launchLeaseExpiresAt: timestamp("launch_lease_expires_at", { withTimezone: true }), nextPollAt: timestamp("next_poll_at", { withTimezone: true }), createdAt: createdAt(), updatedAt: updatedAt(), startedAt: timestamp("started_at", { withTimezone: true }), }, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.invocationId), foreignKey({ columns: [t.tenantId, t.jobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.invocationId], foreignColumns: [invocations.tenantId, invocations.id] }).onDelete("cascade"), index("job_runs_queue").on(t.state, t.createdAt).where(sql`${t.state}='queued'`), index("job_runs_poll_due").on(t.nextPollAt).where(sql`${t.state} in ('running','blocked','stopping')`), index("job_runs_launch_lease").on(t.launchLeaseExpiresAt).where(sql`${t.state}='starting'`)]); export const runs = app.table("runs", { diff --git a/packages/api/src/postgres/webhook-service.ts b/packages/api/src/postgres/webhook-service.ts index c984664e..fef63e53 100644 --- a/packages/api/src/postgres/webhook-service.ts +++ b/packages/api/src/postgres/webhook-service.ts @@ -49,7 +49,7 @@ export class WebhookService { await this.event(deliveryPk, candidate.job.id, provider, deliveryId, result.duplicate ? "duplicate" : "accepted", result.duplicate ? "Webhook occurrence was already claimed." : "Webhook occurrence queued through canonical job invocation."); } catch (error) { if (!(error instanceof InvocationError) || error.code !== "queue_full") throw error; - await this.event(deliveryPk, candidate.job.id, provider, deliveryId, "queue_full", "Job already has a queued run; occurrence skipped."); + await this.event(deliveryPk, candidate.job.id, provider, deliveryId, "queue_full", "Job has no free execution slot and already has a waiting run; occurrence skipped."); } } await this.database.pool.query("UPDATE app.webhook_deliveries SET outcome='ignored',detail='Delivery was received but did not match an enabled trigger.' WHERE tenant_id=$1 AND id=$2 AND outcome='received'", [this.tenantId, deliveryPk]); diff --git a/packages/api/src/run-read-contracts.ts b/packages/api/src/run-read-contracts.ts index d93747f6..a06dea48 100644 --- a/packages/api/src/run-read-contracts.ts +++ b/packages/api/src/run-read-contracts.ts @@ -1,5 +1,5 @@ import { z } from "zod"; -export const executionState = z.enum(["queued", "starting", "running", "blocked", "stopping", "succeeded", "failed", "stopped"]); +export const executionState = z.enum(["queued", "reserved", "starting", "running", "blocked", "stopping", "succeeded", "failed", "stopped"]); export const runStatusResponse = z.object({ id: z.string(), job_id: z.string(), state: executionState, run_name: z.string(), job_name: z.string(), destination_url: z.string().nullable(), diff --git a/packages/api/src/types.ts b/packages/api/src/types.ts index 8c93d5be..d3cc0ff5 100644 --- a/packages/api/src/types.ts +++ b/packages/api/src/types.ts @@ -1,6 +1,6 @@ export type FilterType = "owner" | "creator" | "status" | "label" | "assignee"; export interface MatchRule { type: FilterType; targetId: string; } -export type RunState = "queued" | "starting" | "running" | "done" | "blocked" | "failed" | "ignored" | "stopping" | "stopped" | "succeeded"; +export type RunState = "queued" | "reserved" | "starting" | "running" | "done" | "blocked" | "failed" | "ignored" | "stopping" | "stopped" | "succeeded"; export interface Env { SCHEDULER?: DurableObjectNamespace; diff --git a/packages/api/test/postgres-invocation-repository.test.ts b/packages/api/test/postgres-invocation-repository.test.ts index 60c37460..2cb21a79 100644 --- a/packages/api/test/postgres-invocation-repository.test.ts +++ b/packages/api/test/postgres-invocation-repository.test.ts @@ -10,16 +10,24 @@ const row = { invocation_id: invocation.id, job_id: invocation.jobId, source: in describe("InvocationRepository", () => { it("creates invocation, run, and wake hint in one transaction", async () => { - const query = vi.fn().mockResolvedValueOnce({ rows: [], rowCount: 0 }).mockResolvedValueOnce({ rows: [{ id: invocation.id }], rowCount: 1 }).mockResolvedValueOnce({ rows: [], rowCount: 0 }).mockResolvedValueOnce({ rows: [], rowCount: 1 }).mockResolvedValueOnce({ rows: [], rowCount: 1 }).mockResolvedValueOnce({ rows: [row], rowCount: 1 }); + const query = vi.fn() + .mockResolvedValueOnce({ rows: [], rowCount: 0 }) + .mockResolvedValueOnce({ rows: [{ id: invocation.id }], rowCount: 1 }) + .mockResolvedValueOnce({ rows: [{ count: "0" }], rowCount: 1 }) + .mockResolvedValueOnce({ rows: [], rowCount: 0 }) + .mockResolvedValueOnce({ rows: [{ count: "0" }], rowCount: 1 }) + .mockResolvedValueOnce({ rows: [], rowCount: 0 }) + .mockResolvedValueOnce({ rows: [], rowCount: 1 }) + .mockResolvedValueOnce({ rows: [row], rowCount: 1 }); const database = { pool: {}, transaction: (work: (client: { query: typeof query }) => unknown) => work({ query }) } as unknown as Database; const result = await new InvocationRepository(database, tenantId).create(invocation, run); expect(result.duplicate).toBe(false); expect(result.run.runName).toBe(run.runName); - expect(query.mock.calls[3][1][6]).toBe(run.runName); - expect(query).toHaveBeenCalledTimes(6); + expect(query.mock.calls[5][1][6]).toBe(run.runName); + expect(query).toHaveBeenCalledTimes(8); expect(query.mock.calls[0][1][0]).toBe(tenantId); - expect(query.mock.calls[4][0]).toContain("app.wake_hints"); - expect(query.mock.calls[5][1]).toEqual([tenantId, invocation.jobId, invocation.claimKey]); + expect(query.mock.calls[6][0]).toContain("app.wake_hints"); + expect(query.mock.calls[7][1]).toEqual([tenantId, invocation.jobId, invocation.claimKey]); }); it("returns the canonical winner without creating a second run", async () => { diff --git a/packages/api/test/postgres-queue-admission.test.ts b/packages/api/test/postgres-queue-admission.test.ts index bba25f8c..c15f7e42 100644 --- a/packages/api/test/postgres-queue-admission.test.ts +++ b/packages/api/test/postgres-queue-admission.test.ts @@ -17,15 +17,15 @@ describe.skipIf(!url)("PostgreSQL queue admission", () => { await database.close(); }); - async function fixture(jobId = crypto.randomUUID()) { + async function fixture(jobId = crypto.randomUUID(), concurrency = 1) { const tenantId = crypto.randomUUID(), triggerId = crypto.randomUUID(); tenants.push(tenantId); await database.pool.query("INSERT INTO app.tenants(id) VALUES ($1)", [tenantId]); - await database.pool.query("INSERT INTO app.jobs(tenant_id,id,name,slug,encrypted_prompt_template,execution_target,concurrency_limit) VALUES ($1,$2,'Queue test','queue-test','{{manual.prompt}}',$3,1)", [tenantId, jobId, { agentKind: "codex" }]); + await database.pool.query("INSERT INTO app.jobs(tenant_id,id,name,slug,encrypted_prompt_template,execution_target,concurrency_limit) VALUES ($1,$2,'Queue test','queue-test','{{manual.prompt}}',$3,$4)", [tenantId, jobId, { agentKind: "codex" }, concurrency]); await database.pool.query("INSERT INTO app.triggers(tenant_id,id,job_id,kind,slug) VALUES ($1,$2,$3,'manual','manual')", [tenantId, triggerId, jobId]); const service = new InvocationService(new PostgresJobRepository(database, tenantId, identity, identity), identity); const invoke = (claimKey: string, source: InvocationSource = "manual") => service.invoke(jobId, { source, triggerId, claimKey, context: { manual: { prompt: claimKey } } }); - const counts = async () => (await database.pool.query("SELECT (SELECT count(*)::int FROM app.invocations WHERE tenant_id=$1) invocations,(SELECT count(*)::int FROM app.job_runs WHERE tenant_id=$1 AND state='queued') queued,(SELECT count(*)::int FROM app.runs WHERE tenant_id=$1) runs", [tenantId])).rows[0]; + const counts = async () => (await database.pool.query("SELECT (SELECT count(*)::int FROM app.invocations WHERE tenant_id=$1) invocations,(SELECT count(*)::int FROM app.job_runs WHERE tenant_id=$1 AND state='queued') queued,(SELECT count(*)::int FROM app.job_runs WHERE tenant_id=$1 AND state='reserved') reserved,(SELECT count(*)::int FROM app.runs WHERE tenant_id=$1) runs", [tenantId])).rows[0]; return { tenantId, jobId, invoke, counts }; } @@ -33,9 +33,9 @@ describe.skipIf(!url)("PostgreSQL queue admission", () => { const f = await fixture(); const sources: InvocationSource[] = ["manual", "webhook", "schedule", "jobLifecycle"]; const results = await Promise.allSettled(Array.from({ length: 20 }, (_, i) => f.invoke(`event:${i}`, sources[i % 4]))); - expect(results.filter(r => r.status === "fulfilled")).toHaveLength(1); + expect(results.filter(r => r.status === "fulfilled")).toHaveLength(2); for (const result of results) if (result.status === "rejected") expect(result.reason.code).toBe("queue_full"); - expect(await f.counts()).toEqual({ invocations: 1, queued: 1, runs: 1 }); + expect(await f.counts()).toEqual({ invocations: 2, queued: 1, reserved: 1, runs: 2 }); const otherTenant = await fixture(f.jobId); await expect(otherTenant.invoke("other")).resolves.toMatchObject({ duplicate: false }); }); @@ -45,7 +45,7 @@ describe.skipIf(!url)("PostgreSQL queue admission", () => { const results = await Promise.all(Array.from({ length: 12 }, () => f.invoke("same"))); expect(new Set(results.map(result => result.run.id)).size).toBe(1); expect(results.filter(result => !result.duplicate)).toHaveLength(1); - expect(await f.counts()).toEqual({ invocations: 1, queued: 1, runs: 1 }); + expect(await f.counts()).toEqual({ invocations: 1, queued: 0, reserved: 1, runs: 1 }); }); it("allows one waiting run beside an active run and recovers expired launches without requeuing", async () => { @@ -67,4 +67,14 @@ describe.skipIf(!url)("PostgreSQL queue admission", () => { await expect(f.invoke("next")).resolves.toMatchObject({ duplicate: false }); expect((await f.counts()).queued).toBe(1); }); + + it("reserves every free slot before allowing one waiting run", async () => { + const f = await fixture(crypto.randomUUID(), 10); + const accepted = await Promise.all(Array.from({ length: 11 }, (_, i) => f.invoke(`burst:${i}`))); + expect(accepted).toHaveLength(11); + expect((await f.counts()).reserved).toBe(10); + expect((await f.counts()).queued).toBe(1); + await expect(f.invoke("burst:overflow")).rejects.toMatchObject({ code: "queue_full" }); + expect((await f.counts()).invocations).toBe(11); + }); }); diff --git a/packages/api/test/static-slice.e2e.test.ts b/packages/api/test/static-slice.e2e.test.ts index f79d57f2..5d005554 100644 --- a/packages/api/test/static-slice.e2e.test.ts +++ b/packages/api/test/static-slice.e2e.test.ts @@ -44,7 +44,7 @@ describe.skipIf(!url)("compiled React + actual Worker API + PostgreSQL", () => { const runId = new URL(page.url()).pathname.split("/").at(-1)!; expect(calls.filter(call => call === `POST /api/v1/jobs/${f.jobIds[1]}/invocations`)).toHaveLength(1); const row = (await f.db.pool.query("SELECT i.context,jr.state FROM app.invocations i JOIN app.job_runs jr ON jr.tenant_id=i.tenant_id AND jr.invocation_id=i.id WHERE jr.tenant_id=$1 AND jr.id=$2", [f.tenantId, runId])).rows[0]; - expect(row).toMatchObject({ state: "queued", context: { manual: { prompt: "Real invocation", data: {} } } }); + expect(row).toMatchObject({ state: "reserved", context: { manual: { prompt: "Real invocation", data: {} } } }); await page.reload(); await page.getByText("No trace events yet.", { exact: true }).waitFor(); await f.db.transaction(async client => { await client.query("INSERT INTO app.run_trace_events(tenant_id,run_id,sequence,id,event_type,title,preview_text,display_data) VALUES ($1,$2,1,'canonical','assistant_message','Final output','Safe output','{}')", [f.tenantId, runId]); diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 8359b34d..3684adb4 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -64,6 +64,7 @@ components: type: string enum: - queued + - reserved - starting - running - blocked @@ -161,6 +162,7 @@ components: type: string enum: - queued + - reserved - starting - running - blocked @@ -4648,6 +4650,7 @@ paths: - type: string enum: - queued + - reserved - starting - running - blocked @@ -4913,6 +4916,7 @@ paths: - type: string enum: - queued + - reserved - starting - running - blocked @@ -5373,6 +5377,7 @@ paths: - type: string enum: - queued + - reserved - starting - running - blocked @@ -5875,7 +5880,7 @@ paths: $ref: "#/components/responses/Error404" "409": $ref: "#/components/responses/Error409" - description: queue_full — this job already has one queued run. Retry after it starts. Duplicate idempotency keys return the original run. + description: queue_full — all execution slots are reserved or occupied and one waiting run already exists. Duplicate idempotency keys return the original run. "415": $ref: "#/components/responses/Error415" "429": @@ -6123,6 +6128,7 @@ paths: - type: string enum: - queued + - reserved - starting - running - blocked @@ -6596,6 +6602,7 @@ paths: - type: string enum: - queued + - reserved - starting - running - blocked @@ -7399,6 +7406,7 @@ paths: type: string enum: - queued + - reserved - starting - running - done @@ -7728,6 +7736,7 @@ paths: type: string enum: - queued + - reserved - starting - running - blocked