From a64969b2883412343393c5192bb717ba42de4446 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Tue, 13 Oct 2026 14:50:40 -0700 Subject: [PATCH] fix(server): attribute legacy runs stopped by controller lease loss (#16084) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The heartbeat runner executes legacy agent runs. A controller lease watchdog keeps durable ownership of each legacy run. > - When the watchdog loses the lease, it aborts the adapter. The abort reason was a plain `Error`, and nothing recorded why the run stopped. > - Completion then saved the cancellation as source `unknown`. Sentry got an unexpected cancel that it could not tell apart from other unrecorded stops. > - We saw this on a sandboxed Grok run. The system cancelled it after about 22 minutes with `cancellationSource: unknown`. Workspace copy-back then failed. Every `cancelRun` path records a stop request, so an unrecorded stop this late points to the lease watchdog. > - This pull request records a lease loss as its own cancellation source, with a closed cause label. > - The benefit is that the next event shows whether the lease loss caused the stop, and which renewal failure caused it. That is the missing fact to fix the root cause. ## Linked Issues or Issue Description Refs #15790 Refs #15920 **What happened?** A legacy sandbox run was stopped by the system while it was working. The run record and the Sentry diagnostics show `cancellationSource: unknown`, with no initiator. The controller lease watchdog aborts the adapter with a plain `Error("Legacy controller lease lost")`. Completion does not read the abort reason, so it records the stop as `unknown`. **Expected behavior** When the host stops its own adapter because it lost the controller lease, the run records that cause. Diagnostics name the cause with a closed label. A stop that a user or the control plane requested earlier keeps its recorded source. **Steps to reproduce** 1. Start a legacy run that has a controller lease. 2. Make lease renewal fail: the renewal query errors, the update matches no row, or the lease deadline passes. 3. Let the adapter return its cancelled result. 4. Read `resultJson.cancellation` on the run. Before this change, `source` is `unknown`. **Agent adapter(s) involved** Not adapter-specific (core bug). We saw it with `grok_local` in a sandbox. **Additional context** This change adds diagnostics. It does not prevent the lease loss. #15920 retries a transient copy-back failure. It does not help here, because the stopped sandbox rejects every retry. ## What Changed - `legacy-controller-lease.ts`: The watchdog aborts with a new `LegacyControllerLeaseLostError`. The error carries a closed cause: `renewal_rejected`, `renewal_deadline`, or `renewal_error`. - `run-cancellation.ts`: Add the `controller_lease` cancellation source. Add `controllerLeaseLossCancellation()` and `readControllerLeaseLossCause()`. The reader accepts only the server-written reason text. - `heartbeat/run-completion.ts`: When the outcome is `cancelled` and the abort reason is a lease loss, record a `controller_lease` cancellation (`expected: false`). This covers both an adapter that returns a cancelled result (`completeRun`) and one that throws after the abort, for example through `signal.throwIfAborted()` (`failRun`). A stop request recorded earlier still takes precedence. - `run-failure-diagnostics.ts`: Add `controllerLeaseLossCause` to the execution diagnostics. Only the closed label goes to Sentry, never the reason text. - `heartbeat/run-state.ts`: preserve `controller_lease` in the bounded SQL projection when saved results exceed 64 KB. A database regression verifies the default run-detail read. - `canContinueCancelledRun` stays unchanged. It does not accept `controller_lease`, so a lease loss does not authorize automatic continuation. - `doc/run-log-events.md`: Document the new source and cause labels. - Tests: unit tests for the cause on each watchdog path, completion tests that record the source when the adapter returns and when it throws the abort reason (both fail without the change), tests that a recorded stop request takes precedence, and a test that the Sentry report contains the closed label and not the reason text. ## Verification - `cd server && npx vitest run src/services/run-cancellation.test.ts src/services/legacy-controller-lease.test.ts src/services/__tests__/run-failure-report.test.ts src/services/heartbeat/run-completion.test.ts`: 238 passed, including the embedded Postgres suites. - I reverted only `run-completion.ts` and ran the new completion test. It failed with `source: "unknown"`. With the change, it records `controller_lease`. - I removed only the `failRun` attribution and ran the new thrown-error test. It failed without the `controller_lease` record, and passes with it. - Final full repository `pnpm -r typecheck` and `pnpm build` pass. - Final local regression verification: all 247 tests pass across run-state, cancellation, watchdog, failure reporting, and completion suites. The large-result test fails before the SQL allowlist change. All latest-head CI checks pass (54 successes and two intentional skips). Fresh Apex is 5/5 on `708856c568d07d7b446a4a4af2edc6d9eec7d155` with no unresolved findings. ## Risks - Low risk. The change adds a new source value to server-owned JSON. Old rows keep their values. The readers accept the new value, and no UI code switches on this field. - A lease-loss cancel stays `expected: false`, so it is still reported as unexpected, as before. Now it has a more specific source. - The Sentry payload gets one new closed label (`controllerLeaseLossCause`). It does not include reason text or IDs. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, test runs). OpenAI GPT-6 (`gpt-6`) through Codex added the large-result regression and SQL projection fix, with shell, file-edit, and test tools. The exact context-window size is not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 Co-authored-by: Paperclip --- doc/run-log-events.md | 10 +++++-- .../__tests__/run-failure-report.test.ts | 10 +++++++ .../services/heartbeat/run-completion.test.ts | 30 +++++++++++++++++++ .../src/services/heartbeat/run-completion.ts | 13 +++++++- .../src/services/heartbeat/run-state.test.ts | 23 ++++++++++++-- server/src/services/heartbeat/run-state.ts | 2 +- .../services/legacy-controller-lease.test.ts | 23 +++++++++++++- .../src/services/legacy-controller-lease.ts | 22 ++++++++++---- server/src/services/run-cancellation.test.ts | 20 ++++++++++++- server/src/services/run-cancellation.ts | 18 ++++++++++- .../src/services/run-failure-diagnostics.ts | 4 ++- 11 files changed, 159 insertions(+), 16 deletions(-) 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;