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
8 changes: 8 additions & 0 deletions packages/api/migrations/0031_job_run_history_indexes.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
CREATE INDEX job_runs_by_job_history
ON app.job_runs (tenant_id,job_id,created_at DESC,id DESC,state);

CREATE INDEX job_runs_active_by_job
ON app.job_runs (tenant_id,job_id)
WHERE state IN ('reserved','starting','running','blocked','stopping');

INSERT INTO app.schema_migrations(version) VALUES ('0031_job_run_history_indexes') ON CONFLICT DO NOTHING;
21 changes: 12 additions & 9 deletions packages/api/src/flow-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,15 +115,18 @@ export class ApiService {
private async jobStatistics(ids: string[]) {
if (!ids.length) return new Map<string, { running_count: string; last_run_state: string | null }>();
const result = await databaseFor(this.env).pool.query<{ job_id: string; running_count: string; last_run_state: string | null }>(`
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 ('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
)
SELECT c.job_id,c.running_count,l.state last_run_state FROM counts c JOIN latest l USING (job_id)`, [this.auth.tenantId, ids]);
SELECT selected.job_id,active.running_count,latest.state last_run_state
FROM unnest($2::uuid[]) selected(job_id)
CROSS JOIN LATERAL (
SELECT count(*)::text running_count FROM app.job_runs r
WHERE r.tenant_id=$1 AND r.job_id=selected.job_id
AND r.state IN ('reserved','starting','running','blocked','stopping')
) active
LEFT JOIN LATERAL (
SELECT r.state FROM app.job_runs r
WHERE r.tenant_id=$1 AND r.job_id=selected.job_id
ORDER BY r.created_at DESC,r.id DESC LIMIT 1
) latest ON true`, [this.auth.tenantId, ids]);
return new Map(result.rows.map(row => [row.job_id, row]));
}

Expand Down
14 changes: 9 additions & 5 deletions packages/api/src/postgres/job-summary-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,15 @@ export class JobSummaryRepository {
ORDER BY ${sort === "updated" ? "updated_at DESC,id DESC" : "id DESC"} LIMIT $6
)
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 ('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`}
${selector ? "LEFT JOIN LATERAL (SELECT '0'::text running_count,NULL::text last_run_state) s ON true" : `LEFT JOIN LATERAL (
SELECT
(SELECT count(*)::text FROM app.job_runs active
WHERE active.tenant_id=$1 AND active.job_id=p.id
AND active.state IN ('reserved','starting','running','blocked','stopping')) running_count,
(SELECT latest.state FROM app.job_runs latest
WHERE latest.tenant_id=$1 AND latest.job_id=p.id
ORDER BY latest.created_at DESC,latest.id DESC LIMIT 1) last_run_state
) s ON true`}
ORDER BY ${sort === "updated" ? "p.updated_at DESC,p.id DESC" : "p.id DESC"}`, [this.tenantId, input.cursor ?? null, input.q, input.enabled === undefined ? null : input.enabled === "true", input.projectId ?? null, input.limit + 1, sort]);
const rows = result.rows.slice(0, input.limit);
return {
Expand Down
48 changes: 27 additions & 21 deletions packages/api/src/postgres/run-query-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,27 +34,33 @@ export class RunQueryRepository {
}
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 result = await this.database.pool.query<any>(`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,
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,
CASE WHEN r.state IN ('succeeded','failed','stopped') AND jr.started_at IS NOT NULL AND jr.updated_at >= jr.started_at
THEN json_build_object('duration', round(EXTRACT(EPOCH FROM (jr.updated_at - jr.started_at))))
WHEN r.state NOT IN ('succeeded','failed','stopped') THEN e.elapsed_time
END elapsed_time
FROM app.runs r JOIN app.jobs j ON j.tenant_id=r.tenant_id AND j.id=r.job_id JOIN app.projects p ON p.tenant_id=j.tenant_id AND p.id=j.project_id JOIN app.job_runs jr ON jr.tenant_id=r.tenant_id AND jr.id=r.id JOIN app.invocations i ON i.tenant_id=r.tenant_id AND i.id=r.invocation_id
LEFT JOIN LATERAL (
WITH durations AS (
SELECT EXTRACT(EPOCH FROM (completed.updated_at - completed.started_at)) duration
FROM app.job_runs completed
WHERE completed.tenant_id=r.tenant_id AND completed.job_id=r.job_id AND completed.state IN ('succeeded','failed','stopped')
AND completed.started_at IS NOT NULL AND completed.updated_at >= completed.started_at
)
SELECT CASE WHEN count(durations.duration) = 0 THEN NULL ELSE json_build_object(
'low', round(min(durations.duration)),
'high', round(max(durations.duration))
) END elapsed_time FROM durations
) e ON true
WHERE ${clauses.join(" AND ")} ORDER BY ${order} LIMIT $${values.length}`, values);
const selectedOrder = order.replaceAll("r.", "selected.").replaceAll("j.name", "selected.job_name");
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,
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
FROM app.runs r JOIN app.jobs j ON j.tenant_id=r.tenant_id AND j.id=r.job_id JOIN app.projects p ON p.tenant_id=j.tenant_id AND p.id=j.project_id JOIN app.job_runs jr ON jr.tenant_id=r.tenant_id AND jr.id=r.id JOIN app.invocations i ON i.tenant_id=r.tenant_id AND i.id=r.invocation_id
WHERE ${clauses.join(" AND ")} ORDER BY ${order} LIMIT $${values.length}
), page AS MATERIALIZED (
SELECT id,job_id,state,started_at,job_run_updated_at FROM selected ORDER BY ${selectedOrder} LIMIT ($${values.length} - 1)
), duration_jobs AS MATERIALIZED (
SELECT DISTINCT job_id FROM page WHERE state NOT IN ('succeeded','failed','stopped')
), duration_ranges AS (
SELECT completed.job_id,json_build_object('low',round(min(EXTRACT(EPOCH FROM (completed.updated_at-completed.started_at)))),
'high',round(max(EXTRACT(EPOCH FROM (completed.updated_at-completed.started_at)))) ) elapsed_time
FROM app.job_runs completed JOIN duration_jobs ON duration_jobs.job_id=completed.job_id
WHERE completed.tenant_id=$1 AND completed.state IN ('succeeded','failed','stopped')
AND completed.started_at IS NOT NULL AND completed.updated_at>=completed.started_at
GROUP BY completed.job_id
)
SELECT selected.id,selected.job_id,selected.project_id,selected.job_name,selected.project_name,selected.issue_id,selected.issue_url,selected.issue_title,selected.run_name,selected.agent_name,selected.workspace_name,selected.agent_kind,selected.execution_type,selected.state,selected.failure_source,selected.agent_error,
selected.provider,selected.backend_kind,selected.capabilities,selected.destination_url,selected.artifact_state,selected.artifact_error,selected.created_at,selected.updated_at,selected.started_at,
CASE WHEN selected.state IN ('succeeded','failed','stopped') AND selected.started_at IS NOT NULL AND selected.job_run_updated_at>=selected.started_at
THEN json_build_object('duration',round(EXTRACT(EPOCH FROM (selected.job_run_updated_at-selected.started_at))))
WHEN selected.state NOT IN ('succeeded','failed','stopped') AND page.id IS NOT NULL THEN duration_ranges.elapsed_time
END elapsed_time
FROM selected LEFT JOIN page ON page.id=selected.id LEFT JOIN duration_ranges ON duration_ranges.job_id=selected.job_id
ORDER BY ${selectedOrder}`, values);
const rows = result.rows.slice(0, limit), hasMore = result.rows.length > limit;
const last = rows.at(-1);
const nextCursor = hasMore && last ? sort ? (() => {
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 @@ -69,7 +69,7 @@ export const invocations = app.table("invocations", {
export const manualInvocationPermissions = app.table("manual_invocation_permissions", { tenantId: uuid("tenant_id").notNull(), sourceJobId: uuid("source_job_id").notNull(), destinationJobId: uuid("destination_job_id").notNull(), createdAt: createdAt() }, t => [primaryKey({ columns: [t.tenantId, t.sourceJobId, t.destinationJobId] }), foreignKey({ columns: [t.tenantId, t.sourceJobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), foreignKey({ columns: [t.tenantId, t.destinationJobId], foreignColumns: [jobs.tenantId, jobs.id] }).onDelete("cascade"), index("manual_invocation_permissions_destination").on(t.tenantId, t.destinationJobId)]);
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").$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'`)]);
}, 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'`), index("job_runs_by_job_history").on(t.tenantId, t.jobId, t.createdAt.desc(), t.id.desc(), t.state), index("job_runs_active_by_job").on(t.tenantId, t.jobId).where(sql`${t.state} in ('reserved','starting','running','blocked','stopping')`)]);

export const runs = app.table("runs", {
executionConfig: jsonb("execution_config").$type<ExecutionConfig>().notNull(),
Expand Down
6 changes: 3 additions & 3 deletions packages/api/test/job-lifecycle.postgres.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("job lifecycle delivery (Po
await complete(a, other, "succeeded");
await Promise.all([deliver(), deliver()]);
expect(await invocations(a, target.id)).toHaveLength(2);
});
}, 10_000);

it("does not create lifecycle work from unrelated prompt edits or re-enabling", async () => {
const a = await tenant(), source = await job(a);
Expand Down Expand Up @@ -303,7 +303,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("job lifecycle delivery (Po
await runs.terminal(downstreamRun!, "succeeded", "stored", undefined, true);
await deliverIdle();
expect(await invocations(a, idle.id)).toHaveLength(1);
}, 20_000);
}, 120_000);

it("acknowledges a queue-full lifecycle delivery and lets idle proceed after existing work ends", async () => {
const a = await tenant(), source = await job(a), downstream = await job(a, { sourceJobIds: [source.id], states: ["succeeded"] });
Expand Down Expand Up @@ -341,7 +341,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("job lifecycle delivery (Po
expect(await invocations(a, target.id)).toHaveLength(2);
expect(await invocations(a, legacy.id)).toHaveLength(1);
expect(await deliveries()).toHaveLength(3);
});
}, 10_000);

it("excludes absent IDs, excluded states, disabled or removed subscribers, and other tenants", async () => {
const a = await tenant(), b = await tenant(), source = await job(a);
Expand Down
23 changes: 22 additions & 1 deletion packages/api/test/loading.postgres.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { loadingFixture } from "./helpers/loading-fixture";
import { Database } from "../src/postgres/database";
import { IdentityRepository } from "../src/postgres/identity-repository";
import { PostgresJobRepository } from "../src/postgres/job-repository";
import { JobSummaryRepository } from "../src/postgres/job-summary-repository";
import { ConnectionRepository } from "../src/postgres/connection-repository";
import { ApiService } from "../src/flow-service";
import worker from "../src/worker";
Expand All @@ -16,7 +17,7 @@ describe.skipIf(!url)("request loading with PostgreSQL", () => {
let fixture: Awaited<ReturnType<typeof loadingFixture>>;
let db: Database, env: Env, auth: OAuthProps, cookie: string, jobIds: string[], runId: string, tenantId: string, userId: string, otherTenant: string;
let request: Awaited<ReturnType<typeof loadingFixture>>["request"];
beforeAll(async () => { fixture = await loadingFixture(url!); ({ db, env, auth, cookie, jobIds, runId, tenantId, userId, otherTenant, request } = fixture); });
beforeAll(async () => { fixture = await loadingFixture(url!); ({ db, env, auth, cookie, jobIds, runId, tenantId, userId, otherTenant, request } = fixture); }, 30_000);
afterAll(async () => fixture?.cleanup());

it("lists ten jobs in three data queries, preserving decrypted prompts, trigger order and statistics", async () => {
Expand All @@ -29,6 +30,26 @@ describe.skipIf(!url)("request loading with PostgreSQL", () => {
expect(query).toHaveBeenCalledTimes(4); // membership + jobs + triggers + statistics
} finally { query.mockRestore(); }
});
it("counts only active runs and keeps latest-state ties tenant qualified", async () => {
const triggerId = (await db.pool.query("SELECT id FROM app.triggers WHERE tenant_id=$1 AND job_id=$2 AND kind='manual'", [tenantId, jobIds[0]])).rows[0].id;
const otherTriggerId = (await db.pool.query("SELECT id FROM app.triggers WHERE tenant_id=$1 AND job_id=$2 AND kind='manual'", [otherTenant, jobIds[0]])).rows[0].id;
const states = ["reserved", "starting", "blocked", "stopping", "queued", "succeeded", "failed"];
for (const [i, state] of states.entries()) {
const invocationId = crypto.randomUUID(), id = `20000000-0000-4000-8000-${String(i + 1).padStart(12, "0")}`;
await 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,'{}')", [tenantId, invocationId, jobIds[0], `summary-test-${i}`, triggerId]);
await 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,'test',$6)", [tenantId, id, jobIds[0], invocationId, state, i >= 5 ? "2100-01-01T00:00:00Z" : `2099-01-01T00:00:0${i}Z`]);
}
const otherInvocation = crypto.randomUUID();
await db.pool.query("INSERT INTO app.invocations(tenant_id,id,job_id,source,claim_key,trigger_id,context) VALUES ($1,$2,$3,'manual','summary-other-tenant',$4,'{}')", [otherTenant, otherInvocation, jobIds[0], otherTriggerId]);
await 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,'running','test','2101-01-01T00:00:00Z')", [otherTenant, crypto.randomUUID(), jobIds[0], otherInvocation]);

const jobs = await new ApiService(env, auth).listJobs();
expect(jobs.find(job => job.id === jobIds[0])).toMatchObject({ runningCount: 5, lastRunState: "failed" });
expect(jobs.find(job => job.id === jobIds[1])).toMatchObject({ runningCount: 0, lastRunState: null });
const summaries = (await new JobSummaryRepository(db, tenantId).page({ limit: 100, q: "" })).items;
expect(summaries.find(job => job.id === jobIds[0])).toMatchObject({ runningCount: 5, lastRunState: "failed" });
expect(summaries.find(job => job.id === jobIds[1])).toMatchObject({ runningCount: 0, lastRunState: null });
});
it("does not load another tenant's jobs", async () => {
const query = vi.spyOn(db.pool, "query");
try {
Expand Down
2 changes: 1 addition & 1 deletion packages/api/test/oauth-onboarding.postgres.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP onboarding public boun
const reset = await call("/api/v1/auth/password-reset/complete", { token: token(), password: "replacement long password" }, d.cookie);
expect(reset.status).toBe(200); const body = await reset.json() as any; expect(body.returnTo).toContain(`connection=${d.connection}`);
expect((await consent(body.returnTo, d.cookie + "; " + cookieOf(reset))).response.status).toBe(200);
});
}, 10_000);
it("rejects forged/expired connections and revoked verification without extending the client request", async () => {
mail(); for (const returnTo of ["https://evil.test", "//evil.test", destination("bad").replace("127.0.0.1", "evil.test"), destination("bad").replace("S256", "plain")]) expect((await call("/api/v1/auth/connections", { returnTo })).status).toBe(400);
const a = await start("expired"), account = email();
Expand Down
Loading
Loading