Skip to content
Merged
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
20 changes: 10 additions & 10 deletions packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[];
Expand All @@ -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[];
Expand Down Expand Up @@ -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;
}[];
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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"];
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down
19 changes: 19 additions & 0 deletions packages/api/migrations/0015_reserved_execution_slots.sql
Original file line number Diff line number Diff line change
@@ -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
$$;
2 changes: 1 addition & 1 deletion packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
},
},
},
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/execution.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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";
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/flow-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/job-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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() });
Expand All @@ -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(),
});
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/job-domain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -79,7 +79,7 @@ export interface InvocationResult { invocation: Invocation; run: JobRun; duplica
export interface JobRepository {
getJob(id: string): Promise<Job | null>;
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<boolean>;
countActiveRuns(jobId: string): Promise<number>;
markRunRunning(runId: string, startedAt: string): Promise<JobRun>;
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/postgres/automation-scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
}
Expand Down
6 changes: 3 additions & 3 deletions packages/api/src/postgres/invocation-repository.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -59,15 +59,15 @@ export class InvocationRepository {

async create(invocation: Invocation, run: JobRun, wakeAt = new Date()): Promise<PersistedInvocation & { duplicate: boolean }> {
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)
ON CONFLICT (tenant_id,job_id,claim_key) DO NOTHING RETURNING id`,
[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)`,
Expand Down
8 changes: 4 additions & 4 deletions packages/api/src/postgres/job-repository.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -117,10 +117,10 @@ export class PostgresJobRepository implements JobRepository {
}
async insertInvocationAndRun(invocation: Invocation, run: JobRun): Promise<boolean> {
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,
Expand All @@ -131,7 +131,7 @@ export class PostgresJobRepository implements JobRepository {
return true;
});
}
async countActiveRuns(jobId: string): Promise<number> { 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<number> { 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<JobRun> {
const row = (await this.database.pool.query<any>("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");
Expand Down
Loading
Loading