diff --git a/doc/runner-internals.md b/doc/runner-internals.md index 9fa381b7353..86e98b553d7 100644 --- a/doc/runner-internals.md +++ b/doc/runner-internals.md @@ -603,6 +603,19 @@ or cancelled result must retire that session and collect its managed files befor heartbeat stops the reusable sandbox. A later retry can resume the same sandbox without inheriting the stopped provider transport. +A stopped run has no accepted result, so `publishStoppedNativeSession` moves the +task's session link to it after its environment lease is released. It does so +only for an acknowledged Stop whose turn the provider accepted and then ended +with no request or background work waiting, whose controller journal is settled, +and whose provider reports that the task stopped and kept its session state. An +existing link is replaced only when its run belongs to the same task and agent +and finished before the stopped run started, which is the rule for accepted +results. A newer run, a reset, a conversation or any missing evidence leaves the +link unchanged. A task without a link then starts a new session on its next run. +The outcome is logged as `stopped run's task session`. If the provider later +confirms that the retained state is gone, the next run retires the stopped run's +controller state and starts a new session. + A rejected warm-session close retains its owner, even when no managed instruction copy exists. Idle expiry, failed-turn release, and restart must not report that owner as quiet or launch a replacement over it. The next retirement attempt uses diff --git a/server/src/__tests__/native-terminal-state-readers.test.ts b/server/src/__tests__/native-terminal-state-readers.test.ts index 3eb30b14314..95f67a79868 100644 --- a/server/src/__tests__/native-terminal-state-readers.test.ts +++ b/server/src/__tests__/native-terminal-state-readers.test.ts @@ -20,6 +20,7 @@ const ALLOWED: ReadonlyArray > = null; @@ -3840,6 +3843,7 @@ export function heartbeatService( effects: { onUsageCaptureReady: (value) => { persistUsageCaptureFailure = value; }, onNativeDispatchStarted: () => { nativeDispatchStarted = true; }, + onTaskSessionPublicationReady: (value) => { taskSessionPublication = value; }, onLegacyAdapterEntered: () => { legacyAdapterEntered = true; // A direct adapter reports its own progress from here on. @@ -4272,6 +4276,11 @@ export function heartbeatService( providerResourceDisposition: providerResourceDispositionForRun, nativeLifecycleTelemetry: nativeLifecycleTelemetryForRun, })); + if (taskSessionPublication && latestRun?.status === "cancelled" && latestRun.runtimeMode === "native") { + await publishStoppedNativeSession(db, run.id, taskSessionPublication) + .then(outcome => logger.info({ runId: run.id, outcome }, "stopped run's task session")) + .catch(err => logger.warn({ err, runId: run.id }, "could not keep a stopped run's task session")); + } crashPoint("environment.lease.after_release_before_runtime_services"); await releaseRuntimeServicesForRun(run.id).catch(() => undefined); caseHandoffCleanupSettled = true; diff --git a/server/src/services/heartbeat/runtime-execution.test.ts b/server/src/services/heartbeat/runtime-execution.test.ts index ca9a10993f8..5994730d720 100644 --- a/server/src/services/heartbeat/runtime-execution.test.ts +++ b/server/src/services/heartbeat/runtime-execution.test.ts @@ -129,7 +129,7 @@ describe.skipIf(!support.supported)("heartbeat runtime execution boundary", () = envOrchestrator: { releaseForRun: vi.fn() }, cancelRunInternal: vi.fn(), enqueueWakeup: vi.fn(), persistRunProcessMetadata: vi.fn(), recordCurrentHeartbeatRunRuntimeProgress: vi.fn(), dispatchPendingNativeStatusWakeups: vi.fn(), }, - effects: { onUsageCaptureReady: vi.fn(), onNativeDispatchStarted: vi.fn(), onLegacyAdapterEntered: vi.fn(), onWorkspaceRestoreFailure: vi.fn(), onProviderResourceDisposition: vi.fn(), onNativeWorkspaceFinalizeScheduled: vi.fn(), onNativeSessionResumeScheduled: vi.fn(), onNativeOwnershipHeld: vi.fn() }, + effects: { onUsageCaptureReady: vi.fn(), onNativeDispatchStarted: vi.fn(), onTaskSessionPublicationReady: vi.fn(), onLegacyAdapterEntered: vi.fn(), onWorkspaceRestoreFailure: vi.fn(), onProviderResourceDisposition: vi.fn(), onNativeWorkspaceFinalizeScheduled: vi.fn(), onNativeSessionResumeScheduled: vi.fn(), onNativeOwnershipHeld: vi.fn() }, }; return { input, adapter, run }; } @@ -579,6 +579,8 @@ describe.skipIf(!support.supported)("heartbeat runtime execution boundary", () = expect(await executeHeartbeatRuntime(db, input)).toMatchObject({ dispatched: true, adapterResult: { usage: { inputTokens: 7, outputTokens: 3 }, usageComplete: true } }); expect(adapter.execute).not.toHaveBeenCalled(); expect(input.effects.onNativeDispatchStarted).toHaveBeenCalledOnce(); + expect(input.effects.onTaskSessionPublicationReady).toHaveBeenCalledExactlyOnceWith( + vi.mocked(executePaperclipNativeSession).mock.lastCall![0].taskSessionPublication); expect(await read(run.id)).toMatchObject({ status: "running", usageJson: { inputTokens: 7, outputTokens: 3, accountingReceiptReady: true } }); expect(await finalizations()).toMatchObject([{ status: "succeeded" }]); expectCleanup(input); diff --git a/server/src/services/heartbeat/runtime-execution.ts b/server/src/services/heartbeat/runtime-execution.ts index 1ba8cbdf9cf..fa205a3c504 100644 --- a/server/src/services/heartbeat/runtime-execution.ts +++ b/server/src/services/heartbeat/runtime-execution.ts @@ -1,3 +1,4 @@ +import type { NativeTaskSessionPublicationContext } from "../native-runtime/native-task-session-publication.js"; import { readClaimedNativeStopRecovery } from "../native-runtime/native-cancellation-request.js"; import { readContextCompactionRequest } from "../context-compaction.js"; import { remoteWorkspaceFailureCause } from "../remote-workspace-transport.js"; @@ -209,6 +210,7 @@ export interface HeartbeatRuntimeExecutionInput { effects: { onUsageCaptureReady: (persistFailure: () => Promise) => void; onNativeDispatchStarted: () => void; + onTaskSessionPublicationReady: (context: NativeTaskSessionPublicationContext | undefined) => void; onLegacyAdapterEntered: () => void; onWorkspaceRestoreFailure: (evidence: Record) => void; onProviderResourceDisposition: (disposition: ProviderResourceDisposition) => void; @@ -618,6 +620,7 @@ export async function executeHeartbeatRuntime(db: Db, input: HeartbeatRuntimeExe ), } : undefined; + input.effects.onTaskSessionPublicationReady(taskSessionPublication); const nativeDispatchAtMs = Date.now(); const runCreatedAtMs = run.createdAt.getTime(); const runStartedAtMs = (run.startedAt ?? run.createdAt).getTime(); diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index b0450fe54a2..02e9f99eda6 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -20083,6 +20083,9 @@ describe("runnerd provider runtime wiring", () => { "stopped-availability-omitted", "stop-unconfirmed", "stopped-lease-unreleased", + "run-stopped-state-unavailable", + "run-stopped-unacknowledged", + "run-stopped-other-failure", ] as const)( "handles unconfirmed plugin checkpoint status on replacement lease: %s", async mode => { @@ -20112,16 +20115,27 @@ describe("runnerd provider runtime wiring", () => { const ordinarySelect = db.select.bind(db); const { currentNativeControllerIdentity } = await import("./native-restart-recovery.js"); const controller = await currentNativeControllerIdentity(); + const runStopped = mode.startsWith("run-stopped"); const committedPrior = { run: { id: first.binding.runId, companyId: first.binding.companyId, agentId: first.binding.agentId, - nativeIssueId: first.binding.issueId, runtimeMode: "native", status: "succeeded", + nativeIssueId: first.binding.issueId, runtimeMode: "native", status: runStopped ? "cancelled" : "succeeded", + resultJson: runStopped ? { nativeCancellation: { + schema: "paperclip.native-cancellation.v1", runId: first.binding.runId, companyId: first.binding.companyId, + issueId: first.binding.issueId, scope: "run", reasonCode: "cancellation_run_only", dispatched: true, + dispatchState: mode === "run-stopped-unacknowledged" ? "requested" : "acknowledged", + intentAuditId: "intent", acknowledgementAuditId: "acknowledgement", + } } : null, runnerProfileJson: { nativeExecutionInput: first }, processPid: null, processGroupId: null, processStartedAt: null, }, owner: { runId: first.binding.runId, companyId: first.binding.companyId, issueId: first.binding.issueId, - phase: "committed", resultId: "result-1", leaseOwner: null, recoveryState: null, + ...(runStopped + ? { phase: "terminal_failure", resultId: null, + failureCode: mode === "run-stopped-other-failure" ? "provider_failed" : "native_retry_cancelled" } + : { phase: "committed", resultId: "result-1", failureCode: null }), + leaseOwner: null, recoveryState: null, controllerPid: controller.pid, controllerProcessStartedAt: controller.processStartedAt, controllerBootId: controller.bootId, }, @@ -20150,7 +20164,7 @@ describe("runnerd provider runtime wiring", () => { }; db.select = ((fields?: Record) => { if (fields?.status === heartbeatRuns.status && fields?.runnerProfileJson === heartbeatRuns.runnerProfileJson) { - return priorNativeRunDb(first, "succeeded").select(fields as never); + return priorNativeRunDb(first, committedPrior.run.status).select(fields as never); } if (fields && "run" in fields && "owner" in fields) { return { @@ -20202,10 +20216,14 @@ describe("runnerd provider runtime wiring", () => { sandboxLeaseAcquisition: { outcome: "replacement", providerLeaseId: "replacement-task" }, } as never, }; - if (mode === "stopped-state-unavailable") { + if (mode === "stopped-state-unavailable" || mode === "run-stopped-state-unavailable") { await expect(createRunnerdBackend(launch)).resolves.toBeDefined(); expect(state.createBackend).toHaveBeenCalledOnce(); expect(existsSync(join(scoped, "continuity-breaks"))).toBe(true); + } else if (runStopped) { + await expect(createRunnerdBackend(launch)).rejects.toThrow("retirement_refused=owner_terminal_failure"); + expect(state.createBackend).not.toHaveBeenCalled(); + expect(existsSync(join(scoped, "continuity-breaks"))).toBe(false); } else if (mode === "stopped-lease-unreleased") { await expect(createRunnerdBackend(launch)).rejects.toThrow("retirement_refused=prior_lease_active"); expect(state.createBackend).not.toHaveBeenCalled(); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index f5535d2da5c..3f3201e55c8 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -6319,8 +6319,11 @@ async function inspectFinishedPerTurnRunnerdOwner(input: { } if (!prior || prior.run.runtimeMode !== "native") return refuse("owner_missing"); if (!TERMINAL_HEARTBEAT_RUN_STATUSES.has(prior.run.status)) return refuse("owner_run_not_terminal"); - if (prior.owner.phase !== "committed") return refuse(`owner_${retirementReasonName("ownerPhase", prior.owner.phase)}`); - if (!prior.owner.resultId) return refuse("owner_result_missing"); + const stoppedOwner = confirmedGonePluginTask && prior.run.status === "cancelled" + && prior.owner.phase === "terminal_failure" && prior.owner.failureCode === "native_retry_cancelled" + && !prior.owner.resultId && hasAcknowledgedNativeRunStopReceipt(prior.run); + if (!stoppedOwner && prior.owner.phase !== "committed") return refuse(`owner_${retirementReasonName("ownerPhase", prior.owner.phase)}`); + if (!stoppedOwner && !prior.owner.resultId) return refuse("owner_result_missing"); if (prior.owner.leaseOwner) return refuse("owner_lease_held"); if (prior.owner.recoveryState) return refuse(`owner_recovery_${retirementReasonName("recoveryState", prior.owner.recoveryState)}`); // A durable controller is fenced by its released database lease; a legacy diff --git a/server/src/services/native-runtime/native-stopped-session-publication.test.ts b/server/src/services/native-runtime/native-stopped-session-publication.test.ts new file mode 100644 index 00000000000..f97f1c65759 --- /dev/null +++ b/server/src/services/native-runtime/native-stopped-session-publication.test.ts @@ -0,0 +1,213 @@ +import { randomUUID } from "node:crypto"; +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { eq } from "drizzle-orm"; +import { agents, agentTaskSessions, companies, createDb, environmentLeases, environments, heartbeatRunEvents, + heartbeatRuns, issues, nativeRunFinalizations } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; +import { uniqueIssuePrefix } from "../../__tests__/helpers/issue-prefix.js"; + +const journal = vi.hoisted(() => ({ load: vi.fn() })); +vi.mock("./native-runner-checkpoint.js", async original => ({ + ...await original(), loadNativeRunnerCheckpoint: journal.load, +})); +const { publishStoppedNativeSession } = await import("./native-stopped-session-publication.js"); + +const support = await getEmbeddedPostgresTestSupport(); + +(support.supported ? describe : describe.skip)("stopped run's task session", () => { + let temporary: Awaited>; + let db: ReturnType; + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("paperclip-stopped-session-"); + db = createDb(temporary.connectionString); + }, 60_000); + afterAll(async () => { + await db?.$client.end({ timeout: 1 }); + await temporary?.cleanup(); + }); + beforeEach(() => { journal.load.mockReset(); }); + + async function fixture() { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(); + const sessionId = randomUUID(), runner = randomUUID(), environmentId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Stopped session", issuePrefix: uniqueIssuePrefix("SS") }); + await db.insert(agents).values({ id: agentId, companyId, name: "Agent", adapterType: "paperclip_runner" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Task", status: "in_progress", assigneeAgentId: agentId }); + const nativeCancellation = { schema: "paperclip.native-cancellation.v1", intentId: "intent", intentAuditId: "intent-audit", + acknowledgementAuditId: "acknowledgement-audit", companyId, runId, issueId, scope: "run", + reasonCode: "cancellation_run_only", dispatchState: "acknowledged", dispatched: true }; + const sessionCheckpoint = { backendKind: "test", sessionId, providerSessionId: "provider-thread", activeTurnId: null, + identity: { companyId, agentId, issueId, runId, sessionId }, pendingRuntimeRequests: [], goal: null, semanticResult: null, + terminal: { schema: "paperclip.prp.terminal.v1", turnTerminalState: "cancelled", runTerminalState: "cancelled", + reportedWorkDisposition: "yielded" } }; + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "cancelled", runtimeMode: "native", + nativeIssueId: issueId, issueId, nativeSessionId: sessionId, runnerInstanceId: runner, + startedAt: new Date("2026-01-01T00:10:00Z"), finishedAt: new Date("2026-01-01T00:20:00Z"), resultJson: { nativeCancellation }, runnerProfileJson: { sessionCheckpoint } }); + await db.insert(heartbeatRunEvents).values({ companyId, agentId, runId, seq: 1, eventType: "turn.accepted" }); + await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "terminal_failure", + failureCode: "native_retry_cancelled", attempt: 1 }); + await db.insert(environments).values({ id: environmentId, name: `Environment ${environmentId}`, driver: "plugin" }); + const metadata = { runnerTaskLease: true, runnerTaskExecutionStopped: true, runnerTaskSessionRetained: true, + runnerTaskIdentity: { runnerId: runner, leaseId: "lease", runId, sessionId } }; + const [lease] = await db.insert(environmentLeases).values({ companyId, environmentId, issueId, heartbeatRunId: runId, + status: "released", cleanupStatus: "success", provider: "plugin", providerLeaseId: "task", metadata }).returning(); + await db.insert(agentTaskSessions).values({ companyId, agentId, adapterType: "paperclip_runner", taskKey: issueId, + goalSourceId: `${runner}:${runId}`, goalSourceCursor: 4 }); + const envelope = { runId, normalizedSessionId: sessionId }; + const control: Record = { identity: { runId, normalizedSessionId: sessionId, runnerInstanceId: runner }, + commands: [{ type: "turn.start", status: "completed", controllerSeq: 1 }, { type: "runner.suspend", status: "completed", controllerSeq: 2 }], + committedEvents: [{ eventType: "turn.cancelled", envelope }, { eventType: "run.terminal", envelope }] }; + journal.load.mockImplementation(async () => ({ records: new Map([ + ["header", JSON.stringify({ state: { identity: control.identity } })], + ["cursor", "{}"], + ...(control.commands as unknown[]).map((command, index) => [`command:${index + 1}`, JSON.stringify(command)] as const), + ...(control.committedEvents as unknown[]).map((event, index) => [`event:${index + 1}`, JSON.stringify(event)] as const), + ]) })); + const context = { taskKey: issueId, adapterType: "paperclip_runner", + sessionParamsJson: { cwd: "/workspace", paperclipSessionConfigFingerprint: "prepared" } }; + const read = async () => (await db.select().from(agentTaskSessions).where(eq(agentTaskSessions.taskKey, issueId)))[0]; + const setRun = (values: Partial) => + db.update(heartbeatRuns).set(values).where(eq(heartbeatRuns.id, runId)); + const setLease = (values: Partial) => + db.update(environmentLeases).set(values).where(eq(environmentLeases.id, lease!.id)); + return { companyId, agentId, issueId, runId, sessionId, runner, environmentId, nativeCancellation, sessionCheckpoint, + metadata, control, context, read, setRun, setLease, publish: () => publishStoppedNativeSession(db, runId, context) }; + } + type Fixture = Awaited>; + const linkEarlierRun = async (f: Fixture, sessionId: string, run: Partial = {}) => { + const id = randomUUID(); + await db.insert(heartbeatRuns).values({ id, companyId: f.companyId, agentId: f.agentId, status: "succeeded", issueId: f.issueId, + startedAt: new Date("2026-01-01T00:00:00Z"), finishedAt: new Date("2026-01-01T00:05:00Z"), ...run }); + await db.update(agentTaskSessions).set({ lastRunId: id, sessionDisplayId: "earlier-thread", + sessionParamsJson: { sessionId, paperclipSessionConfigFingerprint: "earlier" } }).where(eq(agentTaskSessions.taskKey, f.issueId)); + }; + const newerRun = async (f: Fixture) => { + const id = randomUUID(); + await db.insert(heartbeatRuns).values({ id, companyId: f.companyId, agentId: f.agentId, status: "queued", issueId: f.issueId }); + return id; + }; + + it("links the session with the prepared metadata, so the next run can resume it", async () => { + const f = await fixture(); + expect(await f.publish()).toBe("published"); + expect(await f.read()).toMatchObject({ lastRunId: f.runId, sessionDisplayId: "provider-thread", lastError: null, + sessionParamsJson: { ...f.context.sessionParamsJson, sessionId: f.sessionId } }); + expect(await f.publish()).toBe("published"); + }); + + it.each([ + ["the same session", (f: Fixture) => f.sessionId], + ["another session", () => randomUUID()], + ])("replaces an earlier run's link to %s", async (_name, linkedSession) => { + const f = await fixture(); + await linkEarlierRun(f, linkedSession(f)); + expect(await f.publish()).toBe("published"); + expect(await f.read()).toMatchObject({ lastRunId: f.runId, sessionDisplayId: "provider-thread", + sessionParamsJson: { ...f.context.sessionParamsJson, sessionId: f.sessionId } }); + }); + + it("replaces an earlier run that finished when this run started", async () => { + const f = await fixture(); + await linkEarlierRun(f, randomUUID(), { finishedAt: new Date("2026-01-01T00:10:00Z") }); + expect(await f.publish()).toBe("published"); + }); + + it("accepts the provider's own turn start", async () => { + const f = await fixture(); + await db.update(heartbeatRunEvents).set({ eventType: "turn.started" }).where(eq(heartbeatRunEvents.runId, f.runId)); + expect(await f.publish()).toBe("published"); + }); + + it("accepts the issue's execution lock when this run still holds it", async () => { + const f = await fixture(); + await db.update(issues).set({ executionRunId: f.runId }).where(eq(issues.id, f.issueId)); + expect(await f.publish()).toBe("published"); + }); + + const refusals: Array<[string, string, (f: Fixture) => Promise | void]> = [ + ["the Stop was never acknowledged", "stop_unproven", f => + f.setRun({ resultJson: { nativeCancellation: { ...f.nativeCancellation, dispatchState: "pending" } } })], + ["the Stop did not reach the provider", "stop_unproven", f => + f.setRun({ resultJson: { nativeCancellation: { ...f.nativeCancellation, dispatched: false } } })], + ["the run failed instead of stopping", "stop_unproven", f => f.setRun({ status: "failed" })], + ["the coordinator did not settle as a Stop", "stop_unproven", f => db.update(nativeRunFinalizations) + .set({ phase: "retryable_failure", failureCode: "native_session_interrupted" }).where(eq(nativeRunFinalizations.runId, f.runId))], + ["recovery still owns the run", "stop_unproven", f => db.update(nativeRunFinalizations) + .set({ leaseOwner: "owner", leaseExpiresAt: new Date(Date.now() + 60_000) }).where(eq(nativeRunFinalizations.runId, f.runId))], + ["no checkpoint was saved", "turn_unsettled", f => f.setRun({ runnerProfileJson: {} })], + ["the checkpoint belongs to another session", "turn_unsettled", f => f.setRun({ nativeSessionId: randomUUID() })], + ["the turn never ended", "turn_unsettled", f => f.setRun({ runnerProfileJson: { sessionCheckpoint: + { ...f.sessionCheckpoint, activeTurnId: "turn", terminal: null } } })], + ["the turn waits for background work", "turn_unsettled", f => f.setRun({ runnerProfileJson: { sessionCheckpoint: + { ...f.sessionCheckpoint, awaitingProviderTurn: true, terminal: null } } })], + ["the turn failed", "turn_unsettled", f => f.setRun({ runnerProfileJson: { sessionCheckpoint: + { ...f.sessionCheckpoint, terminal: { ...f.sessionCheckpoint.terminal, runTerminalState: "failed" } } } })], + ["a request is still waiting for an answer", "turn_unsettled", f => f.setRun({ runnerProfileJson: { sessionCheckpoint: + { ...f.sessionCheckpoint, pendingRuntimeRequests: [{ requestId: "request" }] } } })], + ["a goal is recorded", "turn_unsettled", f => f.setRun({ runnerProfileJson: { sessionCheckpoint: + { ...f.sessionCheckpoint, goal: { status: "active" } } } })], + ["the provider never accepted a turn", "turn_not_started", f => db.update(heartbeatRunEvents) + .set({ eventType: "turn.submitted" }).where(eq(heartbeatRunEvents.runId, f.runId))], + ["only another run's turn was accepted", "turn_not_started", async f => { + const runId = await newerRun(f); + await db.update(heartbeatRunEvents).set({ runId }).where(eq(heartbeatRunEvents.runId, f.runId)); + }], + ["the journal is missing", "journal_unsettled", () => { journal.load.mockResolvedValue(null); }], + ["the journal cannot be read", "journal_unsettled", () => { journal.load.mockRejectedValue(new Error("retired")); }], + ["the journal names another run", "journal_unsettled", f => { (f.control.identity as Record).runId = randomUUID(); }], + ["the journal has no terminal", "journal_unsettled", f => { (f.control.committedEvents as unknown[]).pop(); }], + ["a command is still pending", "journal_unsettled", f => { (f.control.commands as Array>)[1]!.status = "pending"; }], + ["a command's outcome is unknown", "journal_unsettled", f => { + (f.control.commands as Array>)[0]!.status = "indeterminate"; }], + ["a tool call started after the terminal", "journal_unsettled", f => { + (f.control.committedEvents as unknown[]).push({ eventType: "tool.execution.started", + envelope: { runId: f.runId, normalizedSessionId: f.sessionId } }); }], + ["the provider kept no session state", "session_not_retained", f => + f.setLease({ metadata: { ...f.metadata, runnerTaskSessionRetained: false } })], + ["the task is not known to have stopped", "session_not_retained", f => + f.setLease({ metadata: { ...f.metadata, runnerTaskExecutionStopped: false } })], + ["the retained state names another session", "session_not_retained", f => + f.setLease({ metadata: { ...f.metadata, runnerTaskIdentity: { ...f.metadata.runnerTaskIdentity, sessionId: randomUUID() } } })], + ["the lease is not a Runner task", "session_not_retained", f => + f.setLease({ metadata: { ...f.metadata, runnerTaskLease: false } })], + ["lease cleanup is still pending", "session_not_retained", f => + f.setLease({ status: "pending_cleanup", cleanupStatus: "failed" })], + ["the run used a second lease", "session_not_retained", f => db.insert(environmentLeases).values({ companyId: f.companyId, + environmentId: f.environmentId, issueId: f.issueId, heartbeatRunId: f.runId, status: "released", cleanupStatus: "success", + provider: "plugin", providerLeaseId: "other-task", metadata: f.metadata })], + ["a newer run holds the task", "superseded", async f => db.update(issues).set({ executionRunId: await newerRun(f) }) + .where(eq(issues.id, f.issueId))], + ["a newer run wrote the session row", "superseded", async f => db.update(agentTaskSessions) + .set({ goalSourceId: `${f.runner}:${await newerRun(f)}` }).where(eq(agentTaskSessions.taskKey, f.issueId))], + ["the session was reset", "session_row_missing", f => db.delete(agentTaskSessions).where(eq(agentTaskSessions.taskKey, f.issueId))], + ["a later run wrote the link", "superseded", f => linkEarlierRun(f, randomUUID(), { + startedAt: new Date("2026-01-01T00:21:00Z"), finishedAt: new Date("2026-01-01T00:22:00Z") })], + ["the linked run has not finished", "superseded", f => linkEarlierRun(f, randomUUID(), { status: "running", finishedAt: null })], + ["the linked run belongs to another task", "superseded", async f => { + const issueId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId: f.companyId, title: "Other task", status: "todo" }); + await linkEarlierRun(f, randomUUID(), { issueId }); + }], + ["the linked run belongs to another agent", "superseded", async f => { + const agentId = randomUUID(); + await db.insert(agents).values({ id: agentId, companyId: f.companyId, name: "Other agent", adapterType: "paperclip_runner" }); + await linkEarlierRun(f, randomUUID(), { agentId }); + }], + ["this run has no start time", "superseded", async f => { + await linkEarlierRun(f, randomUUID()); + await f.setRun({ startedAt: null }); + }], + ["the task is a conversation", "unsupported_task", f => db.update(issues).set({ conversationAgentId: f.agentId, + conversationUserId: "stopped-session-user", conversationState: "active" }).where(eq(issues.id, f.issueId))], + ["the run's content was deleted", "unsupported_task", f => f.setRun({ + resultJson: { nativeCancellation: f.nativeCancellation, contentDeletedAt: new Date(0).toISOString() } })], + ]; + + it.each(refusals)("leaves the task session unchanged when %s", async (_name, outcome, change) => { + const f = await fixture(); + await change(f); + const before = await f.read(); + expect(await f.publish()).toBe(outcome); + expect(await f.read()).toEqual(before); + }); +}); diff --git a/server/src/services/native-runtime/native-stopped-session-publication.ts b/server/src/services/native-runtime/native-stopped-session-publication.ts new file mode 100644 index 00000000000..50c8683a032 --- /dev/null +++ b/server/src/services/native-runtime/native-stopped-session-publication.ts @@ -0,0 +1,96 @@ +import { and, eq } from "drizzle-orm"; +import { agentTaskSessions, environmentLeases, heartbeatRuns, issues, nativeRunFinalizations, type Db } from "@paperclipai/db"; +import { hasAcknowledgedNativeRunStopReceipt } from "../acknowledged-native-stop.js"; +import { RUN_CONTENT_DELETED_MARKER } from "../tool-access/connections/run-session-reset.js"; +import { loadNativeRunnerCheckpoint } from "./native-runner-checkpoint.js"; +import { taskSessionLinkReplaceable, type NativeTaskSessionPublicationContext } from "./native-task-session-publication.js"; +import { readProviderAttemptOutcome } from "./provider-attempt-outcome.js"; +import { isSettledRemoteWarmControlState } from "./remote-warm-session-recovery.js"; + +export type StoppedSessionOutcome = "published" | "stop_unproven" | "turn_unsettled" | "turn_not_started" + | "session_not_retained" | "journal_unsettled" | "unsupported_task" | "superseded" | "session_row_missing"; + +type Run = typeof heartbeatRuns.$inferSelect; +type Lease = typeof environmentLeases.$inferSelect; + +function record(value: unknown): Record { + return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; +} + +function settledSnapshot(run: Run): { sessionId: string; displayId: string } | null { + const snapshot = record(run.runnerProfileJson?.sessionCheckpoint), identity = record(snapshot.identity); + const displayId = snapshot.providerSessionId ?? snapshot.sessionId; + if (identity.companyId !== run.companyId || identity.agentId !== run.agentId || identity.issueId !== run.nativeIssueId + || identity.runId !== run.id || typeof identity.sessionId !== "string" || identity.sessionId !== run.nativeSessionId + || typeof displayId !== "string" || !displayId + || record(snapshot.terminal).runTerminalState !== "cancelled" || snapshot.activeTurnId !== null + || snapshot.awaitingProviderTurn === true || snapshot.goal != null + || (Array.isArray(snapshot.pendingRuntimeRequests) && snapshot.pendingRuntimeRequests.length > 0)) return null; + return { sessionId: identity.sessionId, displayId }; +} + +function sessionRetained(run: Run, leases: Lease[]): boolean { + if (leases.length !== 1) return false; + const [lease] = leases, metadata = record(lease!.metadata), identity = record(metadata.runnerTaskIdentity); + return lease!.status === "released" && lease!.cleanupStatus === "success" && metadata.runnerTaskLease === true + && metadata.runnerTaskExecutionStopped === true && metadata.runnerTaskSessionRetained === true + && identity.runId === run.id && identity.sessionId === run.nativeSessionId && identity.runnerId === run.runnerInstanceId; +} + +async function journalSettled(db: Db, run: Run): Promise { + const checkpoint = await loadNativeRunnerCheckpoint(db, { companyId: run.companyId, issueId: run.nativeIssueId!, runId: run.id }) + .catch(() => null); + if (!checkpoint) return false; + const { records } = checkpoint, read = (key: string) => record(JSON.parse(records.get(key)!)); + const keys = [...records.keys()], committedEvents: Record[] = []; + for (const key of keys.filter(key => key.startsWith("event:")).reverse()) { + const event = read(key); + committedEvents.unshift(event); + if (event.eventType === "run.terminal") break; + } + const identity = record(record(read("header").state).identity); + const control = { identity, commands: keys.filter(key => key.startsWith("command:")).map(read), committedEvents }; + return identity.runId === run.id && identity.normalizedSessionId === run.nativeSessionId + && identity.runnerInstanceId === run.runnerInstanceId && isSettledRemoteWarmControlState(control, identity); +} + +export async function publishStoppedNativeSession(db: Db, runId: string, + context: NativeTaskSessionPublicationContext): Promise { + const [observed] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).limit(1); + if (!observed?.nativeIssueId || !hasAcknowledgedNativeRunStopReceipt(observed)) return "stop_unproven"; + if (!settledSnapshot(observed)) return "turn_unsettled"; + if (await readProviderAttemptOutcome(db, { runId, sinceSeq: 0 }) === "provider_not_started") return "turn_not_started"; + if (!await journalSettled(db, observed)) return "journal_unsettled"; + const companyId = observed.companyId, issueId = observed.nativeIssueId; + return db.transaction(async tx => { + const [coordinator] = await tx.select().from(nativeRunFinalizations).where(and( + eq(nativeRunFinalizations.runId, runId), eq(nativeRunFinalizations.companyId, companyId), + eq(nativeRunFinalizations.issueId, issueId))).for("update").limit(1); + const [issue] = await tx.select().from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, companyId))) + .for("no key update").limit(1); + const [run] = await tx.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, runId), + eq(heartbeatRuns.companyId, companyId))).for("update").limit(1); + if (!run || run.status !== "cancelled" || run.runtimeMode !== "native" || !hasAcknowledgedNativeRunStopReceipt(run) + || coordinator?.phase !== "terminal_failure" || coordinator.failureCode !== "native_retry_cancelled" + || coordinator.resultId || coordinator.leaseOwner || coordinator.recoveryState) return "stop_unproven"; + const session = settledSnapshot(run); + if (!session) return "turn_unsettled"; + if (!issue || issue.conversationAgentId || context.taskKey !== issueId + || record(run.resultJson)[RUN_CONTENT_DELETED_MARKER]) return "unsupported_task"; + if (issue.executionRunId && issue.executionRunId !== runId) return "superseded"; + const leases = await tx.select().from(environmentLeases).where(and( + eq(environmentLeases.companyId, companyId), eq(environmentLeases.heartbeatRunId, runId))); + if (!sessionRetained(run, leases)) return "session_not_retained"; + const [row] = await tx.select().from(agentTaskSessions).where(and(eq(agentTaskSessions.companyId, companyId), + eq(agentTaskSessions.agentId, run.agentId), eq(agentTaskSessions.adapterType, context.adapterType), + eq(agentTaskSessions.taskKey, context.taskKey))).for("update").limit(1); + if (!row) return "session_row_missing"; + if (!row.goalSourceId?.endsWith(`:${runId}`) || !await taskSessionLinkReplaceable(tx, row.lastRunId, { + companyId, agentId: run.agentId, issueId, runId, startedAt: run.startedAt })) return "superseded"; + await tx.update(agentTaskSessions).set({ + sessionParamsJson: { ...context.sessionParamsJson, sessionId: session.sessionId }, + sessionDisplayId: session.displayId, lastRunId: runId, lastError: null, updatedAt: new Date(), + }).where(eq(agentTaskSessions.id, row.id)); + return "published"; + }); +} diff --git a/server/src/services/native-runtime/native-task-session-publication.ts b/server/src/services/native-runtime/native-task-session-publication.ts index ee61fc3e74e..2c2e8387e5d 100644 --- a/server/src/services/native-runtime/native-task-session-publication.ts +++ b/server/src/services/native-runtime/native-task-session-publication.ts @@ -67,6 +67,18 @@ export type NativeTaskSessionPublicationRun = Pick; +export async function taskSessionLinkReplaceable(tx: Transaction, lastRunId: string | null, owner: { + companyId: string; agentId: string; issueId: string; runId: string; startedAt: Date | null; +}): Promise { + if (!lastRunId || lastRunId === owner.runId) return true; + const [prior] = await tx.select({ companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId, + issueId: heartbeatRuns.issueId, nativeIssueId: heartbeatRuns.nativeIssueId, finishedAt: heartbeatRuns.finishedAt, + }).from(heartbeatRuns).where(eq(heartbeatRuns.id, lastRunId)).limit(1); + return Boolean(prior && prior.companyId === owner.companyId && prior.agentId === owner.agentId + && (prior.nativeIssueId ?? prior.issueId) === owner.issueId && prior.finishedAt && owner.startedAt + && prior.finishedAt <= owner.startedAt); +} + /** Caller holds coordinator → issue NO KEY UPDATE → run. This helper owns only * the task-row lock and UPDATE; never starts a transaction or creates a stub. */ export async function publishNativeTaskSessionInTransaction(tx: Transaction, input: { @@ -128,14 +140,8 @@ export async function publishNativeTaskSessionInTransaction(tx: Transaction, inp .filter((value): value is string => typeof value === "string" && value.length > 0) .map(source => `${source}:${binding.runId}`); if (!session.goalSourceId || !boundSources.includes(session.goalSourceId)) return receipt("suppressed_newer"); - if (session.lastRunId && session.lastRunId !== binding.runId) { - const [prior] = await tx.select({ companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId, - issueId: heartbeatRuns.issueId, nativeIssueId: heartbeatRuns.nativeIssueId, finishedAt: heartbeatRuns.finishedAt, - }).from(heartbeatRuns).where(eq(heartbeatRuns.id, session.lastRunId)).limit(1); - if (!prior || prior.companyId !== binding.companyId || prior.agentId !== binding.agentId - || (prior.nativeIssueId ?? prior.issueId) !== binding.issueId || !prior.finishedAt || !run.startedAt - || prior.finishedAt > run.startedAt) return receipt("suppressed_newer"); - } + if (!await taskSessionLinkReplaceable(tx, session.lastRunId, { companyId: binding.companyId, agentId: binding.agentId, + issueId: binding.issueId, runId: binding.runId, startedAt: run.startedAt })) return receipt("suppressed_newer"); await tx.update(agentTaskSessions).set({ sessionParamsJson: { ...context.sessionParamsJson, sessionId: snapshot.identity.sessionId }, sessionDisplayId: snapshot.providerSessionId ?? snapshot.sessionId, lastRunId: binding.runId,