diff --git a/server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts b/server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts index 7d4885485a8..41f2c9e7a41 100644 --- a/server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts +++ b/server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts @@ -542,6 +542,19 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu expect((await current(agent.id)).lifecycleState).toBe("terminated"); }); + it("stops waiting on a conversation turn cancelled before dispatch", async () => { + const agent = await hire(); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, + status: "cancelled", errorCode: "cancelled", invocationSource: "on_demand", + runtimeMode: "legacy", runtimeModeResolvedAt: new Date(), executionStage: "preparing", + runnerProfileJson: { adapterDispatch: { adapterType: "claude_local" } }, + controllerBootId: randomUUID(), controllerLeaseExpiresAt: new Date(0), + startedAt: new Date(), finishedAt: new Date() }).returning(); + expect(await agentExecutionsHaveStopped(db, [agent.id])).toBe(true); + await db.update(heartbeatRuns).set({ executionStage: "dispatching" }).where(eq(heartbeatRuns.id, run.id)); + expect(await agentExecutionsHaveStopped(db, [agent.id])).toBe(false); + }); + it("does not cancel a reporting agent when its manager pauses", async () => { const parent = await hire(); const [child] = await db.insert(agents).values({ companyId, name: "Report", reportsTo: parent.id, diff --git a/server/src/services/cancelled-native-startup.ts b/server/src/services/cancelled-native-startup.ts index 9358bc973c9..ad29b8b0fdf 100644 --- a/server/src/services/cancelled-native-startup.ts +++ b/server/src/services/cancelled-native-startup.ts @@ -4,7 +4,7 @@ import { createHash } from "node:crypto"; import { and, eq, gt, inArray, isNotNull, isNull, lte, sql } from "drizzle-orm"; import { environmentLeases, heartbeatRunEvents, heartbeatRuns, issueTreeHolds, issueTreeHoldMembers, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db"; import { isUuidLike } from "@paperclipai/shared"; -import { claimedAdapterType } from "./conversation-continuation.js"; +import { claimedAdapterType, isConversationAdapter } from "./conversation-continuation.js"; import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js"; import { canContinueCancelledRun, readRunCancellation } from "./run-cancellation.js"; import { CONTROLLER_LEASE_LOST_FAILURE_CODE, legacyControllerBootId, legacyControllerProvenGone } from "./legacy-controller-lease.js"; @@ -289,8 +289,13 @@ export async function isCancelledNativeStartup(db: Db, run: Run, coordinator: Co run.runnerProfileJson?.nativeExecutionInput == null && run.runnerProfileJson?.nativeWorkspaceSync == null && run.runnerProfileJson?.remoteWorkspace == null && run.resultJson?.workspaceRestoreFailure == null && !hasRequiredWorkspaceRecovery(run.resultJson)); + const legacyBeforeDispatch = run.runtimeMode === "legacy" && + run.executionStage === "preparing" && !run.nativeIssueId && !run.nativeSessionId && !coordinator && + isConversationAdapter(claimedAdapterType(run) ?? "") && + Boolean(run.controllerBootId && run.controllerBootId !== legacyControllerBootId && + run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt <= new Date()); const unclaimedWorkspaceRetry = !coordinator && await isCancelledUnclaimedWorkspaceWaitRetry(db, run); - const beforeSelection = beforeDispatch || unclaimedWorkspaceRetry || historicalBeforeSelection || run.runtimeMode === "legacy" && !run.runtimeModeResolvedAt && + const beforeSelection = beforeDispatch || unclaimedWorkspaceRetry || historicalBeforeSelection || legacyBeforeDispatch || run.runtimeMode === "legacy" && !run.runtimeModeResolvedAt && !run.nativeSessionId && !coordinator && claimedAdapterType(run) === "paperclip_runner" && cancellation?.beforeNativeSelection === true; const neverClaimed = run.runtimeMode === "native" && coordinator && @@ -305,7 +310,7 @@ export async function isCancelledNativeStartup(db: Db, run: Run, coordinator: Co const leases = await db.select().from(environmentLeases).where(and( eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id), )); - if ((!settled && leases.length === 0 && !historicalBeforeSelection) || leases.some(lease => + if ((!settled && leases.length === 0 && !historicalBeforeSelection && !legacyBeforeDispatch) || leases.some(lease => lease.metadata?.pendingCleanupInFlight === true || (lease.provider === "local" ? !lease.releasedAt || lease.status === "pending_cleanup" || lease.cleanupStatus === "failed" : !hasRemoteTerminationReceipt(lease)))) return false; diff --git a/server/src/services/conversation-continuation.ts b/server/src/services/conversation-continuation.ts index 761127de092..15be3c84010 100644 --- a/server/src/services/conversation-continuation.ts +++ b/server/src/services/conversation-continuation.ts @@ -4,7 +4,9 @@ import { and, desc, eq, inArray, isNotNull, isNull, or, sql } from "drizzle-orm" import { environmentLeases, heartbeatRunEvents, heartbeatRuns, issueRecoveryActions, type Db } from "@paperclipai/db"; import { canonicalExecutionUuid } from "./execution-identity.js"; import { readProcessStartedAt } from "./hot-restart.js"; +import { legacyControllerBootId } from "./legacy-controller-lease.js"; import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js"; +import { executionStartedEventPredicate } from "./pre-dispatch-execution-evidence.js"; const LOCAL_CONVERSATION_ADAPTER_TYPES = [ "claude_local", "codex_local", "cursor", "gemini_local", "opencode_local", @@ -104,6 +106,33 @@ export function conversationRecoveryActionPredicate() { eq(heartbeatRuns.status, "interrupted"), inArray(heartbeatRuns.errorCode, ["process_lost", "server_shutdown_interrupted", "execution_reconciliation_required"]), and(eq(heartbeatRuns.status, "cancelled"), sql`${heartbeatRuns.resultJson}->'executionCancellation'->>'state' = 'acknowledged'`), + and(eq(heartbeatRuns.status, "cancelled"), sql`${heartbeatRuns.runtimeMode} = 'legacy' + and ${heartbeatRuns.executionStage} = 'preparing' + and ${heartbeatRuns.processPid} is null + and ${heartbeatRuns.processGroupId} is null + and ${heartbeatRuns.processStartedAt} is null + and ${heartbeatRuns.nativeSessionId} is null + and ${heartbeatRuns.nativeIssueId} is null + and ${heartbeatRuns.sessionIdAfter} is null + and ${heartbeatRuns.controllerBootId} is not null + and ${heartbeatRuns.controllerBootId} <> ${legacyControllerBootId} + and ${heartbeatRuns.controllerLeaseExpiresAt} <= clock_timestamp() + and not exists ( + select 1 from ${environmentLeases} + where ${environmentLeases.companyId} = ${heartbeatRuns.companyId} + and ${environmentLeases.heartbeatRunId} = ${heartbeatRuns.id} + and (coalesce(${environmentLeases.provider}, '') <> 'local' + or ${environmentLeases.releasedAt} is null + or ${environmentLeases.status} = 'pending_cleanup' + or ${environmentLeases.cleanupStatus} = 'failed' + or ${environmentLeases.metadata}->>'pendingCleanupInFlight' = 'true') + ) + and not exists ( + select 1 from ${heartbeatRunEvents} + where ${heartbeatRunEvents.companyId} = ${heartbeatRuns.companyId} + and ${heartbeatRunEvents.runId} = ${heartbeatRuns.id} + and ${executionStartedEventPredicate()} + )`), )} )`, ); diff --git a/server/src/services/explicit-native-continuation.test.ts b/server/src/services/explicit-native-continuation.test.ts index 3e4209de522..796922d76d8 100644 --- a/server/src/services/explicit-native-continuation.test.ts +++ b/server/src/services/explicit-native-continuation.test.ts @@ -1902,6 +1902,81 @@ const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTes }, ); + async function seedLegacyConversationCancelledBeforeDispatch(fence = true) { + const f = await seedHistoricalCancelledPreparation(); + await db.update(heartbeatRuns).set({ errorCode: "cancelled", + runtimeModeResolvedAt: fence ? null : new Date("2026-09-11T10:00:01Z"), + runnerProfileJson: { adapterDispatch: { adapterType: "codex_local" } }, + resultJson: fence + ? { stopReason: "cancelled", cancelledByActorType: "user", + startupCancellation: { beforeNativeSelection: false, requestedAt: "2026-09-11T10:00:00Z" } } + : { stopReason: "cancelled", cancelledByActorType: "user" }, + }).where(eq(heartbeatRuns.id, f.sourceRunId)); + return f; + } + + it.each([true, false].flatMap(fence => ["message", "retry"].map(kind => ({ fence, kind }))))( + "recovers a conversation turn cancelled before dispatch through an explicit $kind (fence: $fence)", async ({ fence, kind }) => { + const f = await seedLegacyConversationCancelledBeforeDispatch(fence); + expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toBeNull(); + expect(await admit(f, true)).toBeNull(); + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running" }); + const successor = await heartbeatService(db).wakeup(f.agentId, { + source: "on_demand", triggerDetail: "manual", reason: kind === "retry" ? "retry_failed_run" : "issue_commented", + ...(kind === "retry" ? { failedRunId: f.sourceRunId } : {}), requestedByActorType: "user", requestedByActorId: "board", + payload: { issueId: f.issueId, ...(kind === "message" ? { commentId: f.commentId } : {}) }, + contextSnapshot: { issueId: f.issueId, ...(kind === "message" ? { wakeCommentId: f.commentId } : {}) }, + }); + expect(successor).toMatchObject({ status: "queued", contextSnapshot: kind === "retry" + ? { forceFreshSession: true, previousRunId: f.sourceRunId } + : { wakeCommentId: f.commentId } }); + expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toBeNull(); + const [source] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.sourceRunId)); + expect(source).toMatchObject({ status: "cancelled", runtimeMode: "legacy", executionStage: "preparing" }); + }, + ); + + it.each([true, false].flatMap(fence => ["dispatching", "no_stage", "native_mode", "process_adapter", "runner_adapter", + "no_adapter", "missing_boot", "current_boot", "missing_lease", "live_lease", "session", "launch", "invoked", "coordinator", + "cleanup", "remote", "remote_released", + ].map(kind => ({ fence, kind }))))( + "holds a conversation turn cancelled before dispatch with contradictory or incomplete $kind evidence (fence: $fence)", async ({ fence, kind }) => { + const f = await seedLegacyConversationCancelledBeforeDispatch(fence); + const patch = kind === "dispatching" ? { executionStage: "dispatching" } + : kind === "no_stage" ? { executionStage: null } + : kind === "native_mode" ? { runtimeMode: "native" as const } + : kind === "process_adapter" ? { runnerProfileJson: { adapterDispatch: { adapterType: "process" } } } + : kind === "runner_adapter" ? { runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner" } } } + : kind === "no_adapter" ? { runnerProfileJson: null } + : kind === "missing_boot" ? { controllerBootId: null } + : kind === "current_boot" ? { controllerBootId: legacyControllerBootId } + : kind === "missing_lease" ? { controllerLeaseExpiresAt: null } + : kind === "live_lease" ? { controllerLeaseExpiresAt: new Date(Date.now() + 60_000) } + : kind === "session" ? { sessionIdAfter: randomUUID() } : {}; + if (Object.keys(patch).length) await db.update(heartbeatRuns).set(patch).where(eq(heartbeatRuns.id, f.sourceRunId)); + if (kind === "launch" || kind === "invoked") await db.insert(heartbeatRunEvents).values({ companyId: f.companyId, + agentId: f.agentId, runId: f.sourceRunId, seq: 1, + eventType: kind === "launch" ? PROCESS_START_REQUESTED : "adapter.invoke", payload: { adapterType: "codex_local" } }); + if (kind === "coordinator") { + await db.update(heartbeatRuns).set({ nativeIssueId: f.issueId }).where(eq(heartbeatRuns.id, f.sourceRunId)); + await db.insert(nativeRunFinalizations).values({ companyId: f.companyId, + runId: f.sourceRunId, issueId: f.issueId, phase: "observed", attempt: 0 }); + } + if (kind === "cleanup" || kind === "remote") await db.insert(environmentLeases).values({ companyId: f.companyId, + heartbeatRunId: f.sourceRunId, provider: kind === "remote" ? "daytona" : "local", + providerLeaseId: kind === "remote" ? "unverified" : null, leasePolicy: "ephemeral", + status: "pending_cleanup", cleanupStatus: "failed" }); + if (kind === "remote_released") await db.insert(environmentLeases).values({ companyId: f.companyId, + heartbeatRunId: f.sourceRunId, provider: "daytona", providerLeaseId: "released-without-receipt", + leasePolicy: "ephemeral", status: "expired", cleanupStatus: "success", releasedAt: new Date() }); + const blocker = await getExecutionBlocker(db, f.companyId, f.issueId); + expect(blocker).not.toBeNull(); + expect(blocker?.canRetry ?? false).toBe(false); + if (kind !== "native_mode") expect(await admit(f)).toBeNull(); + await db.delete(environmentLeases).where(eq(environmentLeases.heartbeatRunId, f.sourceRunId)); + }, + ); + it.each(["attempt", "generation", "controller", "lease", "process", "launch", "provider", "cleanup", "remote", "preparing", "closed", "reassigned"])( "retains cancellation safeguards with %s evidence", async kind => { const f = await seedCancelledStartup();