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
2 changes: 1 addition & 1 deletion packages/api-client/src/schema.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1691,7 +1691,7 @@ export interface paths {
};
/**
* List runs
* @description Returns tenant-authorized runs. Project, job, and state filters accept repeated values and match any selected value within each filter; filters are applied before cursor pagination. When sort is supplied, ordering is applied before cursor pagination; statuses sort lexically by their persisted state, missing values sort last, and ties use run ID. Without sort, runs remain newest-created first.
* @description Returns tenant-authorized runs. Project, job, and state filters accept repeated values and match any selected value within each filter; filters are applied before cursor pagination. When sort is supplied, ordering is applied before cursor pagination; statuses sort lexically by their persisted state, missing values sort last, and ties use run ID. Without sort, queued, reserved, and starting runs come first, running runs second, and all other states last; each group is ordered by creation time descending, then run ID descending. The opaque default cursor includes the priority group and creation time. Legacy two-field cursors resume at their original chronological boundary. Run states can change between requests and move rows across groups; restart pagination from the first page after observing a state transition if a gap-free live view is needed.
*
* Requires the runs:read scope.
*
Expand Down
11 changes: 11 additions & 0 deletions packages/api/migrations/0036_run_priority_order_indexes.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
CREATE INDEX runs_priority_order
ON app.runs (tenant_id,
(CASE WHEN state IN ('queued','reserved','starting') THEN 0 WHEN state='running' THEN 1 ELSE 2 END),
created_at DESC,id DESC);

CREATE INDEX runs_priority_job_order
ON app.runs (tenant_id,job_id,
(CASE WHEN state IN ('queued','reserved','starting') THEN 0 WHEN state='running' THEN 1 ELSE 2 END),
created_at DESC,id DESC);

INSERT INTO app.schema_migrations(version) VALUES ('0036_run_priority_order_indexes') ON CONFLICT DO NOTHING;
2 changes: 1 addition & 1 deletion packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -901,7 +901,7 @@ export const API_ROUTES: RouteContract[] = [
"runs:read",
{
summary: "List runs",
description: "Returns tenant-authorized runs. Project, job, and state filters accept repeated values and match any selected value within each filter; filters are applied before cursor pagination. When sort is supplied, ordering is applied before cursor pagination; statuses sort lexically by their persisted state, missing values sort last, and ties use run ID. Without sort, runs remain newest-created first.",
description: "Returns tenant-authorized runs. Project, job, and state filters accept repeated values and match any selected value within each filter; filters are applied before cursor pagination. When sort is supplied, ordering is applied before cursor pagination; statuses sort lexically by their persisted state, missing values sort last, and ties use run ID. Without sort, queued, reserved, and starting runs come first, running runs second, and all other states last; each group is ordered by creation time descending, then run ID descending. The opaque default cursor includes the priority group and creation time. Legacy two-field cursors resume at their original chronological boundary. Run states can change between requests and move rows across groups; restart pagination from the first page after observing a state transition if a gap-free live view is needed.",
responses: {
"200": {
description: "Paginated runs",
Expand Down
20 changes: 13 additions & 7 deletions packages/api/src/postgres/run-query-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ const sortExpressions = {
agent: "r.agent_kind",
} as const;
type RunSort = keyof typeof sortExpressions;
const runPriority = (state: unknown) => state === "queued" || state === "reserved" || state === "starting" ? 0 : state === "running" ? 1 : 2;
const runPrioritySql = "CASE WHEN r.state IN ('queued','reserved','starting') THEN 0 WHEN r.state='running' THEN 1 ELSE 2 END";

export class RunQueryRepository {
constructor(private database: Database, private tenantId: string) { if (!tenantId) throw new Error("tenantId is required"); }
Expand All @@ -24,19 +26,23 @@ export class RunQueryRepository {
const states = query.getAll("state");
if (states.length) { values.push(states.flatMap(state => state === "done" ? ["done", "succeeded"] : [state])); clauses.push(`r.state=ANY($${values.length}::text[])`); }
if (query.get("contextQuery")) { values.push(`%${query.get("contextQuery")}%`); clauses.push(`i.context::text ILIKE $${values.length}`); }
if (sort && cursor?.length === 5 && cursor[0] === sort && cursor[1] === direction.toLowerCase()) {
if (!sort && cursor?.length === 3 && [0, 1, 2].includes(Number(cursor[0])) && typeof cursor[1] === "string" && typeof cursor[2] === "string") {
values.push(Number(cursor[0]), cursor[1], cursor[2]);
clauses.push(`(${runPrioritySql} > $${values.length - 2} OR (${runPrioritySql} = $${values.length - 2} AND (r.created_at,r.id)<($${values.length - 1}::timestamptz,$${values.length}::uuid)))`);
} else if (!sort && cursor?.length === 2) {
// Resume pre-priority cursors at their original chronological boundary.
values.push(cursor[0], cursor[1]); clauses.push(`(r.created_at,r.id)<($${values.length - 1}::timestamptz,$${values.length}::uuid)`);
} else if (sort && cursor?.length === 5 && cursor[0] === sort && cursor[1] === direction.toLowerCase()) {
const expression = sortExpressions[sort], nullFlag = `(CASE WHEN ${expression} IS NULL THEN 1 ELSE 0 END)`, after = direction === "ASC" ? ">" : "<";
values.push(Number(cursor[2]), cursor[3] ?? null, cursor[4]);
const valuePlaceholder = sort === "created" ? `$${values.length - 1}::timestamptz` : `$${values.length - 1}`;
clauses.push(`(${nullFlag} > $${values.length - 2} OR (${nullFlag} = $${values.length - 2} AND ((${expression} ${after} ${valuePlaceholder}) OR (${expression} IS NOT DISTINCT FROM ${valuePlaceholder} AND r.id ${after} $${values.length}::uuid))))`);
} else if (!sort && cursor?.length === 2) {
values.push(cursor[0], cursor[1]); clauses.push(`(r.created_at,r.id)<($${values.length - 1}::timestamptz,$${values.length}::uuid)`);
}
values.push(limit + 1);
const order = sort ? `CASE WHEN ${sortExpressions[sort]} IS NULL THEN 1 ELSE 0 END ASC, ${sortExpressions[sort]} ${direction} NULLS LAST, r.id ${direction}` : "r.created_at DESC,r.id DESC";
const selectedOrder = order.replaceAll("r.", "selected.").replaceAll("j.name", "selected.job_name");
const order = sort ? `CASE WHEN ${sortExpressions[sort]} IS NULL THEN 1 ELSE 0 END ASC, ${sortExpressions[sort]} ${direction} NULLS LAST, r.id ${direction}` : `${runPrioritySql} ASC,r.created_at DESC,r.id DESC`;
const selectedOrder = sort ? order.replaceAll("r.", "selected.").replaceAll("j.name", "selected.job_name") : "selected.priority ASC,selected.created_at DESC,selected.id DESC";
const result = await this.database.pool.query<any>(`WITH selected AS MATERIALIZED (
SELECT r.id,r.job_id,j.project_id,j.name job_name,p.name project_name,r.issue_id,r.issue_url,r.issue_title,r.run_name,r.agent_name,r.workspace_name,r.agent_kind,coalesce(r.execution_config->>'executionType','agent') execution_type,r.state,r.failure_source,r.failure_code,r.failure_reason,
SELECT r.id,r.job_id,j.project_id,j.name job_name,p.name project_name,r.issue_id,r.issue_url,r.issue_title,r.run_name,r.agent_name,r.workspace_name,r.agent_kind,coalesce(r.execution_config->>'executionType','agent') execution_type,r.state,${runPrioritySql} priority,r.failure_source,r.failure_code,r.failure_reason,
CASE WHEN r.failure_code IS NULL OR r.failure_reason IS NULL THEN NULL ELSE jsonb_build_object('source',CASE WHEN r.failure_source='agent' THEN 'run' ELSE 'system' END,'code',r.failure_code,'reason',r.failure_reason) END failure,
CASE WHEN r.agent_error_reason IS NULL THEN NULL ELSE jsonb_build_object('reason',r.agent_error_reason,'reported_at',r.agent_error_reported_at,'reporter',jsonb_build_object('user_id',r.agent_error_reporter_user_id,'kind',r.agent_error_reporter_kind,'id',r.agent_error_reporter_id)) END agent_error,
r.provider,r.execution_backend_kind backend_kind,r.execution_capabilities capabilities,r.destination_url,r.artifact_state,r.artifact_error,r.created_at,r.updated_at,jr.started_at,jr.updated_at job_run_updated_at
Expand Down Expand Up @@ -67,7 +73,7 @@ export class RunQueryRepository {
const nextCursor = hasMore && last ? sort ? (() => {
const value = sort === "run" ? (last.run_name || last.issue_title || "Run") : last[sort === "job" ? "job_name" : sort === "status" ? "state" : sort === "created" ? "created_at" : "agent_kind"];
return encodeCursor([sort, direction.toLowerCase(), sort === "run" || value != null ? 0 : 1, value, last.id]);
})() : encodeCursor([last.created_at, last.id]) : null;
})() : encodeCursor([runPriority(last.state), last.created_at.toISOString(), last.id]) : null;
return { items: rows, nextCursor };
}
async get(runId: string) {
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/postgres/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ export const jobRuns = app.table("job_runs", {
export const runs = app.table("runs", {
executionConfig: jsonb("execution_config").$type<ExecutionConfig>().notNull(),
tenantId: uuid("tenant_id").notNull(), id: uuid("id").notNull(), jobId: uuid("job_id").notNull(), invocationId: uuid("invocation_id").notNull(), provider: text("provider").notNull(), issueId: text("issue_id").notNull(), issueUrl: text("issue_url"), issueTitle: text("issue_title").notNull().default(""), runName: text("run_name").notNull().default(""), agentName: text("agent_name").notNull(), workspaceName: text("workspace_name").notNull().default(""), agentKind: text("agent_kind").notNull().default(""), state: text("state").notNull(), executionBackendKind: text("execution_backend_kind").notNull().default(""), executionHandle: jsonb("execution_handle").$type<Record<string, unknown>>(), executionCapabilities: jsonb("execution_capabilities").$type<string[]>().notNull().default([]), destinationUrl: text("destination_url"), artifactState: text("artifact_state").$type<ArtifactState>().notNull().default("pending"), artifactError: text("artifact_error"), failureCode: text("failure_code"), failureReason: text("failure_reason"), resultProtocolVersion: integer("result_protocol_version").notNull().default(0), jobResult: jsonb("job_result").$type<import("../job-result").JobResult>(), failureSource: text("failure_source").$type<"system" | "agent">(), agentErrorReason: text("agent_error_reason"), agentErrorReportedAt: timestamp("agent_error_reported_at", { withTimezone: true }), agentErrorReporterUserId: uuid("agent_error_reporter_user_id"), agentErrorReporterKind: text("agent_error_reporter_kind"), agentErrorReporterId: text("agent_error_reporter_id"), traceSources: jsonb("trace_sources").$type<import("../trace-source").TraceSources>(), executionDiagnostics: jsonb("execution_diagnostics").$type<import("../harness-diagnostics").ExecutionDiagnostics>(), claimReleased: boolean("claim_released").notNull().default(false), vmCleanupAttempt: integer("vm_cleanup_attempt").notNull().default(0), cleanupNextAt: timestamp("cleanup_next_at", { withTimezone: true }), vmCleanupComplete: boolean("vm_cleanup_complete").notNull().default(false), createdAt: createdAt(), updatedAt: updatedAt(),
}, 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("runs_order").on(t.tenantId, t.createdAt.desc(), t.id.desc()), index("runs_state_order").on(t.tenantId, t.state, t.createdAt.desc(), t.id.desc()), index("runs_cleanup_due").on(t.cleanupNextAt).where(sql`not ${t.vmCleanupComplete}`), index("runs_issue_trgm").using("gin", sql`${t.issueId} gin_trgm_ops`), index("runs_name_trgm").using("gin", sql`${t.runName} gin_trgm_ops`)]);
}, 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("runs_order").on(t.tenantId, t.createdAt.desc(), t.id.desc()), index("runs_state_order").on(t.tenantId, t.state, t.createdAt.desc(), t.id.desc()), index("runs_priority_order").on(t.tenantId, sql`CASE WHEN ${t.state} IN ('queued','reserved','starting') THEN 0 WHEN ${t.state}='running' THEN 1 ELSE 2 END`, t.createdAt.desc(), t.id.desc()), index("runs_priority_job_order").on(t.tenantId, t.jobId, sql`CASE WHEN ${t.state} IN ('queued','reserved','starting') THEN 0 WHEN ${t.state}='running' THEN 1 ELSE 2 END`, t.createdAt.desc(), t.id.desc()), index("runs_cleanup_due").on(t.cleanupNextAt).where(sql`not ${t.vmCleanupComplete}`), index("runs_issue_trgm").using("gin", sql`${t.issueId} gin_trgm_ops`), index("runs_name_trgm").using("gin", sql`${t.runName} gin_trgm_ops`)]);
export const runArtifacts = app.table("run_artifacts", {
tenantId: uuid("tenant_id").notNull(), runId: uuid("run_id").notNull(), id: uuid("id").notNull(), kind: text("kind").$type<ArtifactKind>().notNull(), objectKey: text("object_key").notNull(), provider: text("provider").notNull(), format: text("format").notNull(), formatVersion: text("format_version"), cliVersion: text("cli_version"), nativeSessionId: text("native_session_id"), sourceGeneration: text("source_generation"), sourcePath: text("source_path"), mediaType: text("media_type"), harnessVersion: text("harness_version"), byteSize: bigint("byte_size", { mode: "number" }).notNull(), sha256: text("sha256").notNull(), state: text("state").$type<ArtifactState>().notNull(), createdAt: createdAt(),
}, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.objectKey), foreignKey({ columns: [t.tenantId, t.runId], foreignColumns: [runs.tenantId, runs.id] }).onDelete("cascade"), index("run_artifacts_by_run").on(t.tenantId, t.runId, t.createdAt, t.id)]);
Expand Down
29 changes: 29 additions & 0 deletions packages/api/test/postgres-run-query-repository.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,35 @@ describe("run timing queries", () => {
}
});

it("prioritizes queued and starting runs, then running, ahead of other states", async () => {
const query = vi.fn(async () => ({ rows: [{ id: "run", state: "queued", created_at: new Date("2026-09-18T12:00:00Z") }] }));
const result = await new RunQueryRepository({ pool: { query } } as any, "tenant").list(new URLSearchParams());
const [sql] = query.mock.calls[0] as unknown as [string, unknown[]];
expect(sql).toContain("CASE WHEN r.state IN ('queued','reserved','starting') THEN 0 WHEN r.state='running' THEN 1 ELSE 2 END ASC,r.created_at DESC,r.id DESC");
expect(sql).toContain("selected.priority ASC,selected.created_at DESC,selected.id DESC");
expect(result.nextCursor).toBeNull();
});

it("continues default pages by priority and deterministic timestamp and ID", async () => {
const query = vi.fn(async () => ({ rows: [{ id: "00000000-0000-4000-8000-000000000003", state: "running", created_at: new Date("2026-09-18T12:00:00Z") }] }));
const cursor = btoa(JSON.stringify([0, "2026-09-18T12:01:00.000Z", "00000000-0000-4000-8000-000000000002"]));
await new RunQueryRepository({ pool: { query } } as any, "tenant").list(new URLSearchParams({ cursor, limit: "1" }));
const [sql, values] = query.mock.calls[0] as unknown as [string, unknown[]];
expect(sql).toContain("CASE WHEN r.state IN ('queued','reserved','starting') THEN 0 WHEN r.state='running' THEN 1 ELSE 2 END > $2");
expect(sql).toContain("(r.created_at,r.id)<($3::timestamptz,$4::uuid)");
expect(values).toEqual(["tenant", 0, "2026-09-18T12:01:00.000Z", "00000000-0000-4000-8000-000000000002", 2]);
});

it("accepts legacy chronological cursors while using the prioritized default order", async () => {
const query = vi.fn(async () => ({ rows: [] }));
const cursor = btoa(JSON.stringify(["2026-09-18T12:01:00.000Z", "00000000-0000-4000-8000-000000000002"]));
await new RunQueryRepository({ pool: { query } } as any, "tenant").list(new URLSearchParams({ cursor }));
const [sql, values] = query.mock.calls[0] as unknown as [string, unknown[]];
expect(sql).toContain("(r.created_at,r.id)<($2::timestamptz,$3::uuid)");
expect(sql).toContain("selected.priority ASC,selected.created_at DESC,selected.id DESC");
expect(values.slice(0, 3)).toEqual(["tenant", "2026-09-18T12:01:00.000Z", "00000000-0000-4000-8000-000000000002"]);
});

it.each([
["job", "asc", "j.name ASC"],
["job", "desc", "j.name DESC"],
Expand Down
Loading
Loading