diff --git a/doc/runner-internals.md b/doc/runner-internals.md index 86e98b553d7..73d93ce5960 100644 --- a/doc/runner-internals.md +++ b/doc/runner-internals.md @@ -562,6 +562,14 @@ that classification finishes. - A runner that died before its first authenticated connection can restart on the same run only when its durable root proves that no provider authority or checkpoint exists. Paperclip quarantines the incomplete root first. +- A sandbox startup that passes its deadline is cancelled, and its task is stopped. + Paperclip queues the same wake again when the provider confirms the stop and the + saved evidence shows no process request, session, turn, Runner checkpoint, or + result. The new run uses the interrupted preparation retry limits. It resumes + the saved session when the stopped task still holds the session state of the + earlier run. Otherwise, it starts a new session. Messages that wait behind the + cancelled run stay in order behind the new run. A startup that a person, a pause, + a budget, or a reassignment stopped is not queued again. - A live but mismatched or unverifiable process fails closed. Paperclip does not signal it or spawn a replacement. - A persisted proposed or terminal result is reconciled before any runner or diff --git a/server/src/index.ts b/server/src/index.ts index eed4c10ea47..03f91909715 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -107,6 +107,7 @@ import { deliverBudgetResumeContinuations, type BudgetResumeDelivery } from "./s import { invalidateNativeReplacementDiscovery, reconcileSafeNativeReplacements } from "./services/native-runtime/native-safe-replacement.js"; import { reconcileAbandonedExecutionControl } from "./services/execution-control-reconciliation.js"; import { acknowledgeNativeStartupCleanup } from "./services/native-runtime/native-startup-cleanup.js"; +import { NATIVE_STARTUP_TIMEOUT_CANCELLATION_REASON } from "./services/native-runtime/native-startup-requeue.js"; import { executionControlSchedule, registerExecutionControlWork } from "./services/execution-control-work.js"; import { connectionIntentDeliveryService } from "./services/connection-intent-delivery.js"; import { existsSync, readFileSync, rmSync } from "node:fs"; @@ -1502,7 +1503,7 @@ async function startServerWithDatabaseTeardown( registerExecutionControlWork(deliveryWork, [ { queue: DELIVERY_QUEUES.executionFinalization, run: () => reconcileAbandonedExecutionControl(db, new Date(), { startupCleanup: async scope => { - await accountingHeartbeat.cancelRun(scope.runId, "Native startup timed out; cancelling and verifying cleanup"); + await accountingHeartbeat.cancelRun(scope.runId, NATIVE_STARTUP_TIMEOUT_CANCELLATION_REASON); await acknowledgeNativeStartupCleanup(db, scope); }, }), next: executionSchedule.finalization }, diff --git a/server/src/services/heartbeat/retries.ts b/server/src/services/heartbeat/retries.ts index 774a68e869e..4bdf7aa0ec9 100644 --- a/server/src/services/heartbeat/retries.ts +++ b/server/src/services/heartbeat/retries.ts @@ -513,6 +513,7 @@ export function createHeartbeatRetries(db: Db, dependencies: HeartbeatRetryDepen maxAttempts?: number; delayMs?: number; preserveWakeContext?: boolean; + forceFreshSession?: boolean; }, ) { if (isProviderQuotaActionRequired(run, opts?.now)) return { outcome: "not_scheduled" as const, @@ -773,7 +774,7 @@ export function createHeartbeatRetries(db: Db, dependencies: HeartbeatRetryDepen } } const taskKey = deriveTaskKeyWithHeartbeatFallback(contextSnapshot, null); - const sessionBefore = await resolveSessionBeforeForWakeup(agent, taskKey); + const sessionBefore = opts?.forceFreshSession ? null : await resolveSessionBeforeForWakeup(agent, taskKey); const interactionRunnerWait = isPreparationWaitRetryReason(retryReason) && isResolvedInteractionContinuationWakeContext(run.contextSnapshot); const interactionContinuationPayload = @@ -808,6 +809,7 @@ export function createHeartbeatRetries(db: Db, dependencies: HeartbeatRetryDepen ...(opts?.preserveWakeContext ? { preparationWait: { kind: retryReason, attempt: schedule.attempt, nextAttemptAt: schedule.dueAt.toISOString() } } : { wakeReason, retryReason }), + ...(opts?.forceFreshSession ? { forceFreshSession: true } : {}), ...(interactionRunnerWait ? { mutation: "interaction" } : {}), ...(retryReason === ENVIRONMENT_PROVIDER_WAIT_RETRY_REASON ? { [ENVIRONMENT_PROVIDER_WAIT_KEY]: environmentProviderWaitFor(run, now) } @@ -2233,6 +2235,8 @@ export function createHeartbeatRetries(db: Db, dependencies: HeartbeatRetryDepen wakeReason?: string; maxAttempts?: number; delayMs?: number; + preserveWakeContext?: boolean; + forceFreshSession?: boolean; }, ) => { const run = await getRun(runId, { unsafeFullResultJson: true }); diff --git a/server/src/services/heartbeat/run-control.ts b/server/src/services/heartbeat/run-control.ts index dc4c6cb8c20..2223b2c3cf0 100644 --- a/server/src/services/heartbeat/run-control.ts +++ b/server/src/services/heartbeat/run-control.ts @@ -137,6 +137,8 @@ import { parseObject } from "../../adapters/utils.js"; import { resumePreservedResultFinalization } from "../preserved-result-finalization.js"; import { isNativeRunnerOwnershipHeld, nativeManualAdmissionOwnerColumns, nativeRunnerOwnershipNotHeldCondition } from "../native-runtime/native-runner-ownership.js"; import { readNativeStartupCleanup, acknowledgeNativeStartupCleanup } from "../native-runtime/native-startup-cleanup.js"; +import { prepareNativeStartupRequeue } from "../native-runtime/native-startup-requeue.js"; +import { INTERRUPTED_PREPARATION_RETRY_REASON } from "../execution-recovery-attempt.js"; import { withCurrentBudgetEnforcement, type BudgetEnforcementScope, @@ -1303,6 +1305,28 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont budgetEnforcement: { ...intent, deliveredAt: deliveredAt.toISOString() } } } : {}; } + async function settleStartupCleanup(run: { id: string; companyId: string }): Promise { + const scope = { companyId: run.companyId, runId: run.id }; + const requeue = await prepareNativeStartupRequeue(db, scope); + if (requeue) { + const refusal = await dependencies.scheduleBoundedRetry(run.id, { retryReason: INTERRUPTED_PREPARATION_RETRY_REASON, + preserveWakeContext: true, forceFreshSession: requeue.forceFreshSession }) + .then(retry => retry.outcome === "scheduled" ? null : { outcome: retry.outcome }, (err: unknown) => { + if (err instanceof HttpError && err.status < 500) return { err }; + throw err; + }); + if (refusal) logger.warn({ runId: run.id, ...refusal }, "a startup that timed out could not be queued again"); + } + return acknowledgeNativeStartupCleanup(db, scope); + } + + async function releaseStartupCleanup(run: typeof heartbeatRuns.$inferSelect, reason: string): Promise { + await setWakeupStatus(run.wakeupRequestId, "cancelled", { finishedAt: run.finishedAt ?? new Date(), error: reason }); + await releaseIssueExecutionAndPromote(run); + await finalizeAgentStatus(run.agentId, "cancelled", undefined, { wasFirstHeartbeat: timerClaimWasFirstHeartbeat(run) }); + await startNextQueuedRunForAgent(run.agentId); + } + async function cancelRun( runId: string, reason: string, @@ -1457,6 +1481,9 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont } await acknowledgeBudgetCancellation(run, terminationProof); } + if (run.status === "cancelled" && readNativeStartupCleanup(run)?.state === "complete" && await settleStartupCleanup(run)) { + await releaseStartupCleanup(run, reason); + } return run; } const agent = await getAgent(run.agentId); @@ -1765,7 +1792,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont const cancelled = cancellation.run; if (cancellation.updated && cancelled) { - if (readNativeStartupCleanup(cancelled)) await acknowledgeNativeStartupCleanup(db, { companyId: cancelled.companyId, runId: cancelled.id }); + if (readNativeStartupCleanup(cancelled)) await settleStartupCleanup(cancelled); await setWakeupStatus(run.wakeupRequestId, "cancelled", { finishedAt: cancelled.finishedAt ?? new Date(), error: reason, diff --git a/server/src/services/native-runtime/native-session-resume.ts b/server/src/services/native-runtime/native-session-resume.ts index 61c5ef5bc31..595cacbe9b0 100644 --- a/server/src/services/native-runtime/native-session-resume.ts +++ b/server/src/services/native-runtime/native-session-resume.ts @@ -284,11 +284,12 @@ async function isUnstartedInheritedFollowUp( ): Promise { const checkpoint = record(run.runnerProfileJson.sessionCheckpoint); const identity = record(checkpoint.identity); - if (run.runtimeMode !== "native" || run.status !== "failed" || run.processPid !== null || + if (run.runtimeMode !== "native" || !["failed", "cancelled"].includes(run.status) || run.processPid !== null || run.processGroupId !== null || run.processStartedAt !== null || run.runnerProfileJson.nativeControllerRecovery != null || identity.runId !== run.id || identity.sessionId !== input.normalizedSessionId || checkpoint.cursor !== null) return false; const [evidence] = await db.select({ executionRecovery: sql`${heartbeatRuns.resultJson}->'executionRecovery'`, + startupCleanup: sql`${heartbeatRuns.resultJson}->'nativeStartupCleanup'`, phase: nativeRunFinalizations.phase, resultId: nativeRunFinalizations.resultId, leaseOwner: nativeRunFinalizations.leaseOwner, @@ -303,9 +304,14 @@ async function isUnstartedInheritedFollowUp( )).where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.agentId, input.agentId), eq(heartbeatRuns.nativeIssueId, input.issueId))); const recovery = record(evidence?.executionRecovery); - return Boolean(evidence && recovery.kind === "bootstrap" && recovery.providerWorkStarted === false && + const startup = record(evidence?.startupCleanup); + const unstarted = run.status === "cancelled" + ? startup.schema === "paperclip.native-startup-cleanup.v1" && startup.runId === run.id && + startup.state === "complete" && startup.beforeProviderWork === true + : recovery.kind === "bootstrap" && recovery.providerWorkStarted === false && evidence?.controllerPid === null; + return Boolean(evidence && unstarted && evidence.phase === "terminal_failure" && evidence.resultId === null && evidence.leaseOwner === null && - evidence.controllerPid === null && !evidence.controllerCheckpoint && !evidence.result && + !evidence.controllerCheckpoint && !evidence.result && !(await nativeSessionProviderEvidence(db, [run.id])).has(run.id)); } diff --git a/server/src/services/native-runtime/native-startup-cleanup.ts b/server/src/services/native-runtime/native-startup-cleanup.ts index be1980de4cf..d34e4c1c4dd 100644 --- a/server/src/services/native-runtime/native-startup-cleanup.ts +++ b/server/src/services/native-runtime/native-startup-cleanup.ts @@ -24,6 +24,7 @@ export interface NativeStartupCleanup { contextId: string; deadlineAtMs: number; leaseOwner: string; controllerGeneration: number; attempt: number; leaseId: string; taskId: string; requiresPreparationStop: boolean; state: "pending" | "complete"; auditId: string; + beforeProviderWork?: boolean; } export function readNativeStartupCleanup(run: Pick): NativeStartupCleanup | null { @@ -185,26 +186,27 @@ export async function verifyNativeStartupCleanup(db: Db, run: Run, release: () = }); } -export async function acknowledgeNativeStartupCleanup(db: Db, input: { companyId: string; runId: string }): Promise { +export async function acknowledgeNativeStartupCleanup(db: Db, input: { companyId: string; runId: string }): Promise { const [binding] = await db.select({ issueId: nativeRunFinalizations.issueId }).from(nativeRunFinalizations).where(and( eq(nativeRunFinalizations.companyId, input.companyId), eq(nativeRunFinalizations.runId, input.runId))); - if (!binding) return; - await db.transaction(async tx => { + if (!binding) return false; + return db.transaction(async tx => { await tx.select({ id: issues.id }).from(issues).where(and(eq(issues.companyId, input.companyId), eq(issues.id, binding.issueId))).for("update"); const [owner] = await tx.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, input.runId)).for("update"); const [run] = await tx.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, input.runId)).for("update"); const marker = run && readNativeStartupCleanup(run); if (!owner || !run || run.status !== "cancelled" || !marker || marker.state !== "complete" || owner.resultId || owner.failureCode !== NATIVE_STARTUP_CLEANUP_PENDING || owner.controllerGeneration !== marker.controllerGeneration || - owner.attempt !== marker.attempt || owner.leaseOwner !== marker.leaseOwner) return; + owner.attempt !== marker.attempt || owner.leaseOwner !== marker.leaseOwner) return false; const [lease] = await tx.select().from(environmentLeases).where(eq(environmentLeases.id, marker.leaseId)).for("update"); if (!lease || lease.heartbeatRunId !== run.id || lease.providerLeaseId !== marker.taskId || !hasRemoteTerminationReceipt(lease) || - (marker.requiresPreparationStop && lease.metadata?.runnerTaskPreparationStopped !== true)) return; + (marker.requiresPreparationStop && lease.metadata?.runnerTaskPreparationStopped !== true)) return false; await assertStartupCreationsStopped(tx as unknown as Db, marker); await notifyDeliveryWork(tx, DELIVERY_QUEUES.agentLifecycle); await notifyDeliveryWork(tx, DELIVERY_QUEUES.environmentCleanup); await notifyQueuedRunDispatch(tx, { companyId: run.companyId }); await tx.update(nativeRunFinalizations).set({ leaseOwner: null, leaseExpiresAt: null, controlDeadlineAt: null, recoveryState: null, failureCode: "native_retry_cancelled", updatedAt: new Date() }).where(and(eq(nativeRunFinalizations.runId, input.runId), isNull(nativeRunFinalizations.resultId))); + return true; }); } diff --git a/server/src/services/native-runtime/native-startup-requeue.test.ts b/server/src/services/native-runtime/native-startup-requeue.test.ts new file mode 100644 index 00000000000..58bff0b4812 --- /dev/null +++ b/server/src/services/native-runtime/native-startup-requeue.test.ts @@ -0,0 +1,347 @@ +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); + }); +}); diff --git a/server/src/services/native-runtime/native-startup-requeue.ts b/server/src/services/native-runtime/native-startup-requeue.ts new file mode 100644 index 00000000000..030815f3501 --- /dev/null +++ b/server/src/services/native-runtime/native-startup-requeue.ts @@ -0,0 +1,100 @@ +import { and, eq, sql } from "drizzle-orm"; +import { environmentLeases, heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults, nativeRunnerCheckpoints, type Db } from "@paperclipai/db"; +import { readRunCancellation } from "../run-cancellation.js"; +import { hasRemoteTerminationReceipt } from "../remote-execution-termination.js"; +import { hasRequiredWorkspaceRecovery } from "../workspace-restore-recovery-state.js"; +import { isNativeRunnerOwnershipHeld } from "./native-runner-ownership.js"; +import { hasNativeExecutionStartEvidence } from "./native-restart-recovery.js"; +import { nativeSessionProviderEvidence } from "./native-session-resume.js"; +import { NATIVE_STARTUP_CLEANUP_PENDING, readNativeStartupCleanup, type NativeStartupCleanup } from "./native-startup-cleanup.js"; + +export const NATIVE_STARTUP_TIMEOUT_CANCELLATION_REASON = "Native startup timed out; cancelling and verifying cleanup"; + +type Run = typeof heartbeatRuns.$inferSelect; +type Lease = typeof environmentLeases.$inferSelect; + +const PERSON_OR_POLICY_STOP_KEYS = ["cancelledByActorType", "cancelledByUserId", "cancelledByAgentId", "interruptedByActorType", + "interruptedByActorId", "queuedCommentInterruptQueueId", "pauseStop", "reassignmentStopRequested"] as const; +const UNSETTLED_PROFILE_KEYS = ["remoteWorkspace", "nativeWorkspaceSync", "nativeWorkspaceFinalizationOwner", + "nativeControllerRecovery"] as const; + +function object(value: unknown): Record { + return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; +} + +function endedOnlyByStartupTimeout(run: Run): NativeStartupCleanup | null { + const marker = readNativeStartupCleanup(run); + const result = object(run.resultJson); + const profile = object(run.runnerProfileJson); + const cancellation = readRunCancellation(run.resultJson); + const nativeCancellation = result.nativeCancellation; + return marker?.state === "complete" && run.status === "cancelled" && run.runtimeMode === "native" && run.errorCode === "cancelled" && + run.scopeKind === "issue" && run.issueId !== null && run.nativeIssueId === run.issueId && + run.processPid === null && run.processGroupId === null && run.processStartedAt === null && run.sessionIdAfter === null && + !isNativeRunnerOwnershipHeld(run) && + cancellation?.source === "control_plane" && cancellation.initiator.type === "system" && + cancellation.reason === NATIVE_STARTUP_TIMEOUT_CANCELLATION_REASON && + PERSON_OR_POLICY_STOP_KEYS.every(key => result[key] === undefined || result[key] === null) && + object(result.startupCancellation).budgetEnforcement === undefined && + (nativeCancellation === undefined || object(nativeCancellation).scope === "run") && + result.workspaceRestoreFailure === undefined && !hasRequiredWorkspaceRecovery(run.resultJson) && + UNSETTLED_PROFILE_KEYS.every(key => profile[key] === undefined || profile[key] === null) ? marker : null; +} + +function inheritedCheckpoint(run: Run): boolean { + const checkpoint = object(object(run.runnerProfileJson).sessionCheckpoint); + return object(checkpoint.identity).runId === run.id && checkpoint.cursor === null; +} + +async function keepsPredecessorSession(tx: Db, run: Run, lease: Lease): Promise { + const metadata = object(lease.metadata); + if (metadata.portableTaskPredecessor !== undefined || metadata.portableTaskPreviousLeaseId !== undefined) return false; + if (metadata.runnerTaskReused !== true) return metadata.runnerTaskIdentity === undefined; + const identity = object(metadata.runnerTaskIdentity); + const previousLeaseId = metadata.runnerTaskPreviousLeaseId; + if (metadata.runnerTaskSessionRetained !== true || typeof identity.runId !== "string" || identity.runId === run.id || + typeof previousLeaseId !== "string") return false; + const [previous] = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, run.companyId), + eq(environmentLeases.id, previousLeaseId))).for("update"); + if (!previous || previous.heartbeatRunId !== identity.runId || previous.providerLeaseId !== lease.providerLeaseId || + previous.issueId !== lease.issueId || !hasRemoteTerminationReceipt(previous)) return false; + await tx.update(environmentLeases).set({ metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) || ${JSON.stringify({ + runnerTaskExecutionStopped: true, runnerTaskSessionRetained: true })}::jsonb`, updatedAt: new Date() }) + .where(eq(environmentLeases.id, previous.id)); + await tx.update(environmentLeases).set({ metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) || ${JSON.stringify({ + runnerTaskSessionRetained: false, runnerTaskSessionReturnedTo: previous.id })}::jsonb`, updatedAt: new Date() }) + .where(eq(environmentLeases.id, lease.id)); + return true; +} + +export async function prepareNativeStartupRequeue(db: Db, input: { companyId: string; runId: string }): + Promise<{ forceFreshSession: boolean } | null> { + const [binding] = await db.select({ issueId: nativeRunFinalizations.issueId }).from(nativeRunFinalizations).where(and( + eq(nativeRunFinalizations.companyId, input.companyId), eq(nativeRunFinalizations.runId, input.runId))); + if (!binding) return null; + return db.transaction(async transaction => { + const tx = transaction as unknown as Db; + await tx.select({ id: issues.id }).from(issues).where(and(eq(issues.companyId, input.companyId), eq(issues.id, binding.issueId))).for("update"); + const [owner] = await tx.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, input.runId)).for("update"); + const [run] = await tx.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, input.companyId), + eq(heartbeatRuns.id, input.runId))).for("update"); + const marker = run ? endedOnlyByStartupTimeout(run) : null; + if (!owner || !run || !marker || owner.resultId || owner.issueId !== run.nativeIssueId || + owner.failureCode !== NATIVE_STARTUP_CLEANUP_PENDING || owner.controllerGeneration !== marker.controllerGeneration || + owner.attempt !== marker.attempt || owner.leaseOwner !== marker.leaseOwner) return null; + const [lease] = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, run.companyId), + eq(environmentLeases.id, marker.leaseId))).for("update"); + if (!lease || lease.heartbeatRunId !== run.id || lease.providerLeaseId !== marker.taskId || !hasRemoteTerminationReceipt(lease)) return null; + const scope = { companyId: run.companyId, runId: run.id }; + const [result] = await tx.select({ id: nativeRunResults.id }).from(nativeRunResults).where(and( + eq(nativeRunResults.companyId, scope.companyId), eq(nativeRunResults.runId, scope.runId))).limit(1); + const [checkpoint] = await tx.select({ runId: nativeRunnerCheckpoints.runId }).from(nativeRunnerCheckpoints).where(and( + eq(nativeRunnerCheckpoints.companyId, scope.companyId), eq(nativeRunnerCheckpoints.runId, scope.runId))).limit(1); + if (result || checkpoint || await hasNativeExecutionStartEvidence(tx, run) || + (await nativeSessionProviderEvidence(tx, [run.id])).has(run.id)) return null; + const keepsSession = lease.metadata?.runnerTaskSessionReturnedTo !== undefined || await keepsPredecessorSession(tx, run, lease); + await tx.update(heartbeatRuns).set({ resultJson: sql`jsonb_set(${heartbeatRuns.resultJson}, '{nativeStartupCleanup,beforeProviderWork}', 'true'::jsonb)`, + updatedAt: new Date() }).where(eq(heartbeatRuns.id, run.id)); + return { forceFreshSession: !keepsSession || !inheritedCheckpoint(run) }; + }); +}