diff --git a/doc/run-log-events.md b/doc/run-log-events.md index 28472e42ccf..92a8cddf543 100644 --- a/doc/run-log-events.md +++ b/doc/run-log-events.md @@ -320,11 +320,15 @@ section in the Observability contract. Cancelled runs retain `resultJson.cancellation`: a closed `source` label (`operator`, `queued_message`, `shutdown`, `provider`, `transport`, -`control_plane`, or `unknown`), whether the stop was expected, the initiator, -reason, and recording time. Recorded stop intent survives adapter completion. +`control_plane`, `controller_lease`, or `unknown`), whether the stop was expected, +the initiator, reason, and recording time. Recorded stop intent survives adapter +completion. `controller_lease` means the host stopped its own legacy adapter +after it lost the durable controller lease; the reason names a closed cause +(`renewal_rejected`, `renewal_deadline`, or `renewal_error`). The local lifecycle event includes this evidence. Started cancellations without an expected stop are also reported to Sentry; its cancellation diagnostics contain -only source, expectedness, and initiator type, never initiator IDs or reason text. +only source, expectedness, initiator type, and the closed lease-loss cause, never +initiator IDs or reason text. Historical ambiguous cancellations stay `unknown` and do not authorize replay. Provider tool-definition validation failures use diff --git a/server/src/services/__tests__/run-failure-report.test.ts b/server/src/services/__tests__/run-failure-report.test.ts index 111be4faf60..c4f5271e206 100644 --- a/server/src/services/__tests__/run-failure-report.test.ts +++ b/server/src/services/__tests__/run-failure-report.test.ts @@ -28,6 +28,7 @@ vi.mock("../../log-redaction.js", async (importOriginal) => { }); import { reportRunFailure, waitForPendingRunFailureReports } from "../run-failure-report.js"; +import { controllerLeaseLossCancellation } from "../run-cancellation.js"; import { REDACTED_EVENT_VALUE } from "../../redaction.js"; const testDatabaseUrl = process.env.PAPERCLIP_TEST_DATABASE_URL; @@ -742,6 +743,15 @@ describeEmbeddedPostgres("reportRunFailure", () => { diagnostics: { execution: { cancellationSource: source, cancellationExpected: false } } }); expect(JSON.stringify(mockCaptureRunFailure.mock.calls)).not.toMatch(/private-actor|private-reason/); }); + it("labels a host controller lease loss with its closed cause", async () => { + await seedCompanyAndAgent(); + await reportRunFailure(db, buildRun({ status: "cancelled", startedAt: new Date(0), finishedAt: new Date(1000), + resultJson: { cancellation: controllerLeaseLossCancellation("renewal_deadline") } })); + expect(mockCaptureRunFailure).toHaveBeenCalledOnce(); + expect(mockCaptureRunFailure.mock.calls[0][0]).toMatchObject({ diagnostics: { execution: { + cancellationSource: "controller_lease", cancellationExpected: false, controllerLeaseLossCause: "renewal_deadline" } } }); + expect(JSON.stringify(mockCaptureRunFailure.mock.calls)).not.toMatch(/Legacy controller lease lost/); + }); it("does not report an operator's Stop as a failure", async () => { await seedCompanyAndAgent(); await reportRunFailure(db, buildRun({ status: "cancelled", startedAt: new Date(0), resultJson: { diff --git a/server/src/services/heartbeat/run-completion.test.ts b/server/src/services/heartbeat/run-completion.test.ts index 4388cd4e4e2..beb1c545801 100644 --- a/server/src/services/heartbeat/run-completion.test.ts +++ b/server/src/services/heartbeat/run-completion.test.ts @@ -6,6 +6,8 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } fro import * as usageReceipts from "../usage-receipts.js"; import { createAgentIdentityRedactor } from "../agent-identity-redaction.js"; import { UnresolvedWorkspaceBaseRefError } from "../workspace-runtime.js"; +import { LegacyControllerLeaseLostError } from "../legacy-controller-lease.js"; +import { requestedRunCancellation } from "../run-cancellation.js"; import { createHeartbeatLifecycle, type HeartbeatLifecycleDependencies } from "./run-lifecycle.js"; import { createHeartbeatRunPreparation, ConfigurationIncompleteFailure } from "./run-preparation.js"; import { createHeartbeatRunState, getAdapterSessionCodec } from "./run-state.js"; @@ -155,6 +157,34 @@ describe.skipIf(!support.supported)("heartbeat run completion boundary", () => { } else expect(f.deps.finalizeAgentStatus).not.toHaveBeenCalled(); }); + it("attributes an adapter stop caused by a lost controller lease", async () => { + const f = await fixture(); + Object.assign(f.input.adapterResult, { exitCode: null, errorCode: "cancelled", errorMessage: "Grok execution was cancelled" }); + f.controller.abort(new LegacyControllerLeaseLostError("renewal_deadline")); + await f.completion.completeRun(f.input); + expect(await read(f.run.id)).toMatchObject({ status: "cancelled", resultJson: { cancellation: { + source: "controller_lease", expected: false, initiator: { type: "system" }, reason: "Legacy controller lease lost (renewal_deadline)" } } }); + }); + + it("attributes a lost controller lease when the adapter throws the abort reason", async () => { + const f = await fixture(); + f.controller.abort(new LegacyControllerLeaseLostError("renewal_rejected")); + await f.completion.failRun(f.failure(f.controller.signal.reason)); + expect(await read(f.run.id)).toMatchObject({ status: "cancelled", resultJson: { + workspaceRestoreFailure: { reason: "missing_base" }, + cancellation: { source: "controller_lease", expected: false, reason: "Legacy controller lease lost (renewal_rejected)" } } }); + }); + + it("keeps a stop requested before the lease loss when the adapter throws", async () => { + const f = await fixture(); + const requested = requestedRunCancellation({ cancelledByActorType: "user", cancelledByUserId: "operator-1" }, "Stopped from the board"); + await db.update(heartbeatRuns).set({ resultJson: { cancellation: requested } }).where(eq(heartbeatRuns.id, f.run.id)); + f.controller.abort(new LegacyControllerLeaseLostError("renewal_error")); + await f.completion.failRun(f.failure(f.controller.signal.reason)); + expect(await read(f.run.id)).toMatchObject({ status: "cancelled", resultJson: { cancellation: { + source: "operator", expected: true, initiator: { type: "user", id: "operator-1" }, reason: "Stopped from the board" } } }); + }); + it("does not publish or overwrite a conflicting terminal transition that wins the compare-and-set", async () => { const f = await fixture(); const write = f.deps.setRunStatusIfRunning.getMockImplementation()!; diff --git a/server/src/services/heartbeat/run-completion.ts b/server/src/services/heartbeat/run-completion.ts index abda3c7f216..970acf1881f 100644 --- a/server/src/services/heartbeat/run-completion.ts +++ b/server/src/services/heartbeat/run-completion.ts @@ -6,7 +6,8 @@ import { readGitConnectionFailure } from "../git-connection-failure.js"; import { CONFIGURATION_INCOMPLETE_FAILURE_CODE, ConfigurationIncompleteFailure } from "./run-preparation.js"; import { isWorkspaceValidationFailedRun, isWorkspaceValidationFailure, attachPaperclipSessionMetadataToSessionParams } from "./workspaces.js"; import { preserveWorkspaceRestoreRecoveryMetadataSql } from "../legacy-workspace-restore-recovery.js"; -import { cancellationResultJson, readRunCancellation } from "../run-cancellation.js"; +import { cancellationResultJson, controllerLeaseLossCancellation, readRunCancellation } from "../run-cancellation.js"; +import { LegacyControllerLeaseLostError } from "../legacy-controller-lease.js"; import { accountRunCost } from "../run-cost-accounting.js"; import { isConversation, settleConversationTurn } from "../agent-conversations.js"; import { legacyExecutionNeedsReconciliationWithEvidence } from "../legacy-execution-recovery.js"; @@ -316,6 +317,14 @@ function readNonEmptyString(value: unknown): string | null { return typeof value === "string" && value.trim().length > 0 ? value : null; } +// Attribute a stop the lease watchdog caused, whether the adapter returned +// or threw. A requested stop recorded earlier still wins in cancellationResultJson. +function controllerLeaseLossResultJson(signal: AbortSignal) { + return signal.reason instanceof LegacyControllerLeaseLostError + ? { cancellation: controllerLeaseLossCancellation(signal.reason.leaseLossCause) } + : {}; +} + export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunCompletionDependencies) { const { getRun, @@ -544,6 +553,7 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC ...(adapterResult.executionRecovery ? { executionRecovery: adapterResult.executionRecovery } : {}), + ...(outcome === "cancelled" ? controllerLeaseLossResultJson(signal) : {}), configFreshness: configFreshnessResultMetadata, }, errorFamily: adapterResult.errorFamily ?? null, @@ -1103,6 +1113,7 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC ...(workspaceValidationFailure?.resultJson ?? configurationIncompleteFailure?.resultJson ?? {}), + ...(stoppedDuringFailure ? controllerLeaseLossResultJson(signal) : {}), ...(!legacyAdapterEntered && run.runtimeMode !== "native" ? { executionRecovery: { diff --git a/server/src/services/heartbeat/run-state.test.ts b/server/src/services/heartbeat/run-state.test.ts index c9bb5e50011..b5194144be4 100644 --- a/server/src/services/heartbeat/run-state.test.ts +++ b/server/src/services/heartbeat/run-state.test.ts @@ -1,4 +1,4 @@ -import { randomUUID } from "node:crypto"; +import { randomBytes, randomUUID } from "node:crypto"; import type { Db } from "@paperclipai/db"; import { agents, @@ -8,7 +8,7 @@ import { heartbeatRuns, issues, } from "@paperclipai/db"; -import { eq, type SQL } from "drizzle-orm"; +import { eq, sql, type SQL } from "drizzle-orm"; import { PgDialect } from "drizzle-orm/pg-core"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { @@ -17,6 +17,7 @@ import { } from "../../__tests__/helpers/embedded-postgres.js"; import * as legacy from "../heartbeat.js"; import * as extracted from "./run-state.js"; +import { readRunCancellation } from "../run-cancellation.js"; // SQL_ASCII needs a separate database cluster. Inspect its selected SQL here; // the PostgreSQL tests below exercise the session queries and transactions. @@ -119,6 +120,24 @@ describePostgres("heartbeat run state database wiring", () => { return { companyId, agent, issue, state: extracted.createHeartbeatRunState(db) }; } + it("preserves controller lease cancellation when a large result is bounded", async () => { + const { companyId, agent, state } = await fixture(); + const cancellation = { + source: "controller_lease", expected: false, initiator: { type: "system" }, + reason: "Legacy controller lease lost (renewal_rejected)", recordedAt: "2026-01-01T00:00:00Z", + }; + const [run] = await db.insert(heartbeatRuns).values({ + companyId, agentId: agent.id, invocationSource: "assignment", status: "cancelled", + resultJson: { cancellation, providerPrivateData: randomBytes(96 * 1024).toString("hex") }, + }).returning(); + const [stored] = await db.select({ size: sql`pg_column_size(${heartbeatRuns.resultJson})` }) + .from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)); + expect(stored.size).toBeGreaterThan(64 * 1024); + const bounded = await state.getRun(run.id); + expect(bounded?.resultJson).not.toHaveProperty("providerPrivateData"); + expect(readRunCancellation(bounded?.resultJson)).toEqual(cancellation); + }); + it("resumes only the selected agent's run and task session", async () => { const { companyId, agent, issue, state } = await fixture(); const foreign = await fixture(); diff --git a/server/src/services/heartbeat/run-state.ts b/server/src/services/heartbeat/run-state.ts index 75961481cad..b10823270cd 100644 --- a/server/src/services/heartbeat/run-state.ts +++ b/server/src/services/heartbeat/run-state.ts @@ -233,7 +233,7 @@ const heartbeatRunSafeResultJsonColumn = sql | null>` 'cancellation', case when jsonb_typeof(${heartbeatRuns.resultJson} -> 'cancellation') = 'object' then jsonb_strip_nulls(jsonb_build_object( 'source', case when ${heartbeatRuns.resultJson} #>> '{cancellation,source}' - in ('operator', 'queued_message', 'shutdown', 'provider', 'transport', 'control_plane', 'unknown') + in ('operator', 'queued_message', 'shutdown', 'provider', 'transport', 'control_plane', 'controller_lease', 'unknown') then ${heartbeatRuns.resultJson} #> '{cancellation,source}' end, 'expected', case when jsonb_typeof(${heartbeatRuns.resultJson} #> '{cancellation,expected}') = 'boolean' then ${heartbeatRuns.resultJson} #> '{cancellation,expected}' end, diff --git a/server/src/services/legacy-controller-lease.test.ts b/server/src/services/legacy-controller-lease.test.ts index 6bceee0c4c6..d2e4b2e2c40 100644 --- a/server/src/services/legacy-controller-lease.test.ts +++ b/server/src/services/legacy-controller-lease.test.ts @@ -4,7 +4,7 @@ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { agents, companies, createDb, heartbeatRuns } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; import { heartbeatService } from "./heartbeat.js"; -import { hasLiveLegacyController, legacyControllerBootId, legacyControllerClaim, +import { hasLiveLegacyController, LEGACY_CONTROLLER_RENEW_MS, legacyControllerBootId, legacyControllerClaim, LegacyControllerLeaseLostError, renewLegacyControllerLease, revokeExpiredLegacyController, watchLegacyControllerLease } from "./legacy-controller-lease.js"; const support = await getEmbeddedPostgresTestSupport(); @@ -68,6 +68,8 @@ const support = await getEmbeddedPostgresTestSupport(); try { await expect(watch.assertOwned("dispatching")).rejects.toThrow("lease lost"); expect(controller.signal.aborted).toBe(true); + expect(controller.signal.reason).toBeInstanceOf(LegacyControllerLeaseLostError); + expect(controller.signal.reason.leaseLossCause).toBe("renewal_rejected"); } finally { watch.stop(); } }); it("only one competing recovery revokes the observed expired owner", async () => { @@ -111,6 +113,7 @@ const support = await getEmbeddedPostgresTestSupport(); await vi.advanceTimersByTimeAsync(101); await checked; expect(controller.signal.aborted).toBe(true); + expect(controller.signal.reason.leaseLossCause).toBe("renewal_deadline"); } finally { watch.stop(); vi.useRealTimers(); } }); @@ -118,3 +121,21 @@ const support = await getEmbeddedPostgresTestSupport(); expect(legacyControllerClaim("native")).toEqual({}); }); }); + +describe("legacy controller lease loss attribution", () => { + it("attributes a failing renewal query to renewal_error", async () => { + type WatchArgs = Parameters; + const failingDb = { update: () => ({ set: () => ({ where: () => ({ + returning: () => Promise.reject(new Error("connection reset")) }) }) }) } as unknown as WatchArgs[0]; + vi.useFakeTimers(); + const controller = new AbortController(); + const run = { id: randomUUID(), companyId: randomUUID(), runtimeMode: "legacy", controllerBootId: legacyControllerBootId, + controllerLeaseExpiresAt: new Date(Date.now() + 60_000) } as WatchArgs[1]; + const watch = watchLegacyControllerLease(failingDb, run, controller); + try { + await vi.advanceTimersByTimeAsync(LEGACY_CONTROLLER_RENEW_MS + 1); + expect(controller.signal.reason).toBeInstanceOf(LegacyControllerLeaseLostError); + expect(controller.signal.reason.leaseLossCause).toBe("renewal_error"); + } finally { watch.stop(); vi.useRealTimers(); } + }); +}); diff --git a/server/src/services/legacy-controller-lease.ts b/server/src/services/legacy-controller-lease.ts index 4fc746fe48c..f8ec824002c 100644 --- a/server/src/services/legacy-controller-lease.ts +++ b/server/src/services/legacy-controller-lease.ts @@ -1,6 +1,7 @@ import { randomUUID } from "node:crypto"; import { and, eq, gt, lte, sql } from "drizzle-orm"; import { heartbeatRuns, type Db } from "@paperclipai/db"; +import type { LegacyControllerLeaseLossCause } from "./run-cancellation.js"; // A boot UUID has meaning across containers; a numeric PID does not. export const legacyControllerBootId = randomUUID(); @@ -9,6 +10,14 @@ export const LEGACY_CONTROLLER_RENEW_MS = 10_000; type Run = typeof heartbeatRuns.$inferSelect; +/** Abort reason for a lost lease, so completion can attribute the stop. */ +export class LegacyControllerLeaseLostError extends Error { + constructor(readonly leaseLossCause: LegacyControllerLeaseLossCause) { + super("Legacy controller lease lost"); + this.name = "LegacyControllerLeaseLostError"; + } +} + /** Commit these fields in the same UPDATE that claims a queued run. */ export function legacyControllerClaim(runtimeMode: string) { if (runtimeMode === "native") return {}; @@ -70,8 +79,11 @@ export function watchLegacyControllerLease(db: Db, run: Run, controller: AbortCo } let stopped = false; let pending = false; - const lost = () => { if (!stopped) controller.abort(new Error("Legacy controller lease lost")); }; - let deadline = setTimeout(lost, Math.max(0, + const lost = (cause: LegacyControllerLeaseLossCause) => { + if (!stopped) controller.abort(new LegacyControllerLeaseLostError(cause)); + }; + const deadlinePassed = () => lost("renewal_deadline"); + let deadline = setTimeout(deadlinePassed, Math.max(0, (run.controllerLeaseExpiresAt?.getTime() ?? 0) - Date.now())); deadline.unref(); const assertOwned = async (stage?: "dispatching") => { @@ -91,20 +103,20 @@ export function watchLegacyControllerLease(db: Db, run: Run, controller: AbortCo } if (stopped) return; if (!renewed) { - lost(); + lost("renewal_rejected"); controller.signal.throwIfAborted(); } controller.signal.throwIfAborted(); if (!stopped) { clearTimeout(deadline); - deadline = setTimeout(lost, Math.max(0, LEGACY_CONTROLLER_LEASE_MS - (Date.now() - startedAt))); + deadline = setTimeout(deadlinePassed, Math.max(0, LEGACY_CONTROLLER_LEASE_MS - (Date.now() - startedAt))); deadline.unref(); } }; const timer = setInterval(() => { if (pending || stopped) return; pending = true; - void assertOwned().catch(lost).finally(() => { pending = false; }); + void assertOwned().catch(() => lost("renewal_error")).finally(() => { pending = false; }); }, LEGACY_CONTROLLER_RENEW_MS); timer.unref(); return { assertOwned, stop() { stopped = true; clearInterval(timer); clearTimeout(deadline); } }; diff --git a/server/src/services/run-cancellation.test.ts b/server/src/services/run-cancellation.test.ts index 18b66bcadce..3e7dbf5727f 100644 --- a/server/src/services/run-cancellation.test.ts +++ b/server/src/services/run-cancellation.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; -import { cancellationResultJson, canContinueCancelledRun, isUnexpectedRunCancellation, requestedRunCancellation } from "./run-cancellation.js"; +import { cancellationResultJson, canContinueCancelledRun, controllerLeaseLossCancellation, isUnexpectedRunCancellation, + readControllerLeaseLossCause, readRunCancellation, requestedRunCancellation } from "./run-cancellation.js"; describe("cancellation provenance", () => { const run = { status: "cancelled", runtimeMode: "legacy" as const, startedAt: new Date(0), finishedAt: new Date(1), @@ -19,6 +20,23 @@ describe("cancellation provenance", () => { expect(requestedRunCancellation({ queuedCommentInterruptQueueId: "queue", interruptedByActorType: "user", interruptedByActorId: "board" }, "Send messages")) .toMatchObject({ source: "queued_message", initiator: { type: "user", id: "board" } }); }); + it("attributes a host lease loss instead of reporting an unknown stop", () => { + const resultJson = cancellationResultJson(run, "cancelled", { + cancellation: controllerLeaseLossCancellation("renewal_deadline") }); + const cancellation = readRunCancellation(resultJson); + expect(cancellation).toMatchObject({ source: "controller_lease", expected: false, initiator: { type: "system" } }); + expect(readControllerLeaseLossCause(cancellation!)).toBe("renewal_deadline"); + expect(isUnexpectedRunCancellation({ ...run, resultJson })).toBe(true); + expect(canContinueCancelledRun({ ...run, resultJson: { ...resultJson, + acpToolInventoryComplete: true, acpPendingToolCount: 0 } })).toBe(false); + expect(readControllerLeaseLossCause({ ...cancellation!, reason: "Legacy controller lease lost (forged)" })).toBeNull(); + }); + it("keeps a recorded stop request over a later lease loss", () => { + const requested = requestedRunCancellation({}, "Stop"); + const resultJson = cancellationResultJson({ ...run, resultJson: { cancellation: requested } }, "cancelled", { + cancellation: controllerLeaseLossCancellation("renewal_rejected") }); + expect(resultJson?.cancellation).toEqual(requested); + }); it("requires positive provider evidence and a complete empty tool inventory for saved input", () => { const resultJson = cancellationResultJson(run, "cancelled", { status: "cancelled", acpToolInventoryComplete: true, acpPendingToolCount: 0 }); expect(resultJson?.cancellation).toMatchObject({ source: "provider", expected: false }); diff --git a/server/src/services/run-cancellation.ts b/server/src/services/run-cancellation.ts index b8cb8681a41..95a37aabfb4 100644 --- a/server/src/services/run-cancellation.ts +++ b/server/src/services/run-cancellation.ts @@ -1,7 +1,7 @@ import type { heartbeatRuns } from "@paperclipai/db"; type Run = Pick; -const SOURCES = ["operator", "queued_message", "shutdown", "provider", "transport", "control_plane", "unknown"] as const; +const SOURCES = ["operator", "queued_message", "shutdown", "provider", "transport", "control_plane", "controller_lease", "unknown"] as const; export type CancellationSource = typeof SOURCES[number]; export interface RunCancellation { source: CancellationSource; @@ -39,6 +39,22 @@ export function requestedRunCancellation(result: Run["resultJson"], reason: stri }, reason: reason.slice(0, 512), recordedAt: new Date().toISOString() }; } +const LEGACY_CONTROLLER_LEASE_LOSS_CAUSES = ["renewal_rejected", "renewal_deadline", "renewal_error"] as const; +export type LegacyControllerLeaseLossCause = typeof LEGACY_CONTROLLER_LEASE_LOSS_CAUSES[number]; +const controllerLeaseLossReason = (cause: LegacyControllerLeaseLossCause) => `Legacy controller lease lost (${cause})`; + +/** The host aborted its own adapter after losing durable run ownership. */ +export function controllerLeaseLossCancellation(cause: LegacyControllerLeaseLossCause): RunCancellation { + return { source: "controller_lease", expected: false, initiator: { type: "system" }, + reason: controllerLeaseLossReason(cause), recordedAt: new Date().toISOString() }; +} + +/** Closed cause label for diagnostics; only the server-written reason matches. */ +export function readControllerLeaseLossCause(cancellation: RunCancellation): LegacyControllerLeaseLossCause | null { + if (cancellation.source !== "controller_lease") return null; + return LEGACY_CONTROLLER_LEASE_LOSS_CAUSES.find(cause => cancellation.reason === controllerLeaseLossReason(cause)) ?? null; +} + /** Preserve recorded stop intent when adapter completion replaces resultJson. */ export function cancellationResultJson(run: Run, status: string, patch?: Run["resultJson"], errorCode?: string | null, error?: string | null): Run["resultJson"] { if (status !== "cancelled" && status !== "interrupted") return patch ?? run.resultJson; diff --git a/server/src/services/run-failure-diagnostics.ts b/server/src/services/run-failure-diagnostics.ts index ae9614a09af..f277481cc70 100644 --- a/server/src/services/run-failure-diagnostics.ts +++ b/server/src/services/run-failure-diagnostics.ts @@ -1,7 +1,7 @@ import { readWorkspaceBaseRefDiagnostic } from "./workspace-base-ref-diagnostics.js"; import { getEnvironmentAcquisitionDiagnostic } from "./environment-acquisition-diagnostics.js"; import type { heartbeatRuns } from "@paperclipai/db"; -import { readRunCancellation } from "./run-cancellation.js"; +import { readControllerLeaseLossCause, readRunCancellation } from "./run-cancellation.js"; import { readProcessLossDiagnostic } from "./process-loss-diagnostics.js"; import { WORKSPACE_RESTORE_FAILURE_CODES } from "@paperclipai/shared"; import { redactDiagnosticText } from "@paperclipai/adapter-utils/command-redaction"; @@ -199,6 +199,8 @@ export function collectRunFailureDiagnostics(run: Run, options: RunFailureReport execution.cancellationSource = cancellation.source; execution.cancellationExpected = cancellation.expected; execution.cancellationInitiatorType = cancellation.initiator.type; + const leaseLossCause = readControllerLeaseLossCause(cancellation); + if (leaseLossCause) execution.controllerLeaseLossCause = leaseLossCause; } else if (run.status === "cancelled") { execution.cancellationSource = "unknown"; execution.cancellationExpected = false;