diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index d33d76cb..a910f642 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -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. * diff --git a/packages/api/migrations/0036_run_priority_order_indexes.sql b/packages/api/migrations/0036_run_priority_order_indexes.sql new file mode 100644 index 00000000..2cdb0130 --- /dev/null +++ b/packages/api/migrations/0036_run_priority_order_indexes.sql @@ -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; diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index aab9e1ef..aa6e4b45 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -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", diff --git a/packages/api/src/postgres/run-query-repository.ts b/packages/api/src/postgres/run-query-repository.ts index 0c49613a..db31518f 100644 --- a/packages/api/src/postgres/run-query-repository.ts +++ b/packages/api/src/postgres/run-query-repository.ts @@ -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"); } @@ -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(`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 @@ -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) { diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 7d2f4d16..5bb398ab 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -92,7 +92,7 @@ export const jobRuns = app.table("job_runs", { export const runs = app.table("runs", { executionConfig: jsonb("execution_config").$type().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>(), executionCapabilities: jsonb("execution_capabilities").$type().notNull().default([]), destinationUrl: text("destination_url"), artifactState: text("artifact_state").$type().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(), 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(), executionDiagnostics: jsonb("execution_diagnostics").$type(), 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().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().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)]); diff --git a/packages/api/test/postgres-run-query-repository.test.ts b/packages/api/test/postgres-run-query-repository.test.ts index c4553683..1e01af14 100644 --- a/packages/api/test/postgres-run-query-repository.test.ts +++ b/packages/api/test/postgres-run-query-repository.test.ts @@ -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"], diff --git a/packages/api/test/run-reads.postgres.test.ts b/packages/api/test/run-reads.postgres.test.ts index a6c3b869..2c0a51a5 100644 --- a/packages/api/test/run-reads.postgres.test.ts +++ b/packages/api/test/run-reads.postgres.test.ts @@ -75,8 +75,8 @@ describe.skipIf(!url)("lightweight status and revision-bound traces", () => { const service = new ApiService(f.env, f.auth); try { const first = await service.listRuns(new URLSearchParams({ limit: "2", jobId: (await f.db.pool.query("SELECT job_id FROM app.job_runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId])).rows[0].job_id })); - expect(first.items.map(run => run.id)).toEqual([f.runId, completedId]); - expect(first.items.map(run => run.elapsed_time)).toEqual([{ duration: 40 }, { duration: 10 }]); + expect(first.items.map(run => run.id)).toEqual([runningId, f.runId]); + expect(first.items.map(run => run.elapsed_time)).toEqual([{ low: 10, high: 40 }, { duration: 40 }]); expect(first.nextCursor).not.toBeNull(); const statement = query.mock.calls.find(([sql]) => typeof sql === "string" && sql.includes("duration_jobs AS MATERIALIZED"))?.[0] as string; expect(statement).toContain("selected AS MATERIALIZED"); @@ -84,8 +84,8 @@ describe.skipIf(!url)("lightweight status and revision-bound traces", () => { expect(statement).not.toContain("LEFT JOIN LATERAL"); const second = await service.listRuns(new URLSearchParams({ limit: "2", jobId: (await f.db.pool.query("SELECT job_id FROM app.job_runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId])).rows[0].job_id, cursor: first.nextCursor! })); - expect(second.items.map(run => run.id)).toEqual([runningId]); - expect(second.items[0].elapsed_time).toEqual({ low: 10, high: 40 }); + expect(second.items.map(run => run.id)).toEqual([completedId]); + expect(second.items[0].elapsed_time).toEqual({ duration: 10 }); expect(second.nextCursor).toBeNull(); await f.db.pool.query("UPDATE app.job_runs SET started_at=NULL WHERE tenant_id=$1 AND id=ANY($2::uuid[])", [f.tenantId, [f.runId, completedId]]); @@ -93,4 +93,65 @@ describe.skipIf(!url)("lightweight status and revision-bound traces", () => { expect(noDurations.items.find(run => run.id === runningId)?.elapsed_time).toBeNull(); } finally { query.mockRestore(); } }); + + it("orders every default priority group with stable ties, filters, cursors and live state changes", async () => { + const jobId = (await f.db.pool.query("SELECT job_id FROM app.runs WHERE tenant_id=$1 AND id=$2", [f.tenantId, f.runId])).rows[0].job_id; + const originals = (await f.db.pool.query("SELECT id,state,created_at FROM app.runs WHERE tenant_id=$1 AND job_id=$2 ORDER BY id", [f.tenantId, jobId])).rows; + const otherIds = originals.map((row: any) => row.id).filter((id: string) => id !== f.runId); + const reservedId = otherIds[0], runningId = otherIds[1]; + const startingId = crypto.randomUUID(), blockedId = crypto.randomUUID(), invocationIds = [crypto.randomUUID(), crypto.randomUUID()]; + const createdAt = { + [f.runId]: "2029-01-02T00:00:00Z", + [reservedId]: "2029-01-02T00:00:00Z", + [runningId]: "2029-01-04T00:00:00Z", + [startingId]: "2029-01-03T00:00:00Z", + [blockedId]: "2029-01-05T00:00:00Z", + }; + const states = { [f.runId]: "queued", [reservedId]: "reserved", [runningId]: "running" }; + const insertedIds = [startingId, blockedId]; + try { + for (const row of originals) { + const state = states[row.id as keyof typeof states] ?? "succeeded"; + await f.db.pool.query("UPDATE app.runs SET state=$3,created_at=$4 WHERE tenant_id=$1 AND id=$2", [f.tenantId, row.id, state, createdAt[row.id as keyof typeof createdAt]]); + await f.db.pool.query("UPDATE app.job_runs SET state=$3,created_at=$4 WHERE tenant_id=$1 AND id=$2", [f.tenantId, row.id, state, createdAt[row.id as keyof typeof createdAt]]); + } + const triggerId = (await f.db.pool.query("SELECT id FROM app.triggers WHERE tenant_id=$1 AND job_id=$2 AND kind='manual' LIMIT 1", [f.tenantId, jobId])).rows[0].id; + for (const [index, [id, state]] of [[startingId, "starting"], [blockedId, "blocked"]].entries()) { + const invocationId = invocationIds[index], time = createdAt[id as keyof typeof createdAt]; + await f.db.pool.query("INSERT INTO app.invocations(tenant_id,id,job_id,source,claim_key,trigger_id,context) VALUES ($1,$2,$3,'manual',$4,$5,'{}')", [f.tenantId, invocationId, jobId, `priority-${id}`, triggerId]); + await f.db.pool.query("INSERT INTO app.job_runs(tenant_id,id,job_id,invocation_id,state,encrypted_prompt,created_at) VALUES ($1,$2,$3,$4,$5,'synthetic',$6)", [f.tenantId, id, jobId, invocationId, state, time]); + await f.db.pool.query("INSERT INTO app.runs(tenant_id,id,job_id,invocation_id,provider,issue_id,agent_name,state,execution_backend_kind,execution_config,created_at) VALUES ($1,$2,$3,$4,'manual',$5,'synthetic',$6,'exe-vm','{}',$7)", [f.tenantId, id, jobId, invocationId, `priority-${id}`, state, time]); + } + + const service = new ApiService(f.env, f.auth); + const first = await service.listRuns(new URLSearchParams({ jobId, limit: "2" })); + const tied = [f.runId, reservedId].sort().reverse(); + expect(first.items.map(run => run.id)).toEqual([startingId, tied[0]]); + const second = await service.listRuns(new URLSearchParams({ jobId, limit: "2", cursor: first.nextCursor! })); + expect(second.items.map(run => run.id)).toEqual([tied[1], runningId]); + const third = await service.listRuns(new URLSearchParams({ jobId, limit: "2", cursor: second.nextCursor! })); + expect(third.items.map(run => run.id)).toEqual([blockedId]); + expect(third.nextCursor).toBeNull(); + + const filtered = await service.listRuns(new URLSearchParams([["jobId", jobId], ["state", "queued"], ["state", "blocked"], ["limit", "1"]])); + expect(filtered.items.map(run => run.id)).toEqual([f.runId]); + expect((await service.listRuns(new URLSearchParams([["jobId", jobId], ["state", "queued"], ["state", "blocked"], ["limit", "1"], ["cursor", filtered.nextCursor!]]))).items.map(run => run.id)).toEqual([blockedId]); + + const explicit = await service.listRuns(new URLSearchParams({ jobId, sort: "created", direction: "desc", limit: "1" })); + expect(explicit.items[0].id).toBe(blockedId); + + await f.db.pool.query("UPDATE app.runs SET state='failed' WHERE tenant_id=$1 AND id=$2", [f.tenantId, startingId]); + await f.db.pool.query("UPDATE app.job_runs SET state='failed' WHERE tenant_id=$1 AND id=$2", [f.tenantId, startingId]); + const afterTransition = await service.listRuns(new URLSearchParams({ jobId, limit: "5" })); + expect(afterTransition.items.at(-1)?.id).toBe(startingId); + } finally { + await f.db.pool.query("DELETE FROM app.runs WHERE tenant_id=$1 AND id=ANY($2::uuid[])", [f.tenantId, insertedIds]); + await f.db.pool.query("DELETE FROM app.job_runs WHERE tenant_id=$1 AND id=ANY($2::uuid[])", [f.tenantId, insertedIds]); + await f.db.pool.query("DELETE FROM app.invocations WHERE tenant_id=$1 AND id=ANY($2::uuid[])", [f.tenantId, invocationIds]); + for (const row of originals) { + await f.db.pool.query("UPDATE app.runs SET state=$3,created_at=$4 WHERE tenant_id=$1 AND id=$2", [f.tenantId, row.id, row.state, row.created_at]); + await f.db.pool.query("UPDATE app.job_runs SET state=$3,created_at=$4 WHERE tenant_id=$1 AND id=$2", [f.tenantId, row.id, row.state, row.created_at]); + } + } + }); }); diff --git a/packages/app/src/features/runs/detail.tsx b/packages/app/src/features/runs/detail.tsx index 8a17fa9c..061f9c57 100644 --- a/packages/app/src/features/runs/detail.tsx +++ b/packages/app/src/features/runs/detail.tsx @@ -28,7 +28,7 @@ export function RunDetail() { const tabPath = (name: "trace" | "info"): "/job-runs/$runId" | "/job-runs/$runId/info" => name === "trace" ? "/job-runs/$runId" : "/job-runs/$runId/info"; const status = useQuery(runStatusQuery(runId!)); const job = useQuery({ ...jobQuery(status.data?.job_id ?? ""), enabled: !!status.data?.job_id }); - const jobRuns = useQuery({ ...runPageQuery({ jobId: status.data?.job_id, limit: 30, sort: "created", direction: "desc" }), enabled: !!status.data?.job_id }); + const jobRuns = useQuery({ ...runPageQuery({ jobId: status.data?.job_id, limit: 30 }), enabled: !!status.data?.job_id }); const [revision, setRevision] = useState(""); const [renaming, setRenaming] = useState(false), [nameDraft, setNameDraft] = useState(""), [nameExpected, setNameExpected] = useState(""), [nameError, setNameError] = useState(""); const active = !status.data || !["succeeded", "failed", "stopped"].includes(status.data.state) || status.data.finalizing; diff --git a/packages/app/src/features/runs/history.tsx b/packages/app/src/features/runs/history.tsx index 2ce13f6f..249f2a7b 100644 --- a/packages/app/src/features/runs/history.tsx +++ b/packages/app/src/features/runs/history.tsx @@ -22,7 +22,7 @@ export function RunHistory({ jobId }: { jobId: string }) { const clearStatuses = () => void navigate({ to: "/jobs/$jobId", params: { jobId }, search: { ...search, states: undefined, sort: undefined, direction: undefined, cursor: undefined, previous: undefined } }); return
{runs.isPending &&

Loading run history…

}{runs.error &&

{runs.error.message}

} - {runs.data && <> + {runs.data && <>
Job runs{search.sort ? "" : ", newest first"}
{columns.slice(1, 2).map(([column, label]) => sortColumn(column)} />)}{columns.slice(2).map(([column, label]) => sortColumn(column)} />)}{runs.data.items.map(run => diff --git a/packages/app/src/features/runs/list.tsx b/packages/app/src/features/runs/list.tsx index 2145965b..f8e9cc9c 100644 --- a/packages/app/src/features/runs/list.tsx +++ b/packages/app/src/features/runs/list.tsx @@ -29,5 +29,5 @@ export function RunList({ jobId, projectId, limit = 30 }: { jobId?: string; proj const pagination = jobId ? : projectId ? : ; const projectOptions = (projects.data ?? []).map(project => ({ id: project.id, label: project.name })), jobOptions = (jobs.data?.items ?? []).map(job => ({ id: job.id, label: job.name })); const emptyMessage = search.states?.length && !search.projects?.length && !search.jobs?.length ? "No runs match the selected statuses." : "No runs match the selected filters."; - return
{runs.isPending &&

Loading runs…

}{runs.error &&

{runs.error.message}

}{runs.data && <>
Job runs{search.sort ? "" : ", queued and starting first, running second, then other states; newest first within each group"}
Elapsed
{!projectId && }{statusHeader}{!projectId && (!scoped ? changeSelection("projects", id, checked)} onClear={() => clearFilters("projects")} /> : )}{!jobId ? changeSelection("jobs", id, checked)} onClear={() => clearFilters("jobs")} /> : }{sortableHeader("run", "Run")}{sortableHeader("created", "Created")}{runs.data.items.map(run => {!projectId && })}{runs.data.items.length === 0 && }
Job runs{search.sort ? "" : ", newest first"}
ProjectJobElapsed
{run.project_id && run.project_name ?
{!scoped&& changeSelection("projects", run.project_id!, !(search.projects ?? []).includes(run.project_id!))}/>}{run.project_name}
: —}
{!scoped&& changeSelection("jobs", run.job_id, !(search.jobs ?? []).includes(run.job_id))}/>}{run.job_name}
{run.run_name || "Run"}{(run.failure?.reason || (run.agent_error as any)?.reason) &&

{run.failure?.reason || (run.agent_error as any).reason}

}
{run.elapsed_time ? formatElapsedTime(run.elapsed_time) : "—"}
{search.states?.length || search.projects?.length || search.jobs?.length ? <>

{emptyMessage}

: jobId || projectId ? "No runs found." : "No runs yet"}
}{pagination}
; + return
{runs.isPending &&

Loading runs…

}{runs.error &&

{runs.error.message}

}{runs.data && <>{!projectId && }{statusHeader}{!projectId && (!scoped ? changeSelection("projects", id, checked)} onClear={() => clearFilters("projects")} /> : )}{!jobId ? changeSelection("jobs", id, checked)} onClear={() => clearFilters("jobs")} /> : }{sortableHeader("run", "Run")}{sortableHeader("created", "Created")}{runs.data.items.map(run => {!projectId && })}{runs.data.items.length === 0 && }
Job runs{search.sort ? "" : ", queued and starting first, running second, then other states; newest first within each group"}
ProjectJobElapsed
{run.project_id && run.project_name ?
{!scoped&& changeSelection("projects", run.project_id!, !(search.projects ?? []).includes(run.project_id!))}/>}{run.project_name}
: —}
{!scoped&& changeSelection("jobs", run.job_id, !(search.jobs ?? []).includes(run.job_id))}/>}{run.job_name}
{run.run_name || "Run"}{(run.failure?.reason || (run.agent_error as any)?.reason) &&

{run.failure?.reason || (run.agent_error as any).reason}

}
{run.elapsed_time ? formatElapsedTime(run.elapsed_time) : "—"}
{search.states?.length || search.projects?.length || search.jobs?.length ? <>

{emptyMessage}

: jobId || projectId ? "No runs found." : "No runs yet"}
}{pagination}
; } diff --git a/packages/docs/openapi.yaml b/packages/docs/openapi.yaml index 56c7a6b1..62e4f652 100644 --- a/packages/docs/openapi.yaml +++ b/packages/docs/openapi.yaml @@ -11874,7 +11874,7 @@ paths: get: 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. + 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.