import { randomUUID } from "node:crypto"; import { and, eq, sql } from "drizzle-orm"; import { agents, authUsers, agentWakeupRequests, closeLivenessDb, companies, createDb, environmentLeases, environments, heartbeatRunEvents, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, nativeRunnerCheckpoints, } from "@paperclipai/db"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; import { heartbeatService } from "../heartbeat.js"; import { hasPendingRunCleanup } from "../execution-blocker.js"; import { remoteTerminationReceipt } from "../remote-execution-termination.js"; import { acknowledgeNativeStartupCleanup, NATIVE_STARTUP_CLEANUP_PENDING } from "./native-startup-cleanup.js"; import { findNativeSessionResumeRun } from "./native-session-resume.js"; import { NATIVE_STARTUP_TIMEOUT_CANCELLATION_REASON, prepareNativeStartupRequeue } from "./native-startup-requeue.js"; const support = await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = support.supported ? describe : describe.skip; if (!support.supported) console.warn(`Skipping native startup requeue tests: ${support.reason ?? "unsupported environment"}`); type SeedOptions = { terminal?: boolean; reused?: boolean; checkpoint?: boolean }; describeEmbeddedPostgres("requeue of a startup that timed out", () => { let db!: ReturnType; let stopDatabase: (() => Promise) | undefined; let companyId!: string; let agentId!: string; let environmentId!: string; let userId!: string; beforeAll(async () => { const started = await startEmbeddedPostgresTestDatabase("paperclip-native-startup-requeue-"); stopDatabase = started.cleanup; db = createDb(started.connectionString); }, 120_000); beforeEach(async () => { companyId = randomUUID(); agentId = randomUUID(); environmentId = randomUUID(); userId = randomUUID(); await db.insert(authUsers).values({ id: userId, name: "Task owner", email: `${userId}@example.invalid`, createdAt: new Date(), updatedAt: new Date() }); await db.insert(companies).values({ id: companyId, name: "Startup", issuePrefix: `S${companyId.slice(0, 5).toUpperCase()}`, requireBoardApprovalForNewAgents: false }); await db.insert(agents).values({ id: agentId, companyId, name: "Runner", role: "engineer", status: "active", adapterType: "paperclip_runner", adapterConfig: { provider: "codex" }, runtimeConfig: {}, permissions: {} }); await db.insert(environments).values({ id: environmentId, name: environmentId, driver: "plugin", config: {} }); }); afterAll(async () => { if (db) await closeLivenessDb(db, 1).catch(() => undefined); await db?.$client.end({ timeout: 1 }); await stopDatabase?.(); }); const cancellation = () => ({ reason: NATIVE_STARTUP_TIMEOUT_CANCELLATION_REASON, source: "control_plane", expected: false, initiator: { id: null, type: "system" }, recordedAt: new Date().toISOString() }); async function insertLease(input: { issueId: string; runId: string; providerLeaseId: string; metadata?: Record }) { const lease = { id: randomUUID(), companyId, environmentId, issueId: input.issueId, heartbeatRunId: input.runId, provider: "plugin", providerLeaseId: input.providerLeaseId }; await db.insert(environmentLeases).values({ ...lease, status: "released", releasedAt: new Date(), cleanupStatus: "success", metadata: { runnerTaskLease: true, runnerTaskExecutionStopped: true, ...input.metadata, remoteExecutionTermination: remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: "stopped" }) } }); return lease.id; } async function seed(options: SeedOptions = {}) { const issueId = randomUUID(), runId = randomUUID(), priorRunId = randomUUID(), wakeupRequestId = randomUUID(); const leaseOwner = randomUUID(), taskId = `task-${runId}`, interactionId = randomUUID(), nativeSessionId = randomUUID(); await db.insert(issues).values({ id: issueId, companyId, identifier: `ST-${runId.slice(0, 8)}`, title: "Startup", status: "in_progress", priority: "medium", workMode: "standard", assigneeAgentId: agentId }); await db.insert(agentWakeupRequests).values({ id: wakeupRequestId, companyId, agentId, source: "automation", reason: "issue_interaction_resolved", status: "claimed", payload: { issueId } }); const scope = { companyId, agentId, runtimeMode: "native" as const, scopeKind: "issue" as const, issueId, nativeIssueId: issueId, nativeSessionId, responsibleUserId: userId, invocationSource: "automation" as const, triggerDetail: "system" }; const source = { backendKind: "runnerd", driverKind: "codex", sessionId: nativeSessionId, providerSessionId: "thread" }; if (options.reused) await db.insert(heartbeatRuns).values({ ...scope, id: priorRunId, status: "succeeded", createdAt: new Date(Date.now() - 60_000), runnerProfileJson: { sessionCheckpoint: { ...source, cursor: "7", identity: { runId: priorRunId, sessionId: nativeSessionId } } } }); await db.insert(heartbeatRuns).values({ ...scope, id: runId, status: options.terminal ? "cancelled" : "running", wakeupRequestId, ...(options.terminal ? { errorCode: "cancelled", error: NATIVE_STARTUP_TIMEOUT_CANCELLATION_REASON, finishedAt: new Date() } : { errorCode: NATIVE_STARTUP_CLEANUP_PENDING }), contextSnapshot: { issueId, taskKey: issueId, wakeReason: "issue_interaction_resolved", interactionId, wakeCommentIds: [randomUUID()] }, runnerProfileJson: options.checkpoint === false ? {} : { sessionCheckpoint: { ...source, cursor: null, identity: { runId, sessionId: nativeSessionId } } }, }); const priorLeaseId = options.reused ? await insertLease({ issueId, runId: priorRunId, providerLeaseId: taskId, metadata: { runnerTaskSessionRetained: false } }) : null; const leaseId = await insertLease({ issueId, runId, providerLeaseId: taskId, metadata: options.reused ? { runnerTaskReused: true, runnerTaskSessionRetained: true, runnerTaskPreviousLeaseId: priorLeaseId, runnerTaskIdentity: { runId: priorRunId } } : {} }); const marker = { schema: "paperclip.native-startup-cleanup.v1", companyId, agentId, runId, contextId: randomUUID(), deadlineAtMs: Date.now() - 1_000, leaseOwner, controllerGeneration: 1, attempt: 1, leaseId, taskId, requiresPreparationStop: false, state: "complete", auditId: randomUUID() }; await db.update(heartbeatRuns).set({ resultJson: { nativeStartupCleanup: marker, startupCancellation: { requestedAt: new Date().toISOString() }, ...(options.terminal ? { cancellation: cancellation() } : {}) } }).where(eq(heartbeatRuns.id, runId)); await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId)); await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "terminal_failure", attempt: 1, leaseOwner, leaseExpiresAt: new Date(Date.now() - 1_000), failureCode: NATIVE_STARTUP_CLEANUP_PENDING, recoveryState: "blocked", controllerBootId: randomUUID(), controllerPid: 4242, controllerProcessStartedAt: new Date(), controllerGeneration: 1 }); return { issueId, runId, leaseId, priorLeaseId, priorRunId, interactionId, wakeupRequestId, nativeSessionId }; } type Seeded = Awaited>; async function state(seeded: Seeded) { const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, seeded.runId)); const [issue] = await db.select().from(issues).where(eq(issues.id, seeded.issueId)); const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, seeded.runId)); const [wakeup] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, seeded.wakeupRequestId)); const successors = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.retryOfRunId, seeded.runId))); const recoveries = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, seeded.issueId)); return { run: run!, issue: issue!, coordinator: coordinator!, wakeup: wakeup!, successors, recoveries }; } async function leaseMetadata(id: string) { const [lease] = await db.select({ metadata: environmentLeases.metadata }).from(environmentLeases).where(eq(environmentLeases.id, id)); return lease!.metadata as Record; } it("queues the same wake again and keeps the task open", async () => { const seeded = await seed(); await heartbeatService(db).cancelRun(seeded.runId, NATIVE_STARTUP_TIMEOUT_CANCELLATION_REASON); const after = await state(seeded); expect(after.run).toMatchObject({ status: "cancelled", errorCode: "cancelled", resultJson: { nativeStartupCleanup: { state: "complete", beforeProviderWork: true } } }); expect(after.successors).toHaveLength(1); expect(after.successors[0]).toMatchObject({ status: "scheduled_retry", scheduledRetryReason: "interrupted_preparation", contextSnapshot: { wakeReason: "issue_interaction_resolved", interactionId: seeded.interactionId, wakeCommentIds: (after.run.contextSnapshot as Record).wakeCommentIds } }); expect(after.successors[0]!.contextSnapshot).not.toHaveProperty("forceFreshSession"); expect(after.issue).toMatchObject({ status: "in_progress", executionRunId: after.successors[0]!.id }); expect(after.coordinator).toMatchObject({ leaseOwner: null, failureCode: "native_retry_cancelled" }); expect(after.recoveries).toEqual([]); expect(await hasPendingRunCleanup(db, companyId, seeded.runId)).toBe(false); }); it("leaves the answer of a held message waiting behind the new run", async () => { const seeded = await seed(); const heldId = randomUUID(); await db.insert(agentWakeupRequests).values({ id: heldId, companyId, agentId, source: "automation", reason: "issue_commented", status: "deferred_issue_execution", requestedByActorType: "user", requestedByActorId: userId, payload: { issueId: seeded.issueId } }); await heartbeatService(db).cancelRun(seeded.runId, NATIVE_STARTUP_TIMEOUT_CANCELLATION_REASON); const after = await state(seeded); const [held] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, heldId)); expect(held!.status).toBe("deferred_issue_execution"); expect(after.issue).toMatchObject({ status: "in_progress", executionRunId: after.successors[0]!.id }); expect(after.recoveries).toEqual([]); }); it("queues one run when the cleanup is settled again", async () => { const seeded = await seed(); const heartbeat = heartbeatService(db); await heartbeat.cancelRun(seeded.runId, NATIVE_STARTUP_TIMEOUT_CANCELLATION_REASON); const first = await state(seeded); await heartbeat.cancelRun(seeded.runId, NATIVE_STARTUP_TIMEOUT_CANCELLATION_REASON); const second = await state(seeded); expect(second.successors.map(run => run.id)).toEqual(first.successors.map(run => run.id)); expect(second.issue.executionRunId).toBe(first.successors[0]!.id); expect(second.recoveries).toEqual([]); }); it("finishes the requeue when the server stopped after the cancellation", async () => { const seeded = await seed({ terminal: true }); await heartbeatService(db).cancelRun(seeded.runId, NATIVE_STARTUP_TIMEOUT_CANCELLATION_REASON); const after = await state(seeded); expect(after.successors).toHaveLength(1); expect(after.issue).toMatchObject({ status: "in_progress", executionRunId: after.successors[0]!.id }); expect(after.coordinator).toMatchObject({ leaseOwner: null, failureCode: "native_retry_cancelled" }); expect(after.wakeup.status).toBe("cancelled"); expect(after.recoveries).toEqual([]); }); it("queues one run when the server stopped before the acknowledgement", async () => { const seeded = await seed(); const heartbeat = heartbeatService(db); const [before] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, seeded.runId)); await heartbeat.cancelRun(seeded.runId, NATIVE_STARTUP_TIMEOUT_CANCELLATION_REASON); const first = await state(seeded); await db.update(nativeRunFinalizations).set({ leaseOwner: before!.leaseOwner, failureCode: before!.failureCode }) .where(eq(nativeRunFinalizations.runId, seeded.runId)); await heartbeat.cancelRun(seeded.runId, NATIVE_STARTUP_TIMEOUT_CANCELLATION_REASON); const second = await state(seeded); expect(second.successors.map(run => run.id)).toEqual(first.successors.map(run => run.id)); expect(second.coordinator).toMatchObject({ leaseOwner: null, failureCode: "native_retry_cancelled" }); expect(second.issue).toMatchObject({ status: "in_progress", executionRunId: first.successors[0]!.id }); expect(second.recoveries).toEqual([]); }); it("settles as before when the new run cannot be queued", async () => { const seeded = await seed(); await db.update(heartbeatRuns).set({ responsibleUserId: null }).where(eq(heartbeatRuns.id, seeded.runId)); await heartbeatService(db).cancelRun(seeded.runId, NATIVE_STARTUP_TIMEOUT_CANCELLATION_REASON); const after = await state(seeded); expect(after.successors).toEqual([]); expect(after.run.status).toBe("cancelled"); expect(after.coordinator.leaseOwner).toBeNull(); expect(after.issue.status).toBe("blocked"); expect(after.recoveries).toHaveLength(1); }); const resultPatch = (patch: Record) => (seeded: Seeded) => db.update(heartbeatRuns).set({ resultJson: sql`${heartbeatRuns.resultJson} || ${JSON.stringify(patch)}::jsonb` }).where(eq(heartbeatRuns.id, seeded.runId)); const profilePatch = (patch: Record) => (seeded: Seeded) => db.update(heartbeatRuns).set({ runnerProfileJson: sql`${heartbeatRuns.runnerProfileJson} || ${JSON.stringify(patch)}::jsonb` }).where(eq(heartbeatRuns.id, seeded.runId)); const refusals: Array<[string, (seeded: Seeded) => PromiseLike]> = [ ["a session started", seeded => db.insert(heartbeatRunEvents).values({ companyId, agentId, runId: seeded.runId, seq: 1, eventType: "session.started" })], ["a process start was requested", seeded => db.insert(heartbeatRunEvents).values({ companyId, agentId, runId: seeded.runId, seq: 1, eventType: "adapter.invoke" })], ["the Runner saved a checkpoint", seeded => db.insert(nativeRunnerCheckpoints).values({ companyId, issueId: seeded.issueId, runId: seeded.runId, part: "header", material: {} })], ["the cleanup was already settled", seeded => acknowledgeNativeStartupCleanup(db, { companyId, runId: seeded.runId })], ["a newer controller owns the run", seeded => db.update(nativeRunFinalizations).set({ controllerGeneration: 2 }) .where(eq(nativeRunFinalizations.runId, seeded.runId))], ["a person stopped the run", resultPatch({ cancelledByActorType: "user", cancelledByUserId: "operator" })], ["an agent stopped the run", resultPatch({ cancelledByAgentId: "agent" })], ["a message interrupted the run", resultPatch({ interruptedByActorType: "user" })], ["a pause stopped the run", resultPatch({ pauseStop: { state: "requested" } })], ["the task was reassigned", resultPatch({ reassignmentStopRequested: true })], ["a budget stopped the run", resultPatch({ startupCancellation: { budgetEnforcement: { scopeType: "agent" } } })], ["the recorded reason is different", resultPatch({ cancellation: { ...cancellation(), reason: "Cancelled due to agent pause" } })], ["a person is the recorded source", resultPatch({ cancellation: { ...cancellation(), source: "operator", initiator: { id: "operator", type: "user" } } })], ["no cancellation is recorded", seeded => db.update(heartbeatRuns).set({ resultJson: sql`${heartbeatRuns.resultJson} - 'cancellation'` }).where(eq(heartbeatRuns.id, seeded.runId))], ["the cancellation covers the task", resultPatch({ nativeCancellation: { scope: "task" } })], ["a workspace restore failed", resultPatch({ workspaceRestoreFailure: { state: "failed" } })], ["remote files are not settled", profilePatch({ remoteWorkspace: { path: "/workspace" } })], ["a file copy is not settled", profilePatch({ nativeWorkspaceSync: { state: "pending" } })], ["the cleanup is pending", seeded => db.update(heartbeatRuns).set({ resultJson: sql`jsonb_set(${heartbeatRuns.resultJson}, '{nativeStartupCleanup,state}', '"pending"'::jsonb)` }) .where(eq(heartbeatRuns.id, seeded.runId))], ["the run did not end as cancelled", seeded => db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, seeded.runId))], ["the run has a process", seeded => db.update(heartbeatRuns).set({ processPid: 4242 }).where(eq(heartbeatRuns.id, seeded.runId))], ["the run saved a session", seeded => db.update(heartbeatRuns).set({ sessionIdAfter: "session" }).where(eq(heartbeatRuns.id, seeded.runId))], ["the lease has no stop receipt", seeded => db.update(environmentLeases).set({ metadata: sql`${environmentLeases.metadata} - 'remoteExecutionTermination'` }).where(eq(environmentLeases.id, seeded.leaseId))], ["the lease belongs to a different task", seeded => db.update(environmentLeases).set({ providerLeaseId: "other-task" }) .where(eq(environmentLeases.id, seeded.leaseId))], ]; it.each(refusals)("does not queue a new run when %s", async (_name, change) => { const seeded = await seed({ terminal: true, reused: true }); await change(seeded); const priorLease = await leaseMetadata(seeded.priorLeaseId!); expect(await prepareNativeStartupRequeue(db, { companyId, runId: seeded.runId })).toBeNull(); const after = await state(seeded); expect(after.run.resultJson).not.toHaveProperty("nativeStartupCleanup.beforeProviderWork"); expect(await leaseMetadata(seeded.priorLeaseId!)).toEqual(priorLease); }); it("keeps a person's Stop as that Stop", async () => { const seeded = await seed(); await resultPatch({ cancelledByActorType: "user", cancelledByUserId: userId })(seeded); await heartbeatService(db).cancelRun(seeded.runId, NATIVE_STARTUP_TIMEOUT_CANCELLATION_REASON); const after = await state(seeded); expect(after.run.status).toBe("cancelled"); expect(after.successors).toEqual([]); expect(after.run.resultJson).not.toHaveProperty("nativeStartupCleanup.beforeProviderWork"); }); it("gives the saved session state back to the earlier run, once", async () => { const seeded = await seed({ terminal: true, reused: true }); const scope = { companyId, runId: seeded.runId }; expect(await prepareNativeStartupRequeue(db, scope)).toEqual({ forceFreshSession: false }); expect(await leaseMetadata(seeded.priorLeaseId!)).toMatchObject({ runnerTaskExecutionStopped: true, runnerTaskSessionRetained: true }); expect(await leaseMetadata(seeded.leaseId)).toMatchObject({ runnerTaskSessionRetained: false, runnerTaskSessionReturnedTo: seeded.priorLeaseId }); const returned = [await leaseMetadata(seeded.priorLeaseId!), await leaseMetadata(seeded.leaseId)]; expect(await prepareNativeStartupRequeue(db, scope)).toEqual({ forceFreshSession: false }); expect([await leaseMetadata(seeded.priorLeaseId!), await leaseMetadata(seeded.leaseId)]).toEqual(returned); }); const leasePatch = (patch: Record) => (seeded: Seeded) => db.update(environmentLeases).set({ metadata: sql`${environmentLeases.metadata} || ${JSON.stringify(patch)}::jsonb` }).where(eq(environmentLeases.id, seeded.leaseId)); const freshSessions: Array<[string, (seeded: Seeded) => PromiseLike]> = [ ["this run attached to the task", seeded => leasePatch({ runnerTaskIdentity: { runId: seeded.runId } })(seeded)], ["the session state was not kept", leasePatch({ runnerTaskSessionRetained: false })], ["the earlier lease is not recorded", leasePatch({ runnerTaskPreviousLeaseId: null })], ["a portable task moved", leasePatch({ portableTaskPredecessor: { leaseId: "earlier" } })], ["the earlier lease has a different run", leasePatch({ runnerTaskIdentity: { runId: randomUUID() } })], ["the earlier lease has a different task", seeded => db.update(environmentLeases).set({ providerLeaseId: "other-task" }) .where(eq(environmentLeases.id, seeded.priorLeaseId!))], ]; it.each(freshSessions)("starts a new session when %s", async (_name, change) => { const seeded = await seed({ terminal: true, reused: true }); await change(seeded); const priorLease = await leaseMetadata(seeded.priorLeaseId!); expect(await prepareNativeStartupRequeue(db, { companyId, runId: seeded.runId })).toEqual({ forceFreshSession: true }); expect(await leaseMetadata(seeded.priorLeaseId!)).toEqual(priorLease); }); it("marks the new run when it must start a new session", async () => { const seeded = await seed({ checkpoint: false }); await heartbeatService(db).cancelRun(seeded.runId, NATIVE_STARTUP_TIMEOUT_CANCELLATION_REASON); const after = await state(seeded); expect(after.successors).toHaveLength(1); expect(after.successors[0]).toMatchObject({ sessionIdBefore: null, contextSnapshot: { forceFreshSession: true, interactionId: seeded.interactionId } }); }); it("reports the acknowledgement only once", async () => { const seeded = await seed({ terminal: true }); const scope = { companyId, runId: seeded.runId }; expect(await acknowledgeNativeStartupCleanup(db, scope)).toBe(true); expect(await acknowledgeNativeStartupCleanup(db, scope)).toBe(false); }); const resumeSource = async (seeded: Seeded) => (await findNativeSessionResumeRun(db, { companyId, agentId, issueId: seeded.issueId, normalizedSessionId: seeded.nativeSessionId, beforeCreatedAt: new Date(Date.now() + 1_000) }))?.id; it("resumes the earlier run's session after the requeue", async () => { const seeded = await seed({ reused: true }); await heartbeatService(db).cancelRun(seeded.runId, NATIVE_STARTUP_TIMEOUT_CANCELLATION_REASON); const after = await state(seeded); expect(after.successors).toHaveLength(1); expect(await resumeSource(seeded)).toBe(seeded.priorRunId); }); const resumeHolds: Array<[string, (seeded: Seeded) => PromiseLike]> = [ ["no requeue proof is saved", seeded => db.update(heartbeatRuns).set({ resultJson: sql`${heartbeatRuns.resultJson} #- '{nativeStartupCleanup,beforeProviderWork}'` }).where(eq(heartbeatRuns.id, seeded.runId))], ["the proof is for a different run", seeded => db.update(heartbeatRuns).set({ resultJson: sql`jsonb_set(${heartbeatRuns.resultJson}, '{nativeStartupCleanup,runId}', '"other"'::jsonb)` }) .where(eq(heartbeatRuns.id, seeded.runId))], ["a session started", seeded => db.insert(heartbeatRunEvents).values({ companyId, agentId, runId: seeded.runId, seq: 99, eventType: "session.started" })], ["the cleanup is not settled", seeded => db.update(nativeRunFinalizations).set({ leaseOwner: "owner" }) .where(eq(nativeRunFinalizations.runId, seeded.runId))], ["the run inherited a different session", seeded => db.update(heartbeatRuns).set({ runnerProfileJson: sql`jsonb_set(${heartbeatRuns.runnerProfileJson}, '{sessionCheckpoint,providerSessionId}', '"other"'::jsonb)` }) .where(eq(heartbeatRuns.id, seeded.runId))], ]; it.each(resumeHolds)("does not look past the cancelled startup when %s", async (_name, change) => { const seeded = await seed({ terminal: true, reused: true }); const scope = { companyId, runId: seeded.runId }; await prepareNativeStartupRequeue(db, scope); await acknowledgeNativeStartupCleanup(db, scope); expect(await resumeSource(seeded)).toBe(seeded.priorRunId); await change(seeded); expect(await resumeSource(seeded)).toBe(seeded.runId); }); });