diff --git a/server/src/services/heartbeat/__tests__/run-control-fixtures.ts b/server/src/services/heartbeat/__tests__/run-control-fixtures.ts index 2adce9077c1..06ed71c35d1 100644 --- a/server/src/services/heartbeat/__tests__/run-control-fixtures.ts +++ b/server/src/services/heartbeat/__tests__/run-control-fixtures.ts @@ -1,8 +1,9 @@ import type { Db } from "@paperclipai/db"; -import { agents, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns } from "@paperclipai/db"; +import { agents, companies, createDb, applyPendingMigrations, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns } from "@paperclipai/db"; import { sql } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, beforeEach, vi, type Mock } from "vitest"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js"; +import { resolveExternalTestDatabaseUrl } from "../../../__tests__/helpers/external-test-database.js"; import { runningProcesses } from "../../../adapters/index.js"; import { terminateLocalService } from "../../local-service-supervisor.js"; import { createHeartbeatRunState } from "../run-state.js"; @@ -65,15 +66,17 @@ export function callbacks(db: Db): TestCallbacks { failedProcessRunCancellations: new Map; failed: boolean; error?: unknown }>(), } satisfies HeartbeatRunControlDependencies; } -export const runControlPostgresSupport = await getEmbeddedPostgresTestSupport(); +const externalTestDatabaseUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_RUN_CONTROL_TEST_DATABASE_URL"); +export const runControlPostgresSupport = externalTestDatabaseUrl ? { supported: true, reason: undefined } : await getEmbeddedPostgresTestSupport(); if (!runControlPostgresSupport.supported) console.warn(`Skipping run-control database tests: ${runControlPostgresSupport.reason}`); export function setupRunControlDatabase(name: string, ready: (db: Db) => void) { let database: Awaited>; let db: Db; beforeAll(async () => { - database = await startEmbeddedPostgresTestDatabase(name); - db = createDb(database.connectionString); + if (externalTestDatabaseUrl) await applyPendingMigrations(externalTestDatabaseUrl); + else database = await startEmbeddedPostgresTestDatabase(name); + db = createDb(externalTestDatabaseUrl ?? database!.connectionString); ready(db); }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); afterAll(async () => { diff --git a/server/src/services/heartbeat/run-control.test.ts b/server/src/services/heartbeat/run-control.test.ts index ab0a9fbb5a8..8497958a8be 100644 --- a/server/src/services/heartbeat/run-control.test.ts +++ b/server/src/services/heartbeat/run-control.test.ts @@ -1,7 +1,7 @@ import { randomUUID } from "node:crypto"; import type { Db } from "@paperclipai/db"; import { activityLog, agents, agentWakeupRequests, caseEvents, caseHandoffs, cases, companies, environmentLeases, heartbeatRuns, issueComments, issues, nativeRunFinalizations } from "@paperclipai/db"; -import { eq, inArray } from "drizzle-orm"; +import { eq, inArray, sql } from "drizzle-orm"; import { afterEach, describe, expect, it, vi } from "vitest"; import { runningProcesses } from "../../adapters/index.js"; import { @@ -173,6 +173,79 @@ describe.skipIf(!runControlPostgresSupport.supported)("heartbeat run-control dat )).toMatchObject({ status: "cancelled" }); }); + it.each([["40P01", 3], ["XX000", 1]] as const)("bounds cancellation transaction attempts for PostgreSQL %s", async (code, attempts) => { + const { company, agent } = await fixture(); + const run = await liveRun(company.id, agent.id); + const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Cancellation failure", status: "in_progress", + assigneeAgentId: agent.id, executionRunId: run.id }).returning(); + await db.update(heartbeatRuns).set({ issueId: issue.id, contextSnapshot: { issueId: issue.id } }).where(eq(heartbeatRuns.id, run.id)); + await db.execute(sql`create sequence run_control_cancel_attempts`); + await db.execute(sql.raw(`create function run_control_cancel_fault() returns trigger language plpgsql as $$ + begin + if new.result_json->'executionCancellation'->>'state' = 'requested' then + perform nextval('run_control_cancel_attempts'); + raise exception using errcode = '${code}', message = 'Synthetic cancellation transaction failure'; + end if; + return new; + end $$`)); + await db.execute(sql`create trigger run_control_cancel_fault before update on heartbeat_runs + for each row execute function run_control_cancel_fault()`); + const deps = callbacks(db); + try { + await expect(createHeartbeatRunControl(db, deps).cancelRunInternal(run.id, "Operator Stop", { + resultJson: { cancelledByActorType: "user", cancelledByUserId: "operator" }, + })).rejects.toMatchObject({ cause: { code } }); + const [counter] = await db.execute<{ count: number }>(sql`select last_value::int as count from run_control_cancel_attempts`); + expect(counter.count).toBe(attempts); + expect(await deps.getRun(run.id)).toMatchObject({ status: "running", resultJson: null }); + expect(terminateLocalService).not.toHaveBeenCalled(); + expect(deps.appendRunEvent).not.toHaveBeenCalled(); + } finally { + await db.execute(sql`drop trigger run_control_cancel_fault on heartbeat_runs`); + await db.execute(sql`drop function run_control_cancel_fault()`); + await db.execute(sql`drop sequence run_control_cancel_attempts`); + } + }); + + it("finishes operator Stop after a concurrent run writer causes a transaction deadlock", async () => { + const { company, agent } = await fixture(); + const run = await liveRun(company.id, agent.id); + const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Stop contention", status: "in_progress", + assigneeAgentId: agent.id, executionRunId: run.id, checkoutRunId: run.id }).returning(); + await db.update(heartbeatRuns).set({ issueId: issue.id, contextSnapshot: { issueId: issue.id } }).where(eq(heartbeatRuns.id, run.id)); + let enter!: () => void, release!: () => void; + const entered = new Promise(resolve => { enter = resolve; }); + const released = new Promise(resolve => { release = resolve; }); + let blockerPid = 0; + const writer = db.transaction(async tx => { + // Make Stop's default detector see the cycle first, so this reproduces + // the API-side victim observed in CI rather than a random victim. + await tx.execute(sql`set local deadlock_timeout = '10s'`); + const [backend] = await tx.execute<{ pid: number }>(sql`select pg_backend_pid() as pid`); + blockerPid = backend.pid; + await tx.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)).for("update"); + enter(); await released; + await tx.update(issues).set({ updatedAt: new Date() }).where(eq(issues.id, issue.id)); + }); + await entered; + const deps = callbacks(db); + const stopping = createHeartbeatRunControl(db, deps).cancelRunInternal(run.id, "Operator Stop", { + resultJson: { cancelledByActorType: "user", cancelledByUserId: "operator" }, + }).then(value => ({ value, error: undefined }), error => ({ value: undefined, error })); + try { + await vi.waitFor(async () => { + const waiting = await db.execute(sql`select pid from pg_stat_activity + where ${blockerPid} = any(pg_blocking_pids(pid)) and wait_event_type = 'Lock'`); + expect(waiting.length).toBeGreaterThan(0); + }, { timeout: 5000 }); + } finally { release(); } + await writer; + const result = await stopping; + expect(result.error).toBeUndefined(); + expect(result.value).toMatchObject({ status: "cancelled" }); + expect(await deps.getRun(run.id)).toMatchObject({ status: "cancelled" }); + }); + it.each(["queued", "running"] as const)("preserves case intent when a guarded Stop loses to %s promotion", async status => { const { company, agent } = await fixture(); const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Promoted case work", status: "todo", assigneeAgentId: agent.id }).returning(); diff --git a/server/src/services/heartbeat/run-control.ts b/server/src/services/heartbeat/run-control.ts index 2ce3cf3c363..7970e09c740 100644 --- a/server/src/services/heartbeat/run-control.ts +++ b/server/src/services/heartbeat/run-control.ts @@ -1134,7 +1134,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont let caseHandoffRetryClaimed = false; if (handoffIssueId && supersedesCaseHandoff && options.resultJson?.caseHandoffYieldStop !== true) { const publications: ActivityPublication[] = []; - const supersessionApplied = await db.transaction(async tx => { + const applySupersession = () => db.transaction(async tx => { const [issue] = await tx.select({ id: issues.id, executionRunId: issues.executionRunId, checkoutRunId: issues.checkoutRunId, assigneeAgentId: issues.assigneeAgentId, assigneeUserId: issues.assigneeUserId }).from(issues) .where(and(eq(issues.companyId, run!.companyId), eq(issues.id, handoffIssueId))).for("update"); @@ -1189,7 +1189,27 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont await cancelCaseHandoffsForIssue(tx as unknown as Db, { companyId: run!.companyId, issueId: handoffIssueId, sourceRunId: runId, includeUnboundTerminalIntent: Boolean(fenced && ownsTask), reason, publications }); return true; - }).catch(rethrowNativeCancellationLockConflict); + }); + let supersessionApplied = false; + for (let attempt = 0; ; attempt++) { + const previousRun = run; + try { + supersessionApplied = await applySupersession(); + break; + } catch (error) { + const value = parseObject(error); + const deadlock = value.code === "40P01" || parseObject(value.cause).code === "40P01"; + if (!deadlock || attempt >= 2) rethrowNativeCancellationLockConflict(error); + // PostgreSQL aborted the entire transaction. Discard its local + // receipts before re-reading current authority under fresh locks. + // Provider Stop and publication happen only after this boundary. + run = previousRun; + cancellationClaimed = false; + caseHandoffRetryClaimed = false; + publications.length = 0; + await new Promise(resolve => setTimeout(resolve, 25 * (attempt + 1))); + } + } publications.forEach(publishActivity); if (!supersessionApplied) return null; }