From b5447432bd0de18398aab67b5294702f87b3b9e8 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:15:17 -0600 Subject: [PATCH 1/5] fix(ui): keep the active company on Cases and Status navigation links (#21794) 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 board UI builds company-prefixed links, such as `/PAP/cases`, from short paths in the sidebar > - The Cases and Status links use `/cases` and `/status`, but these roots were not in the board route list > - The router read `cases` as a company prefix and left the link unprefixed, so the link only worked through the unprefixed redirect > - When a person clicked Cases before the company list loaded, the redirect picked an arbitrary company and showed its empty case list > - The same race made `tests/e2e/cases-read-only.spec.ts` fail in "ci / e2e shard (2/8)" on unrelated PRs (#21683, #21715, #21765) > - This pull request adds both roots to the board route list and makes the e2e test force the race > - The benefit is that Cases and Status always open in the company the person is in, and the flaky e2e test becomes deterministic ## Linked Issues or Issue Description Refs #21683 Refs #21715 Refs #21765 **What happened?** The read-only Cases e2e test failed about once per day with `Expected: 3, Received: 0` links in the case list (job 132875164249 on #21765, job 132680942843 on #21715). The failure screenshot shows the sidebar of a different company ("Passive artifacts …", created by the previous spec) and "No cases yet". The server log shows that the page asked for the cases of the other company and never for the test company. **Expected behavior** A click on the Cases or Status link opens that page for the company in the URL, also when the click happens before the company list has loaded. **Steps to reproduce** 1. Have two or more companies. 2. Open `//issues` on a slow connection (the e2e test holds `GET /api/companies`). 3. Before the company list loads, open More and click Cases. 4. The URL becomes `/cases`. When the list loads, the app redirects to `//cases` and shows another company's empty case list. **Paperclip version or commit** `master` at 46e5e4450f. ## What Changed - `ui/src/lib/company-routes.ts`: add `cases` and `status` to `BOARD_ROUTE_ROOTS`, so `applyCompanyPrefix("/cases", "PAP")` returns `/PAP/cases`. Remove the part of the `caseHref` doc comment that described the old behavior. - `ui/src/lib/company-routes.test.ts`: unit test for both roots (red before the fix, green after). - `tests/e2e/cases-read-only.spec.ts`: hold `GET /api/companies` until the Cases link is clicked, then require the URL `//cases`. Without the fix the URL is `/cases`, so the test fails every time instead of sometimes. ## Verification - `cd ui && npx vitest run src/lib/company-routes.test.ts src/App.cases-routing.test.tsx src/lib/router.company-task-link.test.tsx`: 23 passed. The new test failed on `master` (2 failed). - E2E, before the fix (spec change only): `npx playwright test --config tests/e2e/playwright.config.ts tests/e2e/cases-read-only.spec.ts --repeat-each=5`: 5 of 5 failed with `Received string: "http://127.0.0.1:3199/cases"`. - E2E, after the fix: same command with `--repeat-each=50` on a loaded machine (load average 6 to 12): 50 of 50 passed. - The e2e config starts its own server on port 3199 (`reuseExistingServer: false`) with a fresh `mkdtemp` home and its own embedded PostgreSQL data directory, so these runs did not touch any other instance. ## Risks - Low risk. A company whose issue prefix is exactly `CASES` or `STATUS` now gets the same treatment as a company named after any other board route (for example `TASKS`): a bare `/CASES` path is read as the Cases page. The existing `//issues` exception still applies. - No API, schema, or migration change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, local Playwright runs). ## 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 - [ ] All Paperclip CI gates are green - [ ] 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: Claude Opus 5.5 --- tests/e2e/cases-read-only.spec.ts | 8 ++++++++ ui/src/lib/company-routes.test.ts | 8 ++++++++ ui/src/lib/company-routes.ts | 7 ++----- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/tests/e2e/cases-read-only.spec.ts b/tests/e2e/cases-read-only.spec.ts index 22183302f14..b40226ea49e 100644 --- a/tests/e2e/cases-read-only.spec.ts +++ b/tests/e2e/cases-read-only.spec.ts @@ -76,9 +76,17 @@ test("browses passive cases and rolled-up task documents without starting work o await page.setViewportSize({ width: 1440, height: 1000 }); // The agentless dashboard offers onboarding. Start on the ordinary task // list so this zero-agent fixture can use Cases navigation without setup. + let releaseCompanies!: () => void; + const companiesHeld = new Promise(resolve => { releaseCompanies = resolve; }); + await page.route(url => url.pathname === "/api/companies", async route => { + await companiesHeld; + await route.continue(); + }); await page.goto(`/${company.issuePrefix}/issues`); await page.getByRole("button", { name: "More workspace pages", exact: true }).click(); await page.getByRole("link", { name: /^Cases\b/ }).first().click(); + await expect(page).toHaveURL(new RegExp(`/${company.issuePrefix}/cases$`)); + releaseCompanies(); const casePage = page.getByTestId("case-pages"); const list = page.getByRole("region", { name: "Case list", exact: true }); const choose = async (filter: string, option: string) => { diff --git a/ui/src/lib/company-routes.test.ts b/ui/src/lib/company-routes.test.ts index 0b2631debe6..713b55ff4d7 100644 --- a/ui/src/lib/company-routes.test.ts +++ b/ui/src/lib/company-routes.test.ts @@ -139,6 +139,14 @@ describe("company routes", () => { expect(toCompanyRelativePath("/PAP/timeline")).toBe("/timeline"); }); + it.each(["cases", "status"])("keeps the active company on /%s navigation links", (root) => { + expect(isBoardPathWithoutPrefix(`/${root}`)).toBe(true); + expect(extractCompanyPrefixFromPath(`/${root}`)).toBeNull(); + expect(applyCompanyPrefix(`/${root}`, "PAP")).toBe(`/PAP/${root}`); + expect(applyCompanyPrefix(`/PAP/${root}`, "REA")).toBe(`/PAP/${root}`); + expect(toCompanyRelativePath(`/PAP/${root}`)).toBe(`/${root}`); + }); + it("treats Skill Studio create mode as an unprefixed board route", () => { expect(isBoardPathWithoutPrefix("/skills/studio/new")).toBe(true); expect(extractCompanyPrefixFromPath("/skills/studio/new")).toBeNull(); diff --git a/ui/src/lib/company-routes.ts b/ui/src/lib/company-routes.ts index 34012edc128..5b0b2c6c818 100644 --- a/ui/src/lib/company-routes.ts +++ b/ui/src/lib/company-routes.ts @@ -31,6 +31,8 @@ const BOARD_ROUTE_ROOTS = new Set([ "search", "settings", "timeline", + "cases", + "status", ]); const GLOBAL_ROUTE_ROOTS = new Set(["auth", "invite", "board-claim", "cli-auth", "mcp-connect", "dot-connect", "assistant-connections", "docs", "instance"]); @@ -93,11 +95,6 @@ export function applyCompanyPrefix(path: string, companyPrefix: string | null | * Build a company-prefixed href for an experimental Cases route, e.g. * `caseHref("PAP", "PAP-C5")` → `/PAP/cases/PAP-C5`. * - * Case paths carry identifiers like `PAP-C5` in the first segment, which the - * generic {@link applyCompanyPrefix} mistakes for a company prefix ("CASES") and - * therefore leaves `/cases/...` unprefixed — every case link then only resolves - * via the PAP-13002 unprefixed→prefixed redirect. This builder emits the - * prefixed href directly so case-to-case navigation matches the rest of the app. * Falls back to the unprefixed path (still valid via the redirect) when no * company is active. */ From c6cdd57f7abac954158347b99957a8e858a50334 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:07:56 -0600 Subject: [PATCH 2/5] perf(native-runtime): reuse a same-content image provider pack across builds (#21784) 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 > - A remote agent run needs the provider pack (Node, OpenCode and the Runner bridge) inside its sandbox before the provider can start > - The server reuses a pack that is installed in the sandbox image only when its full manifest equals the server's own manifest > - The manifest includes `runnerSourceRevision`, which is the commit that built the server, so an image pack fails this check on every later server build, also when every file in the pack is the same > - The run then uploads the whole pack again, which cost about 15 s per task in a recent load test > - This pull request accepts an image pack whose sealed content equals the expected pack and that differs only in build provenance, and caches verified archive hashes in the server process > - The benefit is that a sandbox image stays usable across server releases that do not change the pack, and the server does less hashing on its main thread ## Linked Issues or Issue Description Refs #21781 (merged), which names the failed check on the run spans. **What existing behavior does this improve?** Selection of the remote provider pack for a new sandbox (`provider_pack.select`). **Subsystem affected** Server: native runtime, remote provider pack verification and upload. **Current behavior** `provider_pack.verify_preinstalled` compares the complete manifest of the image pack with the server's manifest. Any difference fails, including `runnerSourceRevision` and `runnerInputsDigest`, which only record where the pack was built. The run then uploads the full pack. The server also hashes the same archive or pack directory again for every task. **Proposed behavior** When the run is not bound to a saved pack and the operator did not select a custom pack, the remote verification accepts an image pack when (1) its own digest seals its payload, and (2) its schema and payload equal the expected pack after the two provenance fields are removed. Every artifact, the `dist` tree, the candidate trees, the package versions, the Node version, the target platform and the OpenCode version are still checked in the sandbox, against the same values. The server checks the reported manifest again and selects it through the pack authority, as the compatibility path already does. An upload still happens for different content, a corrupted or partial pack, or no pack. The server also remembers a verified transport archive (by path, inode, size and times), so it does not hash it again for the next task. **Reason and benefit** In the harness (fake sandbox, 150 ms per command, 300 ms + 10 MiB/s per transfer, 24 MiB pack), the cross-build case goes from 4.1 s and 24 MiB uploaded to 1.1 s and 0 bytes. Other cases do not change. **Breaking changes** None. A saved or reattached session, and an operator-selected custom pack, still require the exact pack identity. ## What Changed - `remote-provider-pack-verification.ts`: new `acceptProvenance` option. The remote script accepts a sealed pack with the same content and prints its manifest. The server checks that manifest (`sameContentManifest`) and returns it. A forged or different report fails with `installed_manifest_invalid`. - `native-session-executor.ts` (`prepareRemoteProviderPackOnTarget`): staged and preinstalled verification use the option when `acceptProvenanceDifferences` is set. The function returns the selected manifest. The run caller sets the option only through `providerPackProvenanceReuseAllowed` (not retained, no explicit custom pack, selectable authority), and selects a different manifest through the pack authority. - `provider-pack-layers.ts`: `verifyArchive` skips the hash for an archive it already verified with the same file identity. - `remote-provider-pack.ts`: `providerPackProvenanceReuseAllowed` gate, with tests for each case. - `provider-pack-selection-harness.test.ts`: new harness. Uploads go through the workspace confinement check of the Daytona sync guard. It runs the real remote verification in local processes, with modelled sandbox latency and transfer speed, for five cases, before and after. ## Verification - `cd server && npx vitest run src/services/native-runtime/provider-pack-selection-harness.test.ts src/services/native-runtime/provider-pack-archive.test.ts src/services/native-runtime/remote-provider-pack-verification.test.ts src/services/native-runtime/remote-provider-pack.test.ts src/services/native-runtime/retained-provider-pack-source.test.ts src/__tests__/kimi-connection-probe.test.ts` passes. - `npx vitest run src/services/native-runtime/native-session-executor.test.ts src/services/native-runtime/native-artifact-preparation.test.ts src/services/native-runtime/remote-provider-pack-authority.test.ts` passes (1541 passed, 7 skipped). - Red/green: with the source changes reverted, the harness case `same_content_other_build` and the archive cache test fail. With the changes, they pass. - Harness output (load average about 9 on a shared machine; modelled time = wall time + modelled sandbox latency): | Case | Before | After | | --- | --- | --- | | Exact image pack | preinstalled, 1.1 s, 0 MiB | preinstalled, 1.0 s, 0 MiB | | Same content, other build | uploaded, 4.1 s, 24 MiB | preinstalled, 1.1 s, 0 MiB | | Different content | uploaded, 4.1 s, 24 MiB | uploaded, 4.0 s, 24 MiB | | Corrupted image pack | uploaded, 4.0 s, 24 MiB | uploaded, 4.1 s, 24 MiB | | No image pack | uploaded, 3.7 s, 24 MiB | uploaded, 3.8 s, 24 MiB | - The pack step runs no database statements. - `npx tsc --noEmit -p server/tsconfig.json` passes. ## Risks - This changes which provider pack the server accepts. It accepts a different manifest digest only when all content fields are equal and every file is hashed in the sandbox, and only for a run that is not bound to a saved pack. The selected manifest goes through the existing pack authority, so launch profiles and receipts bind the installed pack's own identity. - The archive hash cache trusts each archive file's identity (inode, size, times) on the server. The sandbox still checks the uploaded bundle digest and verifies every uploaded file, so a changed local file still fails closed. - This does not help when the image pack has other content (for example a different contract digest). See the hand-off notes for the image build. > 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 - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## 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 - [ ] All Paperclip CI gates are green - [ ] 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: Claude Opus 5.5 --- .../native-runtime/native-session-executor.ts | 29 ++- .../provider-pack-archive.test.ts | 20 ++ .../native-runtime/provider-pack-layers.ts | 8 + .../provider-pack-selection-harness.test.ts | 188 ++++++++++++++++++ .../remote-provider-pack-verification.test.ts | 18 ++ .../remote-provider-pack-verification.ts | 38 +++- .../remote-provider-pack.test.ts | 13 +- .../native-runtime/remote-provider-pack.ts | 9 + 8 files changed, 307 insertions(+), 16 deletions(-) create mode 100644 server/src/services/native-runtime/provider-pack-selection-harness.test.ts diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index a225db8c5a7..c16a79bc208 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -130,7 +130,7 @@ import { copyBackCodexAuth } from "@paperclipai/adapter-codex-local/server"; import { nativeCompletionFeedback } from "./native-completion-feedback.js"; import { hasAcknowledgedNativeLifecycleStopIntent, hasAcknowledgedNativeReassignmentStopIntent, hasAcknowledgedNativeStopIntent, hasAcknowledgedNativeRunStopReceipt } from "../acknowledged-native-stop.js"; import { stoppedCodexTurnIsTextOnly } from "./stopped-codex-turn.js"; -import { prepareVerifiedRemoteProviderPack, useVerifiedPreinstalledRemoteProviderPack, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js"; +import { prepareVerifiedRemoteProviderPack, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js"; import { uploadVerifiedProviderPack } from "./provider-pack-upload.js"; import { selectRemotePiCompanion } from "./remote-pi-companion.js"; import { scheduledResumeContinuationAllowed } from "./scheduled-resume-continuation.js"; @@ -14672,6 +14672,7 @@ export async function prepareRemoteProviderPackOnTarget(input: { signal?: AbortSignal; trace?: NativeRunTrace; onLog?: (stream: "stdout" | "stderr", chunk: string) => void | Promise; + acceptProvenanceDifferences?: boolean; }): Promise<{ root: string; manifest: RemoteProviderPackManifest; source: "staged" | "preinstalled" | "uploaded" }> { const remoteTarget = input.target, remoteCommandRunner = input.runner; const configuredProviderPackRoot = input.configuredProviderPackRoot; @@ -14679,10 +14680,10 @@ export async function prepareRemoteProviderPackOnTarget(input: { const stagedRemoteProviderPackRoot = posix.join(remoteTarget.remoteCwd, ".paperclip-runtime", "paperclip-runner", "provider-pack"); let activeRemoteProviderPackRoot: string | null = null; let preinstalledProviderPackRoots: string[] = []; - const verifyRemoteProviderPack = async (packRoot: string) => { - await verifyRemoteProviderPackIdentity({ runner: remoteCommandRunner, - cwd: remoteTarget.remoteCwd, packRoot, manifest: expectedProviderPackManifest }); - }; + let selectedProviderPackManifest = expectedProviderPackManifest; + const verifyRemoteProviderPack = (packRoot: string, acceptProvenance = false) => + verifyRemoteProviderPackIdentity({ runner: remoteCommandRunner, cwd: remoteTarget.remoteCwd, packRoot, + manifest: expectedProviderPackManifest, acceptProvenance: acceptProvenance && input.acceptProvenanceDifferences === true }); const discoverPreinstalledProviderPack = async () => { if (!remoteTarget || !remoteCommandRunner) return []; const result = await remoteCommandRunner.execute({ @@ -14704,16 +14705,16 @@ export async function prepareRemoteProviderPackOnTarget(input: { verifyStaged: () => measureNativeRunnerSpan( input.trace, "provider_pack.verify", - () => verifyRemoteProviderPack(stagedRemoteProviderPackRoot), + async () => { selectedProviderPackManifest = await verifyRemoteProviderPack(stagedRemoteProviderPackRoot, true); }, ), usePreinstalled: async (onRejected) => useVerifiedPreinstalledRemoteProviderPack({ onRejected, candidates: preinstalledProviderPackRoots = await measureNativeRunnerSpan(input.trace, "provider_pack.discover", discoverPreinstalledProviderPack), verifyAndLink: async (preinstalledProviderPack) => { - await measureNativeRunnerSpan( + const preinstalledManifest = await measureNativeRunnerSpan( input.trace, "provider_pack.verify_preinstalled", - () => verifyRemoteProviderPack(preinstalledProviderPack), + () => verifyRemoteProviderPack(preinstalledProviderPack, true), ); const escapedSource = preinstalledProviderPack.replaceAll( "'", @@ -14740,6 +14741,7 @@ export async function prepareRemoteProviderPackOnTarget(input: { throw providerPackIncompatible("link_failed", "preinstalled provider pack could not be linked"); } activeRemoteProviderPackRoot = stagedRemoteProviderPackRoot; + selectedProviderPackManifest = preinstalledManifest; await input.onLog?.( "stderr", "[paperclip-runner] using manifest-matched preinstalled provider pack\n", @@ -14774,9 +14776,10 @@ export async function prepareRemoteProviderPackOnTarget(input: { targetPath: stagedRemoteProviderPackRoot, mode: 0o700, }), - verifyUploaded: () => verifyRemoteProviderPack(stagedRemoteProviderPackRoot), + verifyUploaded: async () => { await verifyRemoteProviderPack(stagedRemoteProviderPackRoot); }, }); activeRemoteProviderPackRoot = stagedRemoteProviderPackRoot; + selectedProviderPackManifest = expectedProviderPackManifest; }, }); activeRemoteProviderPackRoot = stagedRemoteProviderPackRoot; @@ -14786,7 +14789,7 @@ export async function prepareRemoteProviderPackOnTarget(input: { "[paperclip-runner] reusing manifest-matched provider pack from the workspace\n", ); } - return { root: activeRemoteProviderPackRoot!, manifest: expectedProviderPackManifest, source: packSource }; + return { root: activeRemoteProviderPackRoot!, manifest: selectedProviderPackManifest, source: packSource }; } /** Read selection identity only; verify controller contents only if upload is needed. */ @@ -17214,7 +17217,13 @@ async function createRunnerdBackendWithinSessionClaim( target: remoteTarget, runner: remoteCommandRunner, configuredProviderPackRoot, manifest: expectedProviderPackManifest, trace: input.trace, onLog: input.onLog, signal: sourceSignals.length ? AbortSignal.any(sourceSignals) : undefined, + acceptProvenanceDifferences: providerPackProvenanceReuseAllowed({ retainProviderPack, explicitProviderPackSelection, + authoritySelectable: providerPackAuthority !== null }), }); + if (prepared.manifest.digest !== expectedProviderPackManifest.digest) { + providerPackAuthority!.select(prepared.manifest); + expectedProviderPackManifest = prepared.manifest; + } activeRemoteProviderPackRoot = prepared.root; providerPackVerified = true; } diff --git a/server/src/services/native-runtime/provider-pack-archive.test.ts b/server/src/services/native-runtime/provider-pack-archive.test.ts index ee891ed4925..70462a6d46a 100644 --- a/server/src/services/native-runtime/provider-pack-archive.test.ts +++ b/server/src/services/native-runtime/provider-pack-archive.test.ts @@ -69,6 +69,7 @@ it("keeps historical/source packs without an archive on the existing path", asyn it.each(["v1", "v2"])("cancels a real %s archive hash after its first read chunk", async version => { const { pack } = version === "v2" ? await layeredFixture() : await fixture(); const archivePath = version === "v2" ? `${pack}.archives/overlay.tar.zst` : `${pack}.tar.zst`; + await fs.utimes(archivePath, new Date(), new Date(Date.now() + 60_000)); const controller = new AbortController(); const handle = await fs.open(archivePath, "r"); const prototype = Object.getPrototypeOf(handle) as typeof handle; @@ -85,6 +86,25 @@ it.each(["v1", "v2"])("cancels a real %s archive hash after its first read chunk } finally { streaming.mockRestore(); } }); +it("hashes an unchanged verified archive once per server process and again after it changes", async () => { + const { pack } = await fixture(); + const archivePath = `${pack}.tar.zst`; + const handle = await fs.open(archivePath, "r"); + const prototype = Object.getPrototypeOf(handle) as typeof handle; + await handle.close(); + const streaming = vi.spyOn(prototype, "createReadStream"); + try { + await expect(readProviderPackArchive(pack, digest)).resolves.toMatchObject({ sourcePath: archivePath }); + expect(streaming).not.toHaveBeenCalled(); + const original = await fs.readFile(archivePath); + const corrupted = Buffer.from(original); + corrupted[corrupted.length - 1] ^= 0xff; + await fs.writeFile(archivePath, corrupted); + await expect(readProviderPackArchive(pack, digest)).rejects.toThrow("sha256_mismatch"); + expect(streaming).toHaveBeenCalledOnce(); + } finally { streaming.mockRestore(); } +}); + async function layeredFixture() { const { root, pack } = await fixture(); await fs.writeFile(path.join(pack, "bin", "large"), Buffer.alloc(1024 * 1024, 42), { mode: 0o755 }); diff --git a/server/src/services/native-runtime/provider-pack-layers.ts b/server/src/services/native-runtime/provider-pack-layers.ts index c2b8382e15b..090181fdab2 100644 --- a/server/src/services/native-runtime/provider-pack-layers.ts +++ b/server/src/services/native-runtime/provider-pack-layers.ts @@ -28,6 +28,10 @@ const validArchive = (value: unknown): value is Archive => { export const invalidArchive = (reason: string, cause?: unknown) => new Error(`runner_remote_provider_archive_invalid: ${reason}`, cause === undefined ? undefined : { cause }); +const verifiedArchives = new Set(); +const archiveIdentity = (path: string, expected: Archive, metadata: { dev: number; ino: number; size: number; mtimeMs: number; ctimeMs: number }) => + [path, expected.sha256, metadata.dev, metadata.ino, metadata.size, metadata.mtimeMs, metadata.ctimeMs].join("\0"); + export async function verifyArchive(path: string, expected: Archive, signal?: AbortSignal) { signal?.throwIfAborted(); let file; @@ -37,10 +41,14 @@ export async function verifyArchive(path: string, expected: Archive, signal?: Ab const metadata = await file.stat(); if (!metadata.isFile()) throw invalidArchive("archive_not_file"); if (metadata.size !== expected.bytes) throw invalidArchive("size_mismatch"); + const identity = archiveIdentity(path, expected, metadata); + if (verifiedArchives.has(identity)) return; const hash = createHash("sha256"); for await (const chunk of file.createReadStream({ autoClose: false, signal })) hash.update(chunk); signal?.throwIfAborted(); if (hash.digest("hex") !== expected.sha256) throw invalidArchive("sha256_mismatch"); + if (verifiedArchives.size >= 1_024) verifiedArchives.clear(); + verifiedArchives.add(identity); } finally { await file.close(); } } diff --git a/server/src/services/native-runtime/provider-pack-selection-harness.test.ts b/server/src/services/native-runtime/provider-pack-selection-harness.test.ts new file mode 100644 index 00000000000..8ff7be13870 --- /dev/null +++ b/server/src/services/native-runtime/provider-pack-selection-harness.test.ts @@ -0,0 +1,188 @@ +import { execFile } from "node:child_process"; +import { createHash, randomBytes } from "node:crypto"; +import { chmod, cp, mkdir, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join, posix } from "node:path"; +import { promisify } from "node:util"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime"; +import { QUALIFIED_ACPX_PROFILES, QUALIFIED_ACPX_VERSION } from "../../vendor/paperclip-runner/index.js"; +import { prepareRemoteProviderPackOnTarget, resolveRemoteProviderPackSource, sha256DirectoryTree } from "./native-session-executor.js"; +import { canonicalProviderPackJson } from "./remote-provider-pack-verification.js"; + +const exec = promisify(execFile); +const EXECUTE_LATENCY_MS = 150; +const TRANSFER_LATENCY_MS = 300; +const TRANSFER_BYTES_PER_SECOND = 10 * 1024 * 1024; +const LARGE_ARTIFACT_BYTES = 24 * 1024 * 1024; +const sha = (value: string | Buffer) => `sha256:${createHash("sha256").update(value).digest("hex")}`; + +async function writePack(root: string, revision: string, large: Buffer, distSuffix = "") { + const files: Record = { + "node_modules/node/bin/node": `#!/bin/sh\nexec '${process.execPath}' "$@"\n`, + "node_modules/.bin/opencode": "#!/bin/sh\necho 1.18.34\n", + "node_modules/opencode-ai/bin/opencode.exe": large, + "node_modules/opencode-ai/package.json": JSON.stringify({ version: "1.18.34" }), + "node_modules/acpx/package.json": JSON.stringify({ version: QUALIFIED_ACPX_VERSION }), + "node_modules/@agentclientprotocol/claude-agent-acp/package.json": JSON.stringify({ version: QUALIFIED_ACPX_PROFILES.claude.agentServerVersion }), + "node_modules/@agentclientprotocol/codex-acp/package.json": JSON.stringify({ version: QUALIFIED_ACPX_PROFILES.codex.agentServerVersion }), + "pnpm-lock.yaml": "lockfileVersion: '9.0'\n", + "dist/cli/opencode-app-server-proxy.cjs": `module.exports = "proxy${distSuffix}";\n`, + "dist/cli/acpx-runtime-sidecar.cjs": "module.exports = 'sidecar';\n", + "dist/providers/grok/launcher.cjs": "module.exports = 'grok';\n", + }; + for (const [path, content] of Object.entries(files)) { + await mkdir(dirname(join(root, path)), { recursive: true }); + await writeFile(join(root, path), content); + } + await chmod(join(root, "node_modules/node/bin/node"), 0o755); + await chmod(join(root, "node_modules/.bin/opencode"), 0o755); + const artifact = (path: string) => ({ path, sha256: sha(files[path]!) }); + const proxy = artifact("dist/cli/opencode-app-server-proxy.cjs"), sidecar = artifact("dist/cli/acpx-runtime-sidecar.cjs"); + const distDigest = sha256DirectoryTree(join(root, "dist")); + const payload = { + pins: { nodeMinimum: "24.11.0", codex: QUALIFIED_ACPX_PROFILES.codex.agentRuntimeVersion, opencode: "1.18.34", acpx: QUALIFIED_ACPX_VERSION, + claudeAcp: QUALIFIED_ACPX_PROFILES.claude.agentServerVersion, codexAcp: QUALIFIED_ACPX_PROFILES.codex.agentServerVersion, + grok: QUALIFIED_ACPX_PROFILES.grok.agentRuntimeVersion }, + target: { platform: process.platform, architecture: process.arch }, + runnerSourceRevision: revision.repeat(40), + distDigest, + bridgeDigest: `sha256:${createHash("sha256").update(proxy.sha256).update("\n").update(sidecar.sha256).update("\n").update(distDigest).digest("hex")}`, + acpxProfileDigests: { grok: QUALIFIED_ACPX_PROFILES.grok.commandDigest, claude: QUALIFIED_ACPX_PROFILES.claude.commandDigest, + codex: QUALIFIED_ACPX_PROFILES.codex.commandDigest }, + artifacts: { + grokLauncher: artifact("dist/providers/grok/launcher.cjs"), nodeCommand: artifact("node_modules/node/bin/node"), + productionLock: artifact("pnpm-lock.yaml"), opencodeCommand: artifact("node_modules/.bin/opencode"), + opencodeExecutable: artifact("node_modules/opencode-ai/bin/opencode.exe"), opencodeProxy: proxy, acpxSidecar: sidecar, + }, + }; + await writeFile(join(root, "provider-pack.json"), JSON.stringify({ schema: "paperclip-runner/remote-provider-pack/v1", + digest: sha(canonicalProviderPackJson(payload)), payload })); +} + +async function directoryBytes(root: string): Promise { + let total = 0; + for (const entry of await readdir(root, { withFileTypes: true, recursive: true })) { + if (entry.isFile()) total += (await stat(join(entry.parentPath, entry.name))).size; + } + return total; +} + +function assertConfinedSandboxPath(remoteDir: string, candidate: string) { + const root = posix.normalize(remoteDir); + const normalized = posix.normalize(candidate); + if (normalized !== root && !normalized.startsWith(`${root}/`)) { + throw new Error(`sync target path escapes the workspace remote dir: ${candidate}`); + } +} + +function simulatedSandbox(home: string, workspace: string) { + const usage = { simulatedMs: 0, executes: 0, bytesUploaded: 0 }; + const runner: CommandManagedRuntimeRunner = { + execute: async request => { + usage.executes += 1; + usage.simulatedMs += EXECUTE_LATENCY_MS; + try { + const result = await exec(request.command, request.args ?? [], { cwd: request.cwd, env: { ...process.env, HOME: home }, maxBuffer: 1 << 24 }); + return { exitCode: 0, signal: null, pid: null, startedAt: null, timedOut: false, stdout: result.stdout, stderr: result.stderr }; + } catch (error) { + const failed = error as Error & { code?: number; stdout?: string; stderr?: string }; + return { exitCode: typeof failed.code === "number" ? failed.code : 127, signal: null, pid: null, startedAt: null, timedOut: false, + stdout: failed.stdout ?? "", stderr: failed.stderr ?? String(error) }; + } + }, + syncIn: async operations => { + const results = []; + for (const operation of operations) { + let bytes = 0; + for (const file of operation.files) { + if (file.kind !== "directory" || !file.sourcePath) throw new Error("unexpected transfer"); + assertConfinedSandboxPath(workspace, file.targetPath); + bytes += await directoryBytes(file.sourcePath); + await mkdir(dirname(file.targetPath), { recursive: true }); + await cp(file.sourcePath, file.targetPath, { recursive: true }); + } + usage.bytesUploaded += bytes; + usage.simulatedMs += TRANSFER_LATENCY_MS + (bytes / TRANSFER_BYTES_PER_SECOND) * 1000; + results.push({ operationId: operation.operationId, filesTransferred: operation.files.length, bytesTransferred: bytes }); + } + return { operations: results }; + }, + }; + return { runner, usage }; +} + +type Scenario = "exact" | "same_content_other_build" | "different_content" | "corrupted" | "none"; + +describe("provider pack selection harness", () => { + let root: string; + let large: Buffer; + let server: ReturnType; + const rows: string[] = []; + beforeAll(async () => { + root = await mkdtemp(join(tmpdir(), "provider-pack-harness-")); + large = randomBytes(LARGE_ARTIFACT_BYTES); + await writePack(join(root, "server-pack"), "b", large); + server = resolveRemoteProviderPackSource(join(root, "server-pack")); + }); + afterAll(async () => { + if (rows.length) process.stdout.write(`\nprovider pack harness (execute ${EXECUTE_LATENCY_MS} ms, transfer ${TRANSFER_LATENCY_MS} ms + ${TRANSFER_BYTES_PER_SECOND / 1024 / 1024} MiB/s)\n${rows.join("\n")}\n`); + await rm(root, { recursive: true, force: true }); + }); + + const run = async (scenario: Scenario, acceptProvenanceDifferences: boolean) => { + const sandbox = await mkdtemp(join(root, `${scenario}-`)); + const home = join(sandbox, "home"), workspace = join(sandbox, "workspace"); + await mkdir(workspace, { recursive: true }); + const image = join(home, ".local/share/paperclip-runner/provider-pack"); + if (scenario === "exact") await writePack(image, "b", large); + if (scenario === "same_content_other_build") await writePack(image, "a", large); + if (scenario === "different_content") await writePack(image, "a", large, "-older"); + if (scenario === "corrupted") { + await writePack(image, "a", large); + await writeFile(join(image, "dist/cli/acpx-runtime-sidecar.cjs"), "tampered\n"); + } + const { runner, usage } = simulatedSandbox(home, workspace); + const cpuBefore = process.cpuUsage(); + const startedAt = performance.now(); + const prepared = await prepareRemoteProviderPackOnTarget({ + target: { kind: "remote", transport: "sandbox", remoteCwd: workspace, runner } as never, + runner, configuredProviderPackRoot: server.configuredRoot, manifest: server.manifest, acceptProvenanceDifferences, + }); + const wallMs = performance.now() - startedAt; + const cpu = process.cpuUsage(cpuBefore); + rows.push(`${scenario.padEnd(26)} ${acceptProvenanceDifferences ? "after " : "before"} source=${prepared.source.padEnd(12)} ` + + `modelled=${((wallMs + usage.simulatedMs) / 1000).toFixed(2)}s uploaded=${(usage.bytesUploaded / 1024 / 1024).toFixed(1)}MiB ` + + `executes=${usage.executes} serverCpu=${((cpu.user + cpu.system) / 1000).toFixed(0)}ms dbStatements=0`); + return { prepared, usage }; + }; + + it("confines simulated uploads to the workspace", async () => { + const { runner } = simulatedSandbox(root, join(root, "workspace")); + await expect(runner.syncIn!([{ operationId: "escape", files: [{ kind: "directory", sourcePath: join(root, "server-pack"), + targetPath: join(root, "workspace", "..", "outside"), mode: 0o700 }] }])).rejects.toThrow("escapes the workspace"); + }); + + it.each<[Scenario, "preinstalled" | "uploaded", "preinstalled" | "uploaded"]>([ + ["exact", "preinstalled", "preinstalled"], + ["same_content_other_build", "uploaded", "preinstalled"], + ["different_content", "uploaded", "uploaded"], + ["corrupted", "uploaded", "uploaded"], + ["none", "uploaded", "uploaded"], + ])("selects the pack for %s (before: %s, after: %s)", async (scenario, before, after) => { + const previous = await run(scenario, false); + expect(previous.prepared.source).toBe(before); + expect(previous.prepared.manifest).toEqual(server.manifest); + const current = await run(scenario, true); + expect(current.prepared.source).toBe(after); + expect(current.usage.bytesUploaded).toBe(after === "uploaded" ? previous.usage.bytesUploaded : 0); + if (scenario === "same_content_other_build") { + expect(current.prepared.manifest.digest).not.toBe(server.manifest.digest); + expect(current.prepared.manifest.payload.runnerSourceRevision).toBe("a".repeat(40)); + expect({ ...current.prepared.manifest.payload, runnerSourceRevision: null }) + .toEqual({ ...server.manifest.payload, runnerSourceRevision: null }); + } else { + expect(current.prepared.manifest).toEqual(server.manifest); + } + }, 120_000); +}); diff --git a/server/src/services/native-runtime/remote-provider-pack-verification.test.ts b/server/src/services/native-runtime/remote-provider-pack-verification.test.ts index 308d142b9cc..0f47eece296 100644 --- a/server/src/services/native-runtime/remote-provider-pack-verification.test.ts +++ b/server/src/services/native-runtime/remote-provider-pack-verification.test.ts @@ -120,6 +120,24 @@ describe("installed provider pack compatibility", () => { if (field === "digest") pack.digest = sha("corrupt"); await expect(check(pack)).rejects.toThrow("runner_remote_provider_artifact_incompatible"); }); + it("accepts a reported installed manifest only when its sealed content equals the expected pack", async () => { + const expected = manifest("b"); + const report = (installed: unknown) => vi.fn(async (request: Parameters[0]) => ({ + exitCode: 0, signal: null, pid: null, startedAt: null, timedOut: false, stderr: "", + stdout: request.args?.[0] === "--version" ? "1.18.34\n" + : `\npaperclip-pack-manifest=${Buffer.from(JSON.stringify(installed)).toString("base64")}\n` })); + const input = { cwd: "/workspace", packRoot: "/opt/paperclip-runner/provider-pack", manifest: expected, acceptProvenance: true }; + const otherBuild = manifest("b"); + otherBuild.payload.runnerSourceRevision = "a".repeat(40); + await expect(verifyRemoteProviderPack({ ...input, runner: { execute: report(reseal(otherBuild)) } })).resolves.toEqual(reseal(otherBuild)); + const otherContent = reseal({ ...otherBuild, payload: { ...otherBuild.payload, contractDigest: sha("other") } }); + await expect(verifyRemoteProviderPack({ ...input, runner: { execute: report(otherContent) } })) + .rejects.toMatchObject({ failureCheck: "installed_manifest_invalid" }); + await expect(verifyRemoteProviderPack({ ...input, runner: { execute: report({ ...reseal(otherBuild), digest: sha("unsealed") }) } })) + .rejects.toMatchObject({ failureCheck: "installed_manifest_invalid" }); + await expect(verifyRemoteProviderPack({ ...input, acceptProvenance: false, runner: { execute: report(reseal(otherBuild)) } })) + .resolves.toEqual(expected); + }); it("does not reuse image packs when the controller's bundled pack records no contract digest", async () => { const current = manifest("b"); delete current.payload.contractDigest; diff --git a/server/src/services/native-runtime/remote-provider-pack-verification.ts b/server/src/services/native-runtime/remote-provider-pack-verification.ts index 5e7c424f20b..dff334bc7dd 100644 --- a/server/src/services/native-runtime/remote-provider-pack-verification.ts +++ b/server/src/services/native-runtime/remote-provider-pack-verification.ts @@ -105,7 +105,7 @@ function compatibleInstallation( return structuredClone(actual); } -export async function verifyRemoteProviderPack({ runner, cwd, packRoot, manifest, installation, provider, requireExactIdentity = false, requireCurrentOpenCodeProxy = false }: { +export async function verifyRemoteProviderPack({ runner, cwd, packRoot, manifest, installation, provider, requireExactIdentity = false, requireCurrentOpenCodeProxy = false, acceptProvenance = false }: { runner: CommandManagedRuntimeRunner; cwd: string; packRoot: string; @@ -114,6 +114,7 @@ export async function verifyRemoteProviderPack({ provider?: PackProvider; requireExactIdentity?: boolean; requireCurrentOpenCodeProxy?: boolean; + acceptProvenance?: boolean; }): Promise { if (installation) { if (!provider) throw new Error("runner_remote_provider_artifact_incompatible: provider interface is required"); @@ -138,7 +139,10 @@ export async function verifyRemoteProviderPack({ "const canonical=(v)=>Array.isArray(v)?'['+v.map(canonical).join(',')+']':v&&typeof v==='object'?'{'+Object.keys(v).sort().map(k=>JSON.stringify(k)+':'+canonical(v[k])).join(',')+'}':JSON.stringify(v)", "let manifest;try{manifest=JSON.parse(actual)}catch{fail('manifest_invalid','provider pack manifest invalid')}", "const differing=(a,b)=>[...new Set([...Object.keys(a||{}),...Object.keys(b||{})])].sort().filter(k=>canonical((a||{})[k])!==canonical((b||{})[k]))", - "if(canonical(manifest)!==expected){const wanted=JSON.parse(expected);const keys=differing(manifest,wanted).flatMap(k=>k==='payload'?differing(manifest.payload,wanted.payload):k==='digest'?[]:[k]);fail('manifest_mismatch:'+keys.join(',').slice(0,90),'manifest mismatch')}", + "const provenance=process.argv[3]==='provenance'", + "const content=(m)=>{const c=JSON.parse(JSON.stringify(m??null))??{};delete c.digest;if(c.payload&&typeof c.payload==='object'){delete c.payload.runnerSourceRevision;delete c.payload.runnerInputsDigest}return canonical(c)}", + "const sealed=manifest?.digest==='sha256:'+crypto.createHash('sha256').update(canonical(manifest?.payload)).digest('hex')", + "if(canonical(manifest)!==expected&&!(provenance&&sealed&&content(manifest)===content(JSON.parse(expected)))){const wanted=JSON.parse(expected);const keys=differing(manifest,wanted).flatMap(k=>k==='payload'?differing(manifest.payload,wanted.payload):k==='digest'?[]:[k]);fail('manifest_mismatch:'+keys.join(',').slice(0,90),'manifest mismatch')}", "const hash=(p)=>{try{return 'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(path.join(root,p))).digest('hex')}catch{return 'unreadable'}}", "const walk=(treeRoot)=>{const digest=crypto.createHash('sha256');const visit=(directory,prefix='')=>{for(const entry of fs.readdirSync(directory,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))){const relative=prefix?prefix+'/'+entry.name:entry.name;const absolute=path.join(directory,entry.name);if(entry.isDirectory()){digest.update('directory\\0'+relative+'\\n');visit(absolute,relative)}else if(entry.isFile()){digest.update('file\\0'+relative+'\\0'+'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(absolute)).digest('hex')+'\\n')}else if(entry.isSymbolicLink()){digest.update('symlink\\0'+relative+'\\0'+fs.readlinkSync(absolute)+'\\n')}else throw new Error('unsupported dist entry '+relative)}};visit(treeRoot);return 'sha256:'+digest.digest('hex')}", "const tree=(treeRoot)=>{try{return walk(treeRoot)}catch{return 'unreadable'}}", @@ -152,14 +156,16 @@ export async function verifyRemoteProviderPack({ "const packageVersion=(pkg)=>{try{return JSON.parse(fs.readFileSync(path.join(root,'node_modules',...pkg.split('/'),'package.json'),'utf8')).version}catch{return null}}", "const expectedPackages={acpx:manifest.payload.pins.acpx,'@agentclientprotocol/claude-agent-acp':manifest.payload.pins.claudeAcp,'@agentclientprotocol/codex-acp':manifest.payload.pins.codexAcp,'opencode-ai':manifest.payload.pins.opencode}", "for(const [pkg,version] of Object.entries(expectedPackages))if(packageVersion(pkg)!==version)fail('package_version:'+pkg,pkg+' version mismatch')", + "if(provenance)process.stdout.write('\\npaperclip-pack-manifest='+Buffer.from(canonical(manifest)).toString('base64')+'\\n')", ].join(";"); - await withProviderPackCheck("pack", () => runRemoteProviderVerification(() => runner.execute({ + const verified = await withProviderPackCheck("pack", () => runRemoteProviderVerification(() => runner.execute({ command: providerNodeCommand, - args: ["-e", verifyScript, packRoot, expected], + args: ["-e", verifyScript, packRoot, expected, ...(acceptProvenance ? ["provenance"] : [])], cwd: cwd, bypassSession: true, timeoutMs: 30_000, }), "provider pack verification")); + const selected = acceptProvenance ? sameContentManifest(manifest, verified.stdout) : manifest; const opencodeCommand = posix.join( packRoot, manifest.payload.artifacts.opencodeCommand.path, @@ -176,5 +182,27 @@ export async function verifyRemoteProviderPack({ ) { throw providerPackIncompatible("opencode_version", "OpenCode version mismatch"); } - return structuredClone(manifest); + return structuredClone(selected); +} + +const PROVENANCE_FIELDS = ["runnerSourceRevision", "runnerInputsDigest"] as const; + +export function providerPackContent(manifest: ProviderPackIdentity): string { + const payload: Record = { ...manifest.payload }; + for (const field of PROVENANCE_FIELDS) delete payload[field]; + return canonicalProviderPackJson({ schema: manifest.schema, payload }); +} + +function sameContentManifest(expected: T, stdout: string): T { + const encoded = /paperclip-pack-manifest=([A-Za-z0-9+/=]{1,200000})/.exec(stdout)?.[1]; + let installed: T | null = null; + try { installed = encoded ? JSON.parse(Buffer.from(encoded, "base64").toString("utf8")) as T : null; } catch {} + if (!installed?.payload || installed.schema !== expected.schema + || installed.digest !== `sha256:${createHash("sha256").update(canonicalProviderPackJson(installed.payload)).digest("hex")}` + || providerPackContent(installed) !== providerPackContent(expected) + || !/^[0-9a-f]{40}(?:-dirty)?$/.test(installed.payload.runnerSourceRevision) + || (installed.payload.runnerInputsDigest !== undefined && !/^[0-9a-f]{64}$/.test(installed.payload.runnerInputsDigest))) { + throw providerPackIncompatible("installed_manifest_invalid", "installed provider pack identity is invalid"); + } + return installed; } diff --git a/server/src/services/native-runtime/remote-provider-pack.test.ts b/server/src/services/native-runtime/remote-provider-pack.test.ts index 0ae23290c7f..8d4928683d8 100644 --- a/server/src/services/native-runtime/remote-provider-pack.test.ts +++ b/server/src/services/native-runtime/remote-provider-pack.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vitest"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; import { createNativeRunTrace } from "./native-run-trace.js"; -import { prepareVerifiedRemoteProviderPack, useVerifiedPreinstalledRemoteProviderPack, runRemoteProviderVerification, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js"; +import { prepareVerifiedRemoteProviderPack, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, runRemoteProviderVerification, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js"; describe("remote provider verification", () => { const ok = { exitCode: 0, timedOut: false, stdout: "verified", stderr: "", signal: null }; @@ -124,6 +124,17 @@ describe("remote provider pack reuse", () => { }); +describe("same-content pack reuse across builds", () => { + it.each([ + [{ retainProviderPack: false, explicitProviderPackSelection: false, authoritySelectable: true }, true], + [{ retainProviderPack: true, explicitProviderPackSelection: false, authoritySelectable: true }, false], + [{ retainProviderPack: false, explicitProviderPackSelection: true, authoritySelectable: true }, false], + [{ retainProviderPack: false, explicitProviderPackSelection: false, authoritySelectable: false }, false], + ])("allows provenance-only differences only for an unbound run: %j", (input, allowed) => { + expect(providerPackProvenanceReuseAllowed(input)).toBe(allowed); + }); +}); + describe("ordinary ACPX image artifacts", () => { const provider = (agent: string) => ({ kind: "acpx", agent, model: "selected-model" } as Parameters[0]["provider"]); it.each(["cursor", "copilot"])("selects bundled artifacts for remote %s without an operator override", agent => { diff --git a/server/src/services/native-runtime/remote-provider-pack.ts b/server/src/services/native-runtime/remote-provider-pack.ts index b803d6d6d2c..0003cd13661 100644 --- a/server/src/services/native-runtime/remote-provider-pack.ts +++ b/server/src/services/native-runtime/remote-provider-pack.ts @@ -13,6 +13,15 @@ export function shouldUseBundledAcpxImageAssets(input: { ["cursor", "copilot", "kimi"].includes(input.provider.agent); } +/** A run may adopt a same-content pack from another build only when no saved or operator-selected identity binds it. */ +export function providerPackProvenanceReuseAllowed(input: { + retainProviderPack: boolean; + explicitProviderPackSelection: boolean; + authoritySelectable: boolean; +}): boolean { + return !input.retainProviderPack && !input.explicitProviderPackSelection && input.authoritySelectable; +} + type VerificationCommandResult = { exitCode: number | null; timedOut: boolean; From c2e7df2dcc34fd989c4d20faed8f315f22bd056b Mon Sep 17 00:00:00 2001 From: marshall Date: Sun, 15 Nov 2026 10:10:25 -0800 Subject: [PATCH 3/5] fix(workspaces): use project storage for a fresh retry after unowned task storage (#20756) 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 > - A project can use a storage provider plugin. That plugin prepares each task's git worktree > - A board Retry after a failed run can start a fresh attempt. The fresh attempt starts from the project source > - `preparePluginWorkspace` returns `null` when the task is still bound to a workspace that no storage provider owns. It does this also for a fresh attempt > - On a plugin task environment, the host then reserves an empty adapter-managed "Fresh task workspace" with no repository. The runner fails in it. The next Retry finds that empty workspace bound to the task, returns `null` again and reserves another empty workspace. The task can never start again > - This pull request lets a fresh attempt use the project storage provider even when the previous workspace is not provider-owned > - The benefit is that one Retry gives the task a normal provider worktree again ## Linked Issues or Issue Description **What happened?** Tasks moved off an older execution environment kept a binding to a workspace that no storage provider owned. A board Retry selected `fresh_isolated_workspace`. `preparePluginWorkspace` returned `null` because the bound workspace was not plugin-owned. The host fell back to `reserveFreshPluginTaskWorkspace`, which made an empty `adapter_managed` workspace (strategy `project_primary`, no repository, no recovery snapshots). The run failed in about one second with "Plugin-provided Runner execution operation unavailable; reconcile the same task before retrying". Each later Retry made another empty workspace, chained to the last one. **Steps to reproduce** 1. Use a project with a storage provider plugin that supports fresh workspaces. 2. Bind a task to a workspace that the provider does not own (for example an adapter-managed workspace). 3. Call `preparePluginWorkspace` for a fresh attempt with that workspace as the previous workspace. **Expected behavior** The storage provider prepares a new worktree for the fresh attempt. **Actual behavior** `preparePluginWorkspace` returns `null` and never calls the provider. ## What Changed - `server/src/services/plugin-workspaces.ts`: the early `return null` for a previous workspace that no provider owns no longer applies to a fresh attempt. The fresh attempt then uses the project's storage provider, as for a task with no bound workspace. - `server/src/__tests__/plugin-fresh-workspaces.integration.test.ts`: new test "prepares provider storage for a fresh retry that follows a workspace the provider does not own". ## Verification - The first commit adds only the test. CI on that commit (`d09ad235`, [failed job](https://github.com/paperclipai/paperclip/actions/runs/42976154239/job/130393285731)) shows only this test fail on the current code (`preparePluginWorkspace` returns `null`). - The second commit adds the fix. CI shows the test pass. - The other tests in the file keep the fresh-attempt guarantees: an older provider still fails closed, a changed binding revision still stops the call, and a lost reply still reconciles to the same operation. - I did not run the suite locally. The test needs embedded Postgres, and this environment does not install packages. CI runs it. ## Risks - Low to medium risk. A fresh attempt in a project with a storage provider now uses that provider even when the previous workspace was local or adapter-managed. Before, such an attempt used the fallback path. This matches the project's storage policy, and a fresh attempt does not reuse the previous workspace's files. - Projects without a storage provider are not affected: the function still returns `null` for them. - Non-fresh preparation is not affected. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), through Claude Code with tool use (shell, file edits). Standard reasoning mode. ## 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 - [ ] 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: lucktastic <13757243+lucktastic@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- ...plugin-fresh-workspaces.integration.test.ts | 18 ++++++++++++++++++ server/src/services/plugin-workspaces.ts | 3 ++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/server/src/__tests__/plugin-fresh-workspaces.integration.test.ts b/server/src/__tests__/plugin-fresh-workspaces.integration.test.ts index 28854abedfe..5490aaee97a 100644 --- a/server/src/__tests__/plugin-fresh-workspaces.integration.test.ts +++ b/server/src/__tests__/plugin-fresh-workspaces.integration.test.ts @@ -98,6 +98,24 @@ describe.skipIf(!support.supported)("provider-owned fresh retry reservations", ( expect(settled.metadata?.workspaceProviderRemoved).toBe(true); expect(cache.release).toHaveBeenCalledTimes(2); }); + it("prepares provider storage for a fresh retry that follows a workspace the provider does not own", async () => { + const f = await createPluginWorkspaceFixture(db); await enable(f.pluginId); + const [previous] = await db.insert(executionWorkspaces).values({ companyId: f.companyId, projectId: f.input.projectId, + projectWorkspaceId: f.input.projectWorkspaceId, sourceIssueId: f.issueId, mode: "isolated_workspace", + strategyType: "project_primary", name: "Fresh task workspace", status: "active", providerType: "adapter_managed" }).returning(); + await db.update(issues).set({ executionWorkspaceId: previous.id, workspaceBindingRevision: 1 }).where(eq(issues.id, f.issueId)); + await db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, f.runId)); + const [run] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.input.agentId, + issueId: f.issueId, status: "running" }).returning(); + const fresh = { attemptId: randomUUID(), sourceRunId: f.runId, previousWorkspaceId: previous.id, recoverySnapshots: [] }; + const workspace = await preparePluginWorkspace(db, f.workers, { ...f.input, runId: run.id, + existingWorkspaceId: previous.id, fresh, expectedBindingRevision: 1 }); + expect(workspace).not.toBeNull(); + expect(workspace!.id).not.toBe(previous.id); + expect(workspace!.providerType).toBe("plugin"); + expect(f.calls).toHaveLength(1); + expect(f.calls[0].operation).toMatchObject({ kind: "prepare", fresh, branchName: null }); + }); it("rejects a changed task revision before calling the provider", async () => { const f = await fixture(); await enable(f.pluginId); await db.update(issues).set({ workspaceBindingRevision: 2 }).where(eq(issues.id, f.issueId)); diff --git a/server/src/services/plugin-workspaces.ts b/server/src/services/plugin-workspaces.ts index feeac4c55a3..d91fac253bd 100644 --- a/server/src/services/plugin-workspaces.ts +++ b/server/src/services/plugin-workspaces.ts @@ -133,7 +133,8 @@ export async function preparePluginWorkspace( ), ) : []; - if (prior && prior.providerType !== "plugin" && !priorBinding && !prior.metadata?.workspaceProviderOwner) return null; + // A fresh attempt starts from the project source, so storage the provider does not own does not decide it. + if (!input.fresh && prior && prior.providerType !== "plugin" && !priorBinding && !prior.metadata?.workspaceProviderOwner) return null; const owner = priorBinding?.pluginId ?? prior?.metadata?.workspaceProviderOwner ?? (!existing && input.selectedProviderPluginId !== undefined ? input.selectedProviderPluginId : !existing && project ? (await effectiveProjectWorkspacePolicy(db, input.companyId, project.executionWorkspacePolicy, false))?.storageProviderPluginId : null); From b4f71fc2766160ac2a1cb8bb621f0e5931e06d49 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:13:18 -0600 Subject: [PATCH 4/5] perf(recovery): stop re-checking settled workspace flags and snapshot ledger rows every pass (#21795) 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 server runs all background recovery on one Node main thread, and each database statement costs time on it > - The ownership reconciliation pass settles in-progress records every 30 s while it has records to watch > - Two of its kinds listed records that can never change again: dirty remote workspaces whose writer reached runtime, and snapshot ledger rows that are uploaded or still held by a stale writer's epoch > - Each such record cost a transaction, a row lock and up to four reads on every pass, forever, and kept the 30 s watch armed on an idle instance > - This pull request lists only the records that the settle step can still act on, locks the writer run only when the settle will write, and skips one stranded-task read that can never match a native run > - The benefit is that recovery work follows activity, not history ## Linked Issues or Issue Description **Describe the problem** On a hosted instance with 7 native runs, the ownership pass ran about 7.6 + 3.2 + 3.5 + 2.8 statements per second over records that cannot change, and took a row lock on `heartbeat_runs` for each stale dirty workspace on every pass. At 1,000 agents this becomes thousands of statements per second. **Steps to reproduce** Seed about 100 dirty remote workspaces whose writer run reached runtime and ended, 50 pending ledger rows still held by those writers, and 100 uploaded ledger rows. Run the ownership reconciliation worker. The new census test `server/src/__tests__/recovery-settled-records-census.test.ts` does this on the embedded database. **Expected behavior** A settled record costs zero statements on later passes. An idle instance runs no SQL from this pass. **Actual behavior** On master, one pass costs 714 statements and 150 row locks. An idle half hour costs 40,800 statements and 9,000 row locks (the settle watch re-checks every 30 s). Refs #21765 (the stranded-assignment hint scoping that this rebases on) ## What Changed - `remote_workspace_unsaved_files` lists a dirty workspace only when its writer run can still be a preparation-only writer: stage `preparing`, no `runtime_mode_resolved_at`, no process, session or runner id, no finalization row and no work-started event (or no writer at all). The SQL lives with the settle step in `remote-workspace-unsaved-files-settlement.ts`. - The unsaved-files settle reads the writer run without a lock. It takes `for update` only after every check passes, just before it writes, and checks the locked row again. - `remote_snapshot_ledger` lists only `pending` rows with no object key, whose operation is a workspace save, and whose workspace epoch has moved past the row's writer. Uploaded rows belong to snapshot retention, as before. - `terminalRunSettlingUntil` in `recovery/service.ts` skips its `heartbeat_runs` read when the latest run already in memory is not a legacy run of another server boot. `getLatestIssueRun` now also selects `runtime_mode` and `controller_boot_id`. The live-execution check still runs first. - New census test with a staging-shaped fixture, a statement counter grouped by statement shape and caller, and prompt-pickup checks. New red/green test for the stranded-task lease read. Census (embedded PostgreSQL, same fixture, base 531db3c10b vs this branch): | Window | Master statements | Master row locks | Branch statements | Branch row locks | | --- | --- | --- | --- | --- | | One full ownership pass | 714 | 150 | 62 | 0 | | One settle-watch re-check | 681 | 150 | 29 | 0 | | Idle 30 min (real worker) | 40,800 | 9,000 | 0 | 0 | | Active, 7 live runs hinting every 10 s | 47,257 per 30 min | 9,000 | 2,763 per 10 min (about 8,300 per 30 min, of which about 4,200 are the test's own hint writers) | 0 | Confirmed callers on master (per full pass): `select execution_workspace_snapshots` full row at `remote-snapshot-ledger-settlement.ts:20` (150), `select heartbeat_runs ... for update` at `remote-workspace-unsaved-files-settlement.ts:20` (100), `select workspace_operations ... for update` at `remote-snapshot-ledger-settlement.ts:25` (50), `select execution_workspaces.metadata` at `remote-snapshot-ledger-settlement.ts:36` (50). The `execution_replacement` queue costs 2 statements per wake over the same history (discovery and the deadline read), so it is not the source of the snapshot or lease reads in this shape. ## Verification - `cd server && npx vitest run src/__tests__/recovery-settled-records-census.test.ts src/__tests__/issue-recovery-terminal-run-settling.test.ts` (fails on master: 714/40,800 statements and the native lease read; passes here) - `cd server && npx vitest run src/__tests__/remote-snapshot-ledger-settlement.test.ts src/__tests__/ownership-reconciliation-report.test.ts` (51 passed, unchanged) - `cd server && npx vitest run src/__tests__/recovery-deadline-acceptance.test.ts src/__tests__/legacy-continuation-authority.test.ts src/__tests__/heartbeat-process-recovery.test.ts` (502 passed) - The census test also checks that a preparation-only workspace is still settled in the first pass, an abandoned pending ledger row is still retired, a ledger row held by a stale writer is retired in the next pass once the workspace epoch moves, and an `active` run lease whose run ended is still listed and released. ## Risks - The report shows fewer in-progress records for these two kinds. Records that the settle step can never change (a dirty flag whose writer reached runtime, an uploaded ledger row) are no longer listed, so they no longer appear as `I2_settled` violations in the activity log. On master each process wrote one such violation per record. - A pending ledger row held by its stale writer's epoch is no longer re-checked every 30 s. It is found by the next full pass after the workspace epoch moves. A new writer or an epoch abandonment both come with run signals that wake the pass, but on an instance with no other activity this can now wait until the next wake instead of at most 30 s. - A dirty workspace whose writer run row is missing is no longer listed. On master it was re-checked forever and the settle refused it every time. - No schema, API or UI change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Claude Code agent with tool use and code execution. ## 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 - [ ] All Paperclip CI gates are green - [ ] 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: Claude Opus 5.5 --- ...sue-recovery-terminal-run-settling.test.ts | 38 +++ .../recovery-settled-records-census.test.ts | 304 ++++++++++++++++++ .../services/recovery/ownership-registry.ts | 9 +- .../remote-snapshot-ledger-settlement.ts | 12 +- ...mote-workspace-unsaved-files-settlement.ts | 29 +- server/src/services/recovery/service.ts | 13 +- 6 files changed, 394 insertions(+), 11 deletions(-) create mode 100644 server/src/__tests__/issue-recovery-terminal-run-settling.test.ts create mode 100644 server/src/__tests__/recovery-settled-records-census.test.ts diff --git a/server/src/__tests__/issue-recovery-terminal-run-settling.test.ts b/server/src/__tests__/issue-recovery-terminal-run-settling.test.ts new file mode 100644 index 00000000000..d889689a3a8 --- /dev/null +++ b/server/src/__tests__/issue-recovery-terminal-run-settling.test.ts @@ -0,0 +1,38 @@ +import { randomUUID } from "node:crypto"; +import { expect, it } from "vitest"; +import { heartbeatRuns, issues } from "@paperclipai/db"; +import { describeIssueRecovery, issueRecoveryFixture } from "./issue-recovery.test-fixture.js"; + +describeIssueRecovery("stranded-task check of a terminal latest run", () => { + const state = issueRecoveryFixture({ meter: true }); + + async function seed(run: Partial) { + const f = await state.fixture(); + const issueId = randomUUID(), runId = randomUUID(); + await state.db.insert(issues).values({ id: issueId, companyId: f.companyId, title: "Checked task", status: "in_progress", + assigneeAgentId: f.agentId }); + await state.db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, status: "failed", + invocationSource: "manual", contextSnapshot: { issueId }, finishedAt: new Date(Date.now() - 60_000), errorCode: "process_lost", + ...run }); + return { ...f, issueId, runId }; + } + + async function leaseReads(f: { companyId: string; issueId: string }) { + state.meter.startLog(); + await state.heartbeat.reconcileStrandedAssignedIssues({ companyId: f.companyId, issueId: f.issueId, + skipExternalConversationSettlement: true, skipRelatedRecovery: true }); + return state.meter.stopLog().filter(entry => /^select "controller_lease_expires_at" from "heartbeat_runs"/.test(entry.sql.trim())); + } + + it("does not read the controller lease of a native latest run, which can never still be settling", async () => { + const f = await seed({ runtimeMode: "native", controllerBootId: randomUUID(), + controllerLeaseExpiresAt: new Date(Date.now() + 60_000) }); + expect(await leaseReads(f)).toEqual([]); + }, 120_000); + + it("still reads the unexpired controller lease of a legacy run another server is settling", async () => { + const f = await seed({ runtimeMode: "legacy", controllerBootId: randomUUID(), + controllerLeaseExpiresAt: new Date(Date.now() + 60_000) }); + expect(await leaseReads(f)).toHaveLength(1); + }, 120_000); +}); diff --git a/server/src/__tests__/recovery-settled-records-census.test.ts b/server/src/__tests__/recovery-settled-records-census.test.ts new file mode 100644 index 00000000000..08ce7379d16 --- /dev/null +++ b/server/src/__tests__/recovery-settled-records-census.test.ts @@ -0,0 +1,304 @@ +import { randomUUID } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; +import { eq, sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { agents, companies, createDb, environmentLeases, executionWorkspaceSnapshots, executionWorkspaces, heartbeatRuns, + issues, nativeRunFinalizations, workspaceOperations } from "@paperclipai/db"; +import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; +import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js"; +import { notifyExecutionRunWork } from "../services/execution-control-notifications.js"; +import { executionControlSchedule, registerExecutionControlWork } from "../services/execution-control-work.js"; +import { registerOwnershipReconciliationWork } from "../services/native-runtime/native-finalization-reconciler.js"; +import { OWNABLE_KINDS } from "../services/recovery/ownership-registry.js"; +import { createOwnershipReportState, recheckSettlingKinds, runOwnershipReconciliationPass } from "../services/recovery/ownership-invariant-report.js"; +import { invalidateNativeReplacementDiscovery, reconcileSafeNativeReplacements } from "../services/native-runtime/native-safe-replacement.js"; +import { notifyRunDispatch } from "../services/run-dispatch-notifications.js"; +import { readRemoteWorkspaceAuthority } from "@paperclipai/shared"; +import { idleWorkSnapshot } from "../services/task-admission.js"; +import { meterDatabaseStatements } from "./helpers/database-statement-meter.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const minutesAgo = (minutes: number) => new Date(Date.now() - minutes * 60_000); +const quiesced = () => ({ schema: "paperclip.remote-workspace-save-work.v1", activeIds: [], unknown: false, + owners: {}, quiescedAt: minutesAgo(600).toISOString() }); + +type Census = { statements: number; locks: number; byShape: Map }; + +function shapeOf(query: string) { + const text = query.replace(/\s+/g, " ").trim(); + const table = /\bfrom "?([a-z_]+)"?/i.exec(text)?.[1] ?? /^(?:update|insert into) "?([a-z_]+)"?/i.exec(text)?.[1] ?? "?"; + const verb = text.split(" ")[0]!.toLowerCase(); + return `${verb} ${table}${/ for (update|share|no key update)\b/i.test(text) ? " FOR UPDATE" : ""}`; +} + +function callerOf(stack: string) { + const frame = stack.split("\n").slice(1).find(line => line.includes("/server/src/services/") + && !line.includes("delivery-work-coordinator") && !line.includes("task-admission") && !line.includes("activity-log")); + const match = frame && /services\/([^:)]+):(\d+)/.exec(frame); + return match ? `${match[1]}:${match[2]}` : "?"; +} + +describe.skipIf(!support.supported)("recovery passes over settled records (census)", () => { + let database: Awaited>; + let db: ReturnType; + let meter: ReturnType; + let home: string; + let coordinator: ReturnType | undefined; + const errors: unknown[] = []; + let companyId: string, agentId: string; + + beforeAll(async () => { + home = await mkdtemp(join(tmpdir(), "recovery-census-home-")); + vi.stubEnv("PAPERCLIP_HOME", home); + vi.stubEnv("SANDBOX_ORPHAN_CLEANUP_SPOOL_DIR", join(home, "orphan-spool")); + database = await startEmbeddedPostgresTestDatabase("recovery-settled-census-"); + db = createDb(database.connectionString, { maxConnections: 4, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 }); + meter = meterDatabaseStatements(db, database.connectionString); + }, 120_000); + afterAll(async () => { + meter?.uninstall(); await db?.$client.end({ timeout: 1 }); await database?.cleanup(); + vi.unstubAllEnvs(); + await rm(home, { recursive: true, force: true }); + }); + beforeEach(async () => { + await db.execute(sql`truncate execution_workspace_snapshots, workspace_operations, execution_workspaces, activity_log, + native_run_finalizations, heartbeat_runs, issues, agents, companies cascade`); + companyId = randomUUID(); agentId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Census", issuePrefix: `C${companyId.slice(0, 6)}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Worker", role: "engineer", adapterType: "paperclip_runner" }); + }); + afterEach(async () => { + await coordinator?.stop(); coordinator = undefined; + vi.useRealTimers(); + expect(errors.splice(0)).toEqual([]); + }); + + const runRow = (values: Partial = {}) => ({ id: randomUUID(), companyId, agentId, + status: "failed", invocationSource: "manual", finishedAt: minutesAgo(600), errorCode: "process_lost", ...values }); + + const workspaceRow = (authority: { epoch: number; writerRunId: string | null; dirty: boolean; location?: boolean }) => { + const id = randomUUID(); + return { id, companyId, mode: "isolated_workspace", strategyType: "test", name: id, + metadata: { remoteWorkspace: { schema: "paperclip.remote-workspace.v1", epoch: authority.epoch, snapshotId: null, + source: { kind: "git", repoUrl: "https://example.invalid/repo.git", ref: null }, dirty: authority.dirty, + writerRunId: authority.writerRunId, + location: authority.location ? { environmentId: randomUUID(), leaseId: randomUUID(), providerLeaseId: `sandbox-${id}`, + remoteCwd: "/workspace/root" } : null } } }; + }; + + type Rows = { runs: Array>; workspaces: Array>; + operations: Array; snapshots: Array }; + + function ledgerRow(rows: Rows, input: { workspaceId: string; runId: string; epoch: number; status: "pending" | "uploaded"; objectKey?: string | null }) { + const operationId = randomUUID(), snapshotId = randomUUID(); + rows.operations.push({ id: operationId, companyId, executionWorkspaceId: input.workspaceId, + heartbeatRunId: input.runId, phase: "remote_workspace_snapshot", status: "failed", + metadata: { epoch: input.epoch, boundary: "final", generation: 1, saveWork: quiesced() } }); + rows.snapshots.push({ id: snapshotId, companyId, executionWorkspaceId: input.workspaceId, + sourceOperationId: operationId, sourceRunId: input.runId, generation: 1, epoch: input.epoch, status: input.status, + objectKey: input.objectKey ?? null, deleteAfter: new Date(Date.now() + 7 * 86400_000), createdAt: minutesAgo(600), + updatedAt: minutesAgo(600) }); + return snapshotId; + } + + async function insert(rows: Rows) { + if (rows.runs.length) await db.insert(heartbeatRuns).values(rows.runs); + if (rows.workspaces.length) await db.insert(executionWorkspaces).values(rows.workspaces); + if (rows.operations.length) await db.insert(workspaceOperations).values(rows.operations); + if (rows.snapshots.length) await db.insert(executionWorkspaceSnapshots).values(rows.snapshots); + } + + /** The staging shape: history that recovery can no longer change, plus a few live runs. */ + async function seedStagingShape() { + const rows: Rows = { runs: [], workspaces: [], operations: [], snapshots: [] }; + for (let index = 0; index < 100; index++) { + const writer = runRow(index % 2 === 0 ? { executionStage: "executing", runtimeMode: "native", + runtimeModeResolvedAt: minutesAgo(601) } : { status: "succeeded", executionStage: "executing" }); + const workspace = workspaceRow({ epoch: 1, writerRunId: writer.id, dirty: true, location: true }); + rows.runs.push(writer); rows.workspaces.push(workspace); + if (index % 2 === 0) ledgerRow(rows, { workspaceId: workspace.id, runId: writer.id, epoch: 1, status: "pending" }); + } + for (let index = 0; index < 100; index++) { + const source = runRow({ status: "succeeded" }); + const workspace = workspaceRow({ epoch: 2, writerRunId: null, dirty: false }); + rows.runs.push(source); rows.workspaces.push(workspace); + ledgerRow(rows, { workspaceId: workspace.id, runId: source.id, epoch: 1, status: "uploaded", + objectKey: `${companyId}/snapshots/${index}.pcws` }); + } + const finished: Array = [], finalizations: Array = []; + for (let index = 0; index < 20; index++) { + const issueId = randomUUID(); + finished.push({ id: issueId, companyId, title: `Finished ${index}`, status: "done", assigneeAgentId: agentId }); + const failed = runRow({ runtimeMode: "native", nativeIssueId: issueId, contextSnapshot: { issueId }, + runnerProfileJson: { recoveryEventInventoryVersion: 1, nativeExecutionInput: { provider: { kind: "codex" }, + workspace: { cwd: tmpdir() } } } }); + rows.runs.push(failed); + finalizations.push({ runId: failed.id, companyId, issueId, phase: "terminal_failure", attempt: 1, + failureCode: "native_provider_terminal_failed", failureDetail: { originalFailureCode: "fixture_checkpoint_unusable" } }); + } + const live: Array<{ runId: string; issueId: string }> = []; + for (let index = 0; index < 7; index++) { + const issueId = randomUUID(); + const liveRun = runRow({ status: "running", runtimeMode: "native", nativeIssueId: issueId, contextSnapshot: { issueId }, + finishedAt: null, errorCode: null, startedAt: minutesAgo(1) }); + finished.push({ id: issueId, companyId, title: `Live ${index}`, status: "in_progress", assigneeAgentId: agentId }); + rows.runs.push(liveRun); + live.push({ runId: liveRun.id, issueId }); + } + await db.insert(issues).values(finished); + await insert(rows); + await db.insert(nativeRunFinalizations).values(finalizations); + for (const entry of live) await db.update(issues).set({ executionRunId: entry.runId }).where(sql`id = ${entry.issueId}`); + return live; + } + + async function start() { + coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true, + onError: error => errors.push(error) }); + const ownership = registerOwnershipReconciliationWork(db, coordinator, () => true); + const replacement = registerExecutionControlWork(coordinator, [replacementDuty()]); + await Promise.all([ownership.ready, replacement.ready]); + } + + function replacementDuty() { + return { queue: DELIVERY_QUEUES.executionReplacement, + run: () => reconcileSafeNativeReplacements(db, new Date(), { verifyStoppedSession: async () => null }), + next: executionControlSchedule(db).replacement, onSettled: () => invalidateNativeReplacementDiscovery(db), + settleEmptyWhilePaused: true }; + } + + async function advance(ms: number, onTick?: () => Promise) { + const until = Date.now() + ms; + while (Date.now() < until) { + await onTick?.(); + await vi.advanceTimersByTimeAsync(Math.min(10_000, until - Date.now())); await delay(1); + while (idleWorkSnapshot().active > 0) await delay(5); + } + } + + async function census(work: () => Promise): Promise { + const result: Census = { statements: 0, locks: 0, byShape: new Map() }; + meter.startLog({ stacks: true }); + try { await work(); } finally { + for (const entry of meter.stopLog()) { + const lock = / for (update|share|no key update)\b/i.test(entry.sql); + const key = `${shapeOf(entry.sql)} <- ${callerOf(entry.stack ?? "")}`; + const row = result.byShape.get(key) ?? { count: 0, locks: 0 }; + row.count += 1; if (lock) row.locks += 1; + result.byShape.set(key, row); + result.statements += 1; if (lock) result.locks += 1; + } + } + return result; + } + + function table(label: string, result: Census) { + const rows = [...result.byShape].sort((a, b) => b[1].count - a[1].count).slice(0, 20) + .map(([key, value]) => ` ${String(value.count).padStart(6)} ${String(value.locks).padStart(5)} ${key}`); + return `${label}: ${result.statements} statements, ${result.locks} row locks\n${rows.join("\n")}`; + } + + const hint = async (live: Array<{ runId: string; issueId: string }>) => { + for (const { runId, issueId } of live) { + await db.transaction(async tx => { + await notifyRunDispatch(tx, { companyId, runId, issueId }); + await notifyExecutionRunWork(tx, { companyId, runId, issueId }); + }); + } + }; + + it("counts statements and row locks of one pass of each worker over staging-shaped history", async () => { + await seedStagingShape(); + const state = createOwnershipReportState(); + await runOwnershipReconciliationPass(db, { state }); + await runOwnershipReconciliationPass(db, { state }); + const fullPass = await census(() => runOwnershipReconciliationPass(db, { state })); + const watchPass = await census(() => recheckSettlingKinds(db)); + const duty = replacementDuty(); + await duty.run(); + invalidateNativeReplacementDiscovery(db); + const replacementPass = await census(async () => { await duty.run(); await duty.next(); }); + console.log([table("ownership full pass", fullPass), table("ownership watch re-check", watchPass), + table("execution replacement pass", replacementPass)].join("\n\n")); + const settled = (result: Census) => [...result.byShape.keys()].filter(key => + /remote-(workspace-unsaved-files|snapshot-ledger)-settlement/.test(key)); + expect({ full: settled(fullPass), watch: settled(watchPass) }).toEqual({ full: [], watch: [] }); + expect(fullPass.locks).toBe(0); + expect(watchPass.statements).toBeLessThanOrEqual(30); + expect(replacementPass.statements).toBeLessThanOrEqual(3); + }, 300_000); + + it("runs no statements for half an hour once only settled history is left, and takes no row locks while runs are active", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); + const live = await seedStagingShape(); + await start(); await advance(60_000); + await db.update(issues).set({ executionRunId: null, status: "done" }).where(sql`execution_run_id is not null`); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(sql`status = 'running'`); + await advance(60_000); + const idle = await census(() => advance(30 * 60_000)); + await db.update(heartbeatRuns).set({ status: "running", finishedAt: null }) + .where(sql`id in (${sql.join(live.map(entry => sql`${entry.runId}`), sql`, `)})`); + const active = await census(() => advance(10 * 60_000, () => hint(live))); + console.log([table("idle 30 min", idle), table("active 10 min", active)].join("\n\n")); + expect(idle.statements).toBe(0); + expect(active.locks).toBe(0); + expect([...active.byShape.keys()].filter(key => /remote-(workspace-unsaved-files|snapshot-ledger)-settlement/.test(key))).toEqual([]); + }, 1_200_000); + + it("still settles every record that can change promptly, beside staging-shaped history", async () => { + await seedStagingShape(); + const rows: Rows = { runs: [], workspaces: [], operations: [], snapshots: [] }; + const preparing = runRow({ executionStage: "preparing", finishedAt: minutesAgo(2) }); + const preparedWorkspace = workspaceRow({ epoch: 1, writerRunId: preparing.id, dirty: true, location: true }); + const saver = runRow({ executionStage: "executing", finishedAt: minutesAgo(2) }); + const movedWorkspace = workspaceRow({ epoch: 3, writerRunId: null, dirty: false }); + const stuckWriter = runRow({ executionStage: "executing", finishedAt: minutesAgo(2) }); + const stuckWorkspace = workspaceRow({ epoch: 1, writerRunId: stuckWriter.id, dirty: true, location: true }); + const leaseRun = runRow({ finishedAt: minutesAgo(2) }); + rows.runs.push(preparing, saver, stuckWriter, leaseRun); + rows.workspaces.push(preparedWorkspace, movedWorkspace, stuckWorkspace); + const abandoned = ledgerRow(rows, { workspaceId: movedWorkspace.id, runId: saver.id, epoch: 1, status: "pending" }); + const held = ledgerRow(rows, { workspaceId: stuckWorkspace.id, runId: stuckWriter.id, epoch: 1, status: "pending" }); + await insert(rows); + const [lease] = await db.insert(environmentLeases).values({ companyId, heartbeatRunId: leaseRun.id, status: "active" }).returning(); + const ledger = async (id: string) => (await db.select().from(executionWorkspaceSnapshots) + .where(eq(executionWorkspaceSnapshots.id, id)))[0]!; + + const state = createOwnershipReportState(); + const first = await runOwnershipReconciliationPass(db, { state }); + const kind = (id: string) => first.kinds.find(entry => entry.kind === id)!; + expect(kind("remote_workspace_unsaved_files")).toMatchObject({ settled: 1 }); + expect(readRemoteWorkspaceAuthority((await db.select().from(executionWorkspaces) + .where(eq(executionWorkspaces.id, preparedWorkspace.id)))[0]!.metadata)).toMatchObject({ dirty: false, writerRunId: null, epoch: 2 }); + expect((await ledger(abandoned)).status).toBe("deleted"); + expect((await ledger(held)).status).toBe("pending"); + expect(kind("environment_run_lease_active")).toMatchObject({ inProgress: 1, settled: 1 }); + expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, lease!.id)))[0]!.status).toBe("pending_cleanup"); + + await db.update(executionWorkspaces).set({ metadata: { remoteWorkspace: { ...readRemoteWorkspaceAuthority(stuckWorkspace.metadata)!, + epoch: 2, writerRunId: null, dirty: false, location: null } } }).where(eq(executionWorkspaces.id, stuckWorkspace.id)); + const second = await runOwnershipReconciliationPass(db, { state }); + expect(second.kinds.find(entry => entry.kind === "remote_snapshot_ledger")).toMatchObject({ settled: 1 }); + expect((await ledger(held)).status).toBe("deleted"); + const settledPass = await census(() => runOwnershipReconciliationPass(db, { state })); + expect([...settledPass.byShape.keys()].filter(key => /remote-(workspace-unsaved-files|snapshot-ledger)-settlement/.test(key))).toEqual([]); + }, 300_000); + + it("skips a dirty workspace whose writer id is not a UUID without failing the listing", async () => { + const valid = runRow({ executionStage: "preparing", finishedAt: minutesAgo(2) }); + const rows: Rows = { runs: [valid], workspaces: [workspaceRow({ epoch: 1, writerRunId: valid.id, dirty: true, location: true })], + operations: [], snapshots: [] }; + const malformed = workspaceRow({ epoch: 1, writerRunId: null, dirty: true, location: true }); + malformed.metadata.remoteWorkspace.writerRunId = "not-a-run-id" as unknown as null; + rows.workspaces.push(malformed); + await insert(rows); + const kind = OWNABLE_KINDS.find(entry => entry.id === "remote_workspace_unsaved_files")!; + const listed = await kind.listInProgress!(db, 200, 0); + expect(listed.records.map(record => record.recordId)).toEqual([rows.workspaces[0]!.id]); + }, 120_000); +}); + diff --git a/server/src/services/recovery/ownership-registry.ts b/server/src/services/recovery/ownership-registry.ts index 66c768dc06a..1d07a28f561 100644 --- a/server/src/services/recovery/ownership-registry.ts +++ b/server/src/services/recovery/ownership-registry.ts @@ -38,8 +38,8 @@ import { } from "../native-runtime/native-accepted-result-lease-settlement.js"; import { settleClaimedWakeRequest } from "./wake-request-claimed-settlement.js"; import { settleAbandonedRemoteSnapshotSave, settleAbandonedWorkspaceCommandOperation, settleAbandonedWorkspaceFinalizeAttempt } from "./workspace-finalize-attempt-settlement.js"; -import { settlePreparationOnlyRemoteWorkspaceEpoch } from "./remote-workspace-unsaved-files-settlement.js"; -import { settleAbandonedRemoteSnapshotLedger } from "./remote-snapshot-ledger-settlement.js"; +import { preparationOnlyWriterCondition, settlePreparationOnlyRemoteWorkspaceEpoch } from "./remote-workspace-unsaved-files-settlement.js"; +import { retirableRemoteSnapshotLedgerCondition, settleAbandonedRemoteSnapshotLedger } from "./remote-snapshot-ledger-settlement.js"; import { LOCAL_WORKSPACE_COMMAND_PHASES, runtimeControlOperationOwnerStamp, settleRuntimeControlOperation } from "../workspace-operations.js"; import { copybackOwnerHoldOwner, settleCopybackOwnerHold } from "./copyback-owner-hold.js"; import { applyObservedFenceProviderProof, observedWorkspaceFenceOwner, settleObservedWorkspaceFence } from "./observed-workspace-fence.js"; @@ -968,7 +968,8 @@ export const OWNABLE_KINDS: readonly OwnableKind[] = [ listInProgress: async (db, limit, offset) => { const rows = await db.select({ id: executionWorkspaces.id, companyId: executionWorkspaces.companyId, metadata: executionWorkspaces.metadata, updatedAt: executionWorkspaces.updatedAt }).from(executionWorkspaces) - .where(sql`(${executionWorkspaces.metadata}->'remoteWorkspace'->>'dirty')::boolean is true`).orderBy(asc(executionWorkspaces.id)).limit(limit + 1).offset(offset); + .where(and(sql`(${executionWorkspaces.metadata}->'remoteWorkspace'->>'dirty')::boolean is true`, + preparationOnlyWriterCondition())).orderBy(asc(executionWorkspaces.id)).limit(limit + 1).offset(offset); const result = page(rows, limit); return { truncated: result.truncated, records: result.rows.map(row => { const writerRunId = str(json(json(row.metadata).remoteWorkspace).writerRunId); @@ -983,7 +984,7 @@ export const OWNABLE_KINDS: readonly OwnableKind[] = [ listInProgress: async (db, limit, offset) => { const rows = await db.select({ id: executionWorkspaceSnapshots.id, companyId: executionWorkspaceSnapshots.companyId, sourceRunId: executionWorkspaceSnapshots.sourceRunId, updatedAt: executionWorkspaceSnapshots.updatedAt }) - .from(executionWorkspaceSnapshots).where(inArray(executionWorkspaceSnapshots.status, ["pending", "uploaded"])).orderBy(asc(executionWorkspaceSnapshots.id)).limit(limit + 1).offset(offset); + .from(executionWorkspaceSnapshots).where(retirableRemoteSnapshotLedgerCondition()).orderBy(asc(executionWorkspaceSnapshots.id)).limit(limit + 1).offset(offset); const result = page(rows, limit); return { truncated: result.truncated, records: result.rows.map(row => ({ recordId: row.id, companyId: row.companyId, runId: row.sourceRunId, issueId: null, diff --git a/server/src/services/recovery/remote-snapshot-ledger-settlement.ts b/server/src/services/recovery/remote-snapshot-ledger-settlement.ts index 9a5dbe2bf94..dbd6df0a7fb 100644 --- a/server/src/services/recovery/remote-snapshot-ledger-settlement.ts +++ b/server/src/services/recovery/remote-snapshot-ledger-settlement.ts @@ -1,4 +1,4 @@ -import { and, eq, isNull, sql } from "drizzle-orm"; +import { and, eq, isNull, sql, type SQL } from "drizzle-orm"; import { executionWorkspaceSnapshots, executionWorkspaces, heartbeatRuns, workspaceOperations, type Db } from "@paperclipai/db"; import { readRemoteWorkspaceAuthority } from "@paperclipai/shared"; import { persistActivity, publishActivity, type ActivityPublication } from "../activity-log.js"; @@ -14,6 +14,16 @@ const TERMINAL_RUN_STATUSES = ["succeeded", "failed", "cancelled", "timed_out", type Snapshot = typeof executionWorkspaceSnapshots.$inferSelect; +export function retirableRemoteSnapshotLedgerCondition(): SQL { + return and(eq(executionWorkspaceSnapshots.status, "pending"), isNull(executionWorkspaceSnapshots.objectKey), + sql`not exists (select 1 from workspace_operations operation where operation.company_id = ${executionWorkspaceSnapshots.companyId} + and operation.id = ${executionWorkspaceSnapshots.sourceOperationId} and operation.phase <> 'remote_workspace_snapshot')`, + sql`not exists (select 1 from execution_workspaces workspace where workspace.company_id = ${executionWorkspaceSnapshots.companyId} + and workspace.id = ${executionWorkspaceSnapshots.executionWorkspaceId} + and workspace.metadata->'remoteWorkspace'->>'writerRunId' = ${executionWorkspaceSnapshots.sourceRunId}::text + and workspace.metadata->'remoteWorkspace'->>'epoch' = ${executionWorkspaceSnapshots.epoch}::text)`)!; +} + export async function retireEndedRemoteSnapshotLedgerRow(tx: Db, input: { companyId: string; snapshotId: string; now: Date; proof: string; }): Promise<{ retired: true; snapshot: Snapshot; status: "deleted" | "delete_requested" } | { retired: false; reason: string }> { diff --git a/server/src/services/recovery/remote-workspace-unsaved-files-settlement.ts b/server/src/services/recovery/remote-workspace-unsaved-files-settlement.ts index 5931f763b7e..bdc51aa68b4 100644 --- a/server/src/services/recovery/remote-workspace-unsaved-files-settlement.ts +++ b/server/src/services/recovery/remote-workspace-unsaved-files-settlement.ts @@ -1,4 +1,4 @@ -import { and, eq, inArray, like, or, sql } from "drizzle-orm"; +import { and, eq, inArray, like, or, sql, type SQL } from "drizzle-orm"; import { executionWorkspaces, heartbeatRunEvents, heartbeatRuns, nativeRunFinalizations, workspaceOperations, type Db } from "@paperclipai/db"; import { readRemoteWorkspaceAuthority } from "@paperclipai/shared"; import type { OwnerProof } from "../owner-proof.js"; @@ -11,17 +11,36 @@ const TERMINAL_RUN_STATUSES = ["succeeded", "failed", "cancelled", "timed_out", const WORK_STARTED_EVENT_TYPES = ["adapter.invoke", "adapter.progress"]; const WORK_STARTED_EVENT_PREFIXES = ["turn.", "provider.", "native.process_"]; +const WRITER_RUN_ID = sql`${executionWorkspaces.metadata}->'remoteWorkspace'->>'writerRunId'`; + +export function preparationOnlyWriterCondition(): SQL { + const workStarted = sql.join([ + sql`event.event_type in (${sql.join(WORK_STARTED_EVENT_TYPES.map(type => sql`${type}`), sql`, `)})`, + ...WORK_STARTED_EVENT_PREFIXES.map(prefix => sql`event.event_type like ${`${prefix}%`}`), + ], sql` or `); + return sql`(${WRITER_RUN_ID} is null or exists (select 1 from heartbeat_runs writer + where writer.id = (case when ${WRITER_RUN_ID} ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + then (${WRITER_RUN_ID})::uuid end) and writer.company_id = ${executionWorkspaces.companyId} + and writer.execution_stage = 'preparing' and writer.runtime_mode_resolved_at is null + and writer.process_pid is null and writer.process_group_id is null + and writer.native_session_id is null and writer.runner_instance_id is null + and not exists (select 1 from native_run_finalizations finalization + where finalization.company_id = writer.company_id and finalization.run_id = writer.id) + and not exists (select 1 from heartbeat_run_events event where event.run_id = writer.id and (${workStarted}))))`; +} + export async function settlePreparationOnlyRemoteWorkspaceEpoch(db: Db, record: InProgressRecord, context: { now: Date; proof: OwnerProof }): Promise { if (record.owner.kind !== "run" || !record.runId || !record.companyId) return { settled: false, reason: "owner_not_provable" }; const runId = record.runId, companyId = record.companyId; return db.transaction(async (transaction): Promise => { const tx = transaction as unknown as Db; - const [run] = await tx.select({ status: heartbeatRuns.status, executionStage: heartbeatRuns.executionStage, + const readRun = () => tx.select({ status: heartbeatRuns.status, executionStage: heartbeatRuns.executionStage, runtimeModeResolvedAt: heartbeatRuns.runtimeModeResolvedAt, processPid: heartbeatRuns.processPid, processGroupId: heartbeatRuns.processGroupId, nativeSessionId: heartbeatRuns.nativeSessionId, runnerInstanceId: heartbeatRuns.runnerInstanceId }) - .from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, runId))).for("update"); + .from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, runId))); + const [run] = await readRun(); if (!run || !TERMINAL_RUN_STATUSES.includes(run.status)) return { settled: false, reason: "owner_run_active" }; if (run.runtimeModeResolvedAt || run.executionStage !== "preparing") return { settled: false, reason: "writer_reached_runtime", watch: false }; const [finalization] = await tx.select({ runId: nativeRunFinalizations.runId }).from(nativeRunFinalizations) @@ -44,6 +63,10 @@ export async function settlePreparationOnlyRemoteWorkspaceEpoch(db: Db, record: eq(workspaceOperations.phase, "remote_workspace_snapshot"), inArray(workspaceOperations.status, ["running", "pending"]), sql`${workspaceOperations.metadata}->>'epoch' = ${String(authority.epoch)}`)).limit(1); if (save) return { settled: false, reason: "save_in_flight" }; + const [locked] = await readRun().for("update"); + if (!locked || !TERMINAL_RUN_STATUSES.includes(locked.status)) return { settled: false, reason: "owner_run_active" }; + if (locked.runtimeModeResolvedAt || locked.executionStage !== "preparing" || locked.processPid || locked.processGroupId + || locked.nativeSessionId || locked.runnerInstanceId) return { settled: false, reason: "writer_reached_runtime", watch: false }; // A preparation that restored the saved version and then did nothing else // left exactly that version in its root. When the durable unchanged-baseline // proof holds, hand the workspace on at its saved version and keep the root, diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 52b165c4bb5..0cb4576f41e 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -322,6 +322,8 @@ type LatestIssueRun = retryOfRunId?: string | null; scheduledRetryReason?: string | null; runnerProfileJson?: unknown; + runtimeMode?: string | null; + controllerBootId?: string | null; }) | null; type SuccessfulLatestIssueRun = NonNullable & { @@ -1099,6 +1101,8 @@ export function recoveryService( retryOfRunId: heartbeatRuns.retryOfRunId, scheduledRetryReason: heartbeatRuns.scheduledRetryReason, runnerProfileJson: heartbeatRuns.runnerProfileJson, + runtimeMode: heartbeatRuns.runtimeMode, + controllerBootId: heartbeatRuns.controllerBootId, }) .from(heartbeatRuns) .where( @@ -1208,8 +1212,11 @@ export function recoveryService( * a live execution; another process proves it with its unexpired controller * lease, which it clears once settlement (retry scheduling, claim release) * is done. This process's own lease without a live execution is stale. */ - async function terminalRunSettlingUntil(companyId: string, runId: string): Promise { + async function terminalRunSettlingUntil(companyId: string, runId: string, + known?: { runtimeMode?: string | null; controllerBootId?: string | null }): Promise { if (deps.liveRunExecutions?.has(runId)) return new Date(Date.now() + 30_000); + if (known?.runtimeMode !== undefined && (known.runtimeMode !== "legacy" || !known.controllerBootId + || known.controllerBootId === legacyControllerBootId)) return null; const [run] = await db.select({ leaseExpiresAt: heartbeatRuns.controllerLeaseExpiresAt }) .from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, runId), eq(heartbeatRuns.runtimeMode, "legacy"), sql`${heartbeatRuns.controllerBootId} is not null`, @@ -4755,7 +4762,7 @@ export function recoveryService( || await isAutomaticRecoverySuppressedByPauseHold(db, issue.companyId, issue.id, treeControlSvc)) continue; // Another server is still settling the run: look again when its lease // lapses, since later generic skips may never reach their own check. - const settlingUntil = await terminalRunSettlingUntil(issue.companyId, run.id); + const settlingUntil = await terminalRunSettlingUntil(issue.companyId, run.id, latestRun); if (settlingUntil) { onDeferredDeadline?.(settlingUntil.getTime()); handled.add(issue.id); @@ -4937,7 +4944,7 @@ export function recoveryService( // and releases the claim itself. Escalating in that window clears the // claim the retry needs. Re-check once its controller lease lapses. const settlingUntil = latestRun && isTerminalIssueRun(latestRun) - ? await terminalRunSettlingUntil(issue.companyId, latestRun.id) : null; + ? await terminalRunSettlingUntil(issue.companyId, latestRun.id, latestRun) : null; if (settlingUntil) { opts?.onDeferredDeadline?.(settlingUntil.getTime()); result.skipped += 1; From f71aa135a0d52a1f86b81bb2a1f3e10db6bf4cde Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 15 Nov 2026 12:54:23 -0600 Subject: [PATCH 5/5] fix(server): release sandbox leases for runs stopped before runner attach (#21788) 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 > - Agents in a `sandbox` environment run each task in a paid remote sandbox that an environment lease tracks > - When a run stops, the control plane must release that lease, and terminating an agent waits until every lease of the agent is released > - In a load test, a run stopped after its sandbox was ready but before its runner started never released its lease, so the sandbox kept running and the agent stayed in "terminating" forever > - In the same test, terminating an agent whose failed run had a scheduled same-run retry waited about 18 minutes, until the stale retry time > - This pull request makes lease release finish for every stop window, records any release that must wait with a retry time, adds a hint-driven safety net, and makes termination cancel a pending native retry at once > - The benefit is that a stopped run never leaves a paid sandbox running, and agent termination finishes in seconds without manual repair ## Linked Issues or Issue Description **What happened?** A load test with ten OpenCode agents in a `sandbox` environment stopped its agents mid-run (pause, then terminate). Two defects appeared. 1. A run cancelled while it selected its provider pack (after the sandbox was acquired and the workspace was prepared, before the runner started) kept its environment lease `active` for more than 40 minutes. The agent stayed in lifecycle `terminating`. The lifecycle worker retried every pass and wrote `updatedAt` each time with no recorded reason. Delete returned 409 "Complete termination before deleting the agent". 2. A failed native run with a scheduled bootstrap retry kept its lease until the stale retry time. Agent termination took about 18 minutes. The run still showed "retry_scheduled" after the agent was terminated. **Expected behavior** A stopped run releases its sandbox lease within seconds. If release must wait, the wait has a recorded reason and retry time, and a background pass finishes it. Terminating an agent cancels a pending retry, releases its lease, and reaches `terminated` promptly. **Steps to reproduce** 1. Start a native run in a `sandbox` environment. 2. Stop it after the sandbox is acquired and the workspace is prepared, before the runner starts. 3. Pause and then terminate the agent. 4. See that the lease stays `active` and the agent stays `terminating`. **Paperclip version or commit** Reproduced on `master` at 62033b9994 (load test build 2026.1106.0+2564). **Relevant logs or output** Root causes found in the code: - `releaseEnvironmentLeasesForRun` returned with no record when workspace retention refused a cancelled run. The refusal was permanent when the run's native finalization owner had expired but was not cleared. The owner is cleared only after `agentExecutionsHaveStopped` sees every lease released, so the two waited on each other. - `releaseRunLeases` silently skipped a lease whose prepared native workspace was still "pending export", even for a run that never started a runner and so never changed those files. - The destroy path deferred on any busy warm session in the same environment, also with no record. - `stopInvocationsForAgents` returned on the first run that was still live, so it did not release the leases of the other runs of the agent. - The agent stop cancelled only `queued`, `running` and `scheduled_retry` runs. A failed native run with a pending same-run retry kept its lease until that retry fired. - The lifecycle worker deferred a pending host step by 2 seconds every pass, with no reason and no backoff. ## What Changed - `releaseEnvironmentLeasesForRun` (`run-control.ts`): - A native run with no runner launch evidence (no `native.process_start_requested`, no runner event, no process id) skips workspace retention and warm-session closing. No runner process exists to fence, and no work ran against the prepared files. - When retention is refused only because the run's native finalization owner lease has expired, the release clears that expired owner (compare-and-set on the exact expired owner of a cancelled run with no result) and retries retention once. A recorded recovery then stops and retains the sandbox, so the files stay recoverable. - Every release that cannot finish now records `metadata.releaseDeferral` (`reason`, `attempts`, `retryAt`, disposition) on the active lease and publishes an `orphan-active-leases` hint. The retry time backs off from 30 seconds to 15 minutes, then retries hourly without end. The record keeps `failingSince` and the last reason. A new Stop or terminate operation, or a server restart, triggers an immediate attempt. - `nativeWorkspaceExportPendingForLease` treats a cancelled run with no runner launch evidence as owing no export. - Safety net: `sweepOrphanedActiveLeases` (the existing hint- and deadline-driven orphan-lease work) now retries the run's own release for a due deferral or for a cancelled native run, after the native owner lease has expired. The orphan-lease loader uses the stored `retryAt` as the due time. No new timer or poller. - Agent stop: - It cancels a failed native run that has a pending same-run retry (or an interrupted cancellation of one), through the existing retry-cancellation path. A pause stamps `pauseStop` on those runs too, so a budget resume can continue them. - It releases the leases of every terminal run, and it skips a lease whose deferral is not yet due. - `agentInvocationStopBlocker` and `agentExecutionStopBlocker` return why the stop must still wait. - Lifecycle worker: a pending host or plugin step records `pendingReason` and `pendingPasses` on the operation, and its retry backs off from 2 seconds to a 60 second cap. When a release leaves a run with no unsettled lease, the stopping agent's saved retry time is cleared and the lifecycle queue is notified, so Pause or Terminate finishes on the next pass. - Cancelled-workspace preservation: a stopped run that never started a runner has its prepared reference moved to `nativeWorkspaceSyncReleasedUnchanged` when its lease is released, so the preservation worker no longer selects it. The worker records the same settlement itself for older runs, and waits on a live owner's exact lease expiry. ## Verification - Red on `master`, green on this branch (embedded PostgreSQL, fake plugin sandbox provider): - `server/src/__tests__/heartbeat-lease-release-before-runner-attach.test.ts`: agent pause then terminate, and board Stop, for each window between sandbox acquire and runner attach (artifact discovery, pack select, pack upload, runner launch, transport connect, session open). Each test checks that the provider gets a stop or destroy call, the lease is released, the run is cancelled, and the agent reaches `terminated` within one extra worker pass. It also checks the orphan-lease safety net for a leaked lease and a recorded deferral that the background pass finishes when due. - `server/src/__tests__/heartbeat-terminate-pending-native-retry.test.ts`: terminating an agent whose failed run has a bootstrap retry 17 minutes away cancels the retry, releases the lease and reaches `terminated` at once. The test covers an open task and a cancelled task. - `server/src/modules/agent-lifecycle/__tests__/pending-backoff.test.ts`: a host step that stays pending records its reason, and its retry delay grows to a 60 second cap. - Related suites pass: run-control, recovery, orphaned active lease sweep, environment runtime, agent lifecycle, native workspace preservation and recovery, held comment wake. - `server` typecheck passes. ## Risks - A cancelled native run with no launch evidence now gets its prepared sandbox destroyed instead of kept. The proof is the same launch evidence that restart recovery uses. - A launched cancelled run whose retention owes nothing is stopped and retained, as before. A retention that throws (lock or write error, or a live owner) now keeps the lease active with a recorded reason and retry time, instead of a silent skip. - Release now clears an expired native finalization owner of a cancelled run. An old controller whose lease already expired then fails its next owner check and stops, which is the normal lease rule. - On the first start after deploy, the orphan-lease work releases leases already leaked by cancelled native runs. - Task state after pause then terminate: the run-scoped stop keeps the task status (an open task stays open, a cancelled task stays cancelled), and a run that held prepared files gets the existing workspace recovery record on its stopped sandbox. No new state is added. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (code search, shell, test runs). ## 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 - [ ] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] 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: Claude Opus 5.5 --- ...lease-release-before-runner-attach.test.ts | 285 ++++++++++++++++++ ...eat-terminate-pending-native-retry.test.ts | 140 +++++++++ .../__tests__/driver-scope.test.ts | 4 +- .../__tests__/pending-backoff.test.ts | 86 ++++++ .../agent-lifecycle/adapters/postgres.ts | 30 +- .../agent-lifecycle/application/ports.ts | 4 +- .../agent-lifecycle/application/worker.ts | 7 +- server/src/modules/agent-lifecycle/index.ts | 2 +- server/src/services/agent-execution-stop.ts | 31 +- server/src/services/agent-lifecycle-driver.ts | 11 +- ...environment-lease-release-deferral.test.ts | 61 ++++ .../environment-lease-release-deferral.ts | 96 ++++++ server/src/services/heartbeat.ts | 32 +- .../services/heartbeat/live-recovery-work.ts | 9 +- server/src/services/heartbeat/recovery.ts | 38 +++ .../services/heartbeat/run-control.test.ts | 114 ++++++- server/src/services/heartbeat/run-control.ts | 106 ++++++- ...celled-workspace-preservation-idle.test.ts | 103 +++++++ .../native-failed-workspace-recovery.ts | 10 +- .../native-workspace-finalization-state.ts | 9 +- 20 files changed, 1126 insertions(+), 52 deletions(-) create mode 100644 server/src/__tests__/heartbeat-lease-release-before-runner-attach.test.ts create mode 100644 server/src/__tests__/heartbeat-terminate-pending-native-retry.test.ts create mode 100644 server/src/modules/agent-lifecycle/__tests__/pending-backoff.test.ts create mode 100644 server/src/services/environment-lease-release-deferral.test.ts create mode 100644 server/src/services/environment-lease-release-deferral.ts create mode 100644 server/src/services/native-runtime/native-cancelled-workspace-preservation-idle.test.ts diff --git a/server/src/__tests__/heartbeat-lease-release-before-runner-attach.test.ts b/server/src/__tests__/heartbeat-lease-release-before-runner-attach.test.ts new file mode 100644 index 00000000000..f1f5229d7eb --- /dev/null +++ b/server/src/__tests__/heartbeat-lease-release-before-runner-attach.test.ts @@ -0,0 +1,285 @@ +import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { + agents, + companies, + createDb, + environmentLeases, + environments, + heartbeatRunEvents, + heartbeatRuns, + issues, + nativeRunFinalizations, + plugins, +} from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +const mockTelemetryClient = vi.hoisted(() => ({ track: vi.fn() })); +vi.mock("../telemetry.ts", () => ({ getTelemetryClient: () => mockTelemetryClient })); + +import { heartbeatService } from "../services/heartbeat.ts"; +import { createLifecycleDriver } from "../services/agent-lifecycle-driver.js"; +import { configureAgentLifecycle, createAgentLifecycle } from "../services/agent-lifecycle.js"; +import { PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED } from "../services/native-local-process-stop.js"; +import type { PluginWorkerManager } from "../services/plugin-worker-manager.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = support.supported ? describe : describe.skip; + +type Window = "artifact_discovery" | "provider_pack_select" | "provider_pack_upload" | "runner_launch" | "transport_connect" | "session_open"; +const PRE_LAUNCH: Window[] = ["artifact_discovery", "provider_pack_select", "provider_pack_upload"]; +const ALL_WINDOWS: Window[] = [...PRE_LAUNCH, "runner_launch", "transport_connect", "session_open"]; +const PROVIDER_METHODS = ["environmentAcquireLease", "environmentExecute", "environmentReleaseLease", + "environmentDestroyLease", "environmentStopLease"]; + +describeEmbeddedPostgres("environment lease release between sandbox acquire and runner attach", () => { + let db!: ReturnType; + let tempDb: Awaited> | null = null; + const workers: Array<{ stop(): Promise }> = []; + + beforeAll(async () => { + tempDb = await startEmbeddedPostgresTestDatabase("paperclip-lease-release-before-attach-"); + db = createDb(tempDb.connectionString); + }, 30_000); + + afterEach(async () => { + for (const worker of workers.splice(0)) await worker.stop(); + }); + + afterAll(async () => { + await tempDb?.cleanup(); + }); + + function providerWorker(pluginId: string) { + const call = vi.fn(async (_pluginId: string, method: string, params: { providerLeaseId?: string }) => { + if (method === "environmentDestroyLease") return { providerLeaseId: params.providerLeaseId, state: "destroyed" }; + if (method === "environmentStopLease") return { providerLeaseId: params.providerLeaseId, state: "stopped" }; + if (method === "environmentReleaseLease") return { providerLeaseId: params.providerLeaseId, state: "destroyed" }; + throw new Error(`Unexpected provider method ${method}`); + }); + const manager = { + isRunning: vi.fn((id: string) => id === pluginId), + getWorker: vi.fn(() => ({ supportedMethods: PROVIDER_METHODS })), + call, + } as unknown as PluginWorkerManager; + const teardownCalls = () => call.mock.calls.filter(([, method]) => + method === "environmentDestroyLease" || method === "environmentStopLease" || method === "environmentReleaseLease"); + return { manager, teardownCalls }; + } + + async function seed(window: Window) { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(); + const environmentId = randomUUID(), leaseId = randomUUID(), pluginId = randomUUID(); + const providerLeaseId = `sandbox-${randomUUID()}`; + const pluginKey = `paperclip.lease-release-${pluginId.slice(0, 8)}`; + await db.insert(plugins).values({ id: pluginId, pluginKey, packageName: "@paperclipai/plugin-fake-sandbox", version: "1.0.0", + apiVersion: 1, categories: ["automation"], status: "ready", installOrder: 1, updatedAt: new Date(), + manifestJson: { id: pluginKey, apiVersion: 1, version: "1.0.0", displayName: "Fake sandbox", description: "Test provider", + author: "Paperclip", categories: ["automation"], capabilities: ["environment.drivers.register"], + entrypoints: { worker: "dist/worker.js" }, + environmentDrivers: [{ driverKey: "fake-plugin", kind: "sandbox_provider", displayName: "Fake Plugin", + configSchema: { type: "object" } }] } } as never); + await db.insert(companies).values({ id: companyId, name: "Paperclip", + issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`, requireBoardApprovalForNewAgents: false }); + await db.insert(agents).values({ id: agentId, companyId, name: "OpenCoder", role: "engineer", status: "running", + adapterType: "paperclip_runner", adapterConfig: { provider: "opencode" }, runtimeConfig: {}, permissions: {} }); + await db.insert(issues).values({ id: issueId, companyId, title: "Short task", status: "in_progress", + priority: "medium", assigneeAgentId: agentId }); + const config = { provider: "fake-plugin", image: "fake:test", timeoutMs: 1234, reuseLease: false }; + await db.insert(environments).values({ id: environmentId, name: `Fake sandbox ${environmentId}`, driver: "sandbox", + status: "active", config }); + const startedAt = new Date(Date.now() - 10_000); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "assignment", status: "running", + runtimeMode: "native", runtimeModeResolvedAt: startedAt, issueId, nativeIssueId: issueId, startedAt, + contextSnapshot: { issueId }, nextEventSeq: 1, + runnerProfileJson: { nativeWorkspaceSync: { + schema: "paperclip.native-workspace-sync/v3", state: "prepared", descriptorSha256: "a".repeat(64), + baselineSha256: "b".repeat(64), finalHostSha256: null, workspaceId: randomUUID(), leaseId, providerLeaseId, + remoteCwd: "/workspace", resourceDisposition: "destroy" } } }); + await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId)); + await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "observed", attempt: 1, + controllerGeneration: 1, leaseOwner: `executor-${runId}`, leaseExpiresAt: new Date(Date.now() - 1_000) }); + await db.insert(environmentLeases).values({ id: leaseId, companyId, environmentId, heartbeatRunId: runId, issueId, + status: "active", leasePolicy: "ephemeral", provider: "fake-plugin", providerLeaseId, + metadata: { ...config, agentId, driver: "sandbox", pluginId, pluginKey, sandboxProviderPlugin: true, + remoteCwd: "/workspace", sandboxState: "started" } }); + const events: Array<{ eventType: string; sourceEventId?: string }> = []; + if (!PRE_LAUNCH.includes(window)) events.push({ eventType: PROCESS_START_REQUESTED }); + if (window === "transport_connect" || window === "session_open") events.push({ eventType: PROCESS_IDENTITY_RECORDED }); + if (window === "session_open") events.push({ eventType: "session.started", sourceEventId: randomUUID() }); + for (const [index, event] of events.entries()) { + await db.insert(heartbeatRunEvents).values({ companyId, runId, agentId, seq: index + 1, eventType: event.eventType, + stream: "system", level: "info", message: event.eventType, sourceEventId: event.sourceEventId ?? null }); + } + await db.update(heartbeatRuns).set({ nextEventSeq: events.length + 1 }).where(eq(heartbeatRuns.id, runId)); + return { companyId, agentId, issueId, runId, leaseId, providerLeaseId, ...providerWorker(pluginId) }; + } + + async function lease(leaseId: string) { + return (await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0]!; + } + + async function run(runId: string) { + return (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]!; + } + + async function expectSandboxReleased(fixture: Awaited>) { + let row = await lease(fixture.leaseId); + if (row.status === "pending_cleanup") { + await heartbeatService(db, { pluginWorkerManager: fixture.manager }).sweepPendingCleanupLeases({ backoffMs: 0 }); + row = await lease(fixture.leaseId); + } + expect(row.status).not.toBe("active"); + expect(row.status).not.toBe("pending_cleanup"); + expect(row.releasedAt).not.toBeNull(); + expect(fixture.teardownCalls()).toContainEqual([expect.any(String), expect.any(String), + expect.objectContaining({ providerLeaseId: fixture.providerLeaseId }), expect.any(Number)]); + } + + it.each(ALL_WINDOWS)("terminating the agent releases a sandbox leased during %s", async window => { + const fixture = await seed(window); + const lifecycle = createAgentLifecycle(db); + const worker = configureAgentLifecycle(db, createLifecycleDriver(db, fixture.manager)); + workers.push(worker); + await lifecycle.pauseAgent(fixture.agentId); + await worker.process(fixture.agentId); + await lifecycle.terminateAgent(fixture.agentId); + let agent = (await db.select().from(agents).where(eq(agents.id, fixture.agentId)))[0]!; + let passes = 0; + for (; agent.lifecycleState !== "terminated" && passes < 4; passes++) { + await db.update(agents).set({ lifecycleOperation: { ...agent.lifecycleOperation!, retryAt: undefined } }) + .where(eq(agents.id, fixture.agentId)); + await worker.process(fixture.agentId); + agent = (await db.select().from(agents).where(eq(agents.id, fixture.agentId)))[0]!; + } + expect(agent.lifecycleState).toBe("terminated"); + expect(passes).toBeLessThanOrEqual(1); + const stopped = await run(fixture.runId); + expect(stopped.status).toBe("cancelled"); + await expectSandboxReleased(fixture); + if (PRE_LAUNCH.includes(window)) { + expect(stopped.runnerProfileJson).not.toHaveProperty("nativeWorkspaceSync"); + expect(stopped.runnerProfileJson).toHaveProperty("nativeWorkspaceSyncReleasedUnchanged.state", "prepared"); + } else { + expect(stopped.resultJson).toHaveProperty("workspaceRestoreRecovery.schema", "paperclip.workspace-restore-recovery.v1"); + } + }, 60_000); + + it.each(ALL_WINDOWS)("stopping the run releases a sandbox leased during %s", async window => { + const fixture = await seed(window); + const heartbeat = heartbeatService(db, { pluginWorkerManager: fixture.manager }); + await heartbeat.cancelRun(fixture.runId, "Cancelled by a board operator", { + resultJson: { cancelledByActorType: "user", cancelledByUserId: "operator" } }); + expect((await run(fixture.runId)).status).toBe("cancelled"); + await heartbeat.sweepOrphanedActiveLeases({ companyId: fixture.companyId, leaseId: fixture.leaseId, backoffMs: 5 * 60_000 }); + await expectSandboxReleased(fixture); + }, 60_000); + + it("records a release a live workspace owner holds back and finishes it in the background once due", async () => { + const fixture = await seed("runner_launch"); + const ownerUntil = new Date(Date.now() + 60_000); + await db.update(nativeRunFinalizations).set({ leaseExpiresAt: ownerUntil }).where(eq(nativeRunFinalizations.runId, fixture.runId)); + await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(), errorCode: "cancelled" }) + .where(eq(heartbeatRuns.id, fixture.runId)); + const heartbeat = heartbeatService(db, { pluginWorkerManager: fixture.manager }); + await heartbeat.releaseEnvironmentLeasesForRun({ runId: fixture.runId, companyId: fixture.companyId, + agentId: fixture.agentId, status: "cancelled", providerResourceDisposition: "destroy" }); + const deferred = await lease(fixture.leaseId); + expect(deferred.status).toBe("active"); + expect(deferred.metadata?.releaseDeferral).toMatchObject({ reason: "workspace_owner_active", attempts: 1, + providerResourceDisposition: "destroy" }); + expect(fixture.teardownCalls()).toHaveLength(0); + + const deadlines: number[] = []; + await heartbeat.sweepOrphanedActiveLeases({ companyId: fixture.companyId, leaseId: fixture.leaseId, backoffMs: 5 * 60_000, + onDeferredDeadline: at => deadlines.push(at) }); + expect((await lease(fixture.leaseId)).status).toBe("active"); + expect(deadlines).toContain(Date.parse(String((deferred.metadata?.releaseDeferral as { retryAt: string }).retryAt))); + + await db.update(nativeRunFinalizations).set({ leaseExpiresAt: new Date(Date.now() - 1_000) }) + .where(eq(nativeRunFinalizations.runId, fixture.runId)); + await db.update(environmentLeases).set({ metadata: { ...deferred.metadata, + releaseDeferral: { ...(deferred.metadata?.releaseDeferral as object), retryAt: new Date(Date.now() - 1_000).toISOString() } } }) + .where(eq(environmentLeases.id, fixture.leaseId)); + await heartbeat.sweepOrphanedActiveLeases({ companyId: fixture.companyId, leaseId: fixture.leaseId, backoffMs: 5 * 60_000 }); + await expectSandboxReleased(fixture); + }, 60_000); + + async function terminate(fixture: Awaited>) { + const lifecycle = createAgentLifecycle(db); + const worker = configureAgentLifecycle(db, createLifecycleDriver(db, fixture.manager)); + workers.push(worker); + await lifecycle.terminateAgent(fixture.agentId); + await worker.process(fixture.agentId); + return (await db.select().from(agents).where(eq(agents.id, fixture.agentId)))[0]!; + } + + it("finishes a release that lock conflicts held back, preserving the files, once the locks clear", async () => { + const fixture = await seed("runner_launch"); + await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(), errorCode: "cancelled" }) + .where(eq(heartbeatRuns.id, fixture.runId)); + const heartbeat = heartbeatService(db, { pluginWorkerManager: fixture.manager }); + let ready!: () => void, unlock!: () => void; + const locked = new Promise(resolve => { ready = resolve; }); + const released = new Promise(resolve => { unlock = resolve; }); + const holder = db.transaction(async tx => { + await tx.select({ id: issues.id }).from(issues).where(eq(issues.id, fixture.issueId)).for("update"); + ready(); await released; + }); + await locked; + try { + for (let attempt = 1; attempt <= 3; attempt++) { + await heartbeat.releaseEnvironmentLeasesForRun({ runId: fixture.runId, companyId: fixture.companyId, + agentId: fixture.agentId, status: "cancelled", providerResourceDisposition: "destroy" }); + expect((await lease(fixture.leaseId)).metadata?.releaseDeferral).toMatchObject({ reason: "workspace_retention_busy", attempts: attempt }); + } + } finally { unlock(); await holder; } + const deferred = await lease(fixture.leaseId); + await db.update(environmentLeases).set({ metadata: { ...deferred.metadata, releaseDeferral: { + ...(deferred.metadata?.releaseDeferral as object), retryAt: new Date(Date.now() - 1_000).toISOString() } } }) + .where(eq(environmentLeases.id, fixture.leaseId)); + await heartbeat.sweepOrphanedActiveLeases({ companyId: fixture.companyId, leaseId: fixture.leaseId, backoffMs: 5 * 60_000 }); + await expectSandboxReleased(fixture); + expect((await run(fixture.runId)).resultJson).toHaveProperty("workspaceRestoreRecovery.schema", "paperclip.workspace-restore-recovery.v1"); + expect((await terminate(fixture)).lifecycleState).toBe("terminated"); + }, 60_000); + + it("attempts a slow-phase deferred release at once when the agent is terminated", async () => { + const fixture = await seed("runner_launch"); + await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(), errorCode: "cancelled" }) + .where(eq(heartbeatRuns.id, fixture.runId)); + const current = await lease(fixture.leaseId); + await db.update(environmentLeases).set({ metadata: { ...current.metadata, releaseDeferral: { reason: "release_failed", + attempts: 8, retryAt: new Date(Date.now() + 60 * 60_000).toISOString(), failingSince: new Date(Date.now() - 3 * 3_600_000).toISOString(), + providerResourceDisposition: "destroy" } } }).where(eq(environmentLeases.id, fixture.leaseId)); + expect((await terminate(fixture)).lifecycleState).toBe("terminated"); + await expectSandboxReleased(fixture); + }, 60_000); + + it("gives each overlapping stop operation one immediate attempt, then respects the stored retry time", async () => { + const fixture = await seed("runner_launch"); + await db.update(nativeRunFinalizations).set({ leaseExpiresAt: new Date(Date.now() + 60 * 60_000) }) + .where(eq(nativeRunFinalizations.runId, fixture.runId)); + await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(), errorCode: "cancelled" }) + .where(eq(heartbeatRuns.id, fixture.runId)); + const heartbeat = heartbeatService(db, { pluginWorkerManager: fixture.manager }); + const parent = `lifecycle:${randomUUID()}`, child = `lifecycle:${randomUUID()}`; + for (let pass = 0; pass < 30; pass++) { + expect(await heartbeat.agentInvocationStopBlocker([fixture.agentId], "Agent lifecycle stop requested", + { trigger: pass % 2 === 0 ? parent : child })).toMatch(/^environment_lease_release_deferred:workspace_owner_active$/); + } + expect((await lease(fixture.leaseId)).metadata?.releaseDeferral).toMatchObject({ reason: "workspace_owner_active", + attempts: 2, triggers: [parent, child] }); + expect(fixture.teardownCalls()).toHaveLength(0); + }, 60_000); + + it.each(PRE_LAUNCH)("the orphan lease check releases a sandbox a cancelled run leaked during %s", async window => { + const fixture = await seed(window); + await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(), errorCode: "cancelled" }) + .where(eq(heartbeatRuns.id, fixture.runId)); + const heartbeat = heartbeatService(db, { pluginWorkerManager: fixture.manager }); + await heartbeat.sweepOrphanedActiveLeases({ companyId: fixture.companyId, leaseId: fixture.leaseId, backoffMs: 5 * 60_000 }); + await expectSandboxReleased(fixture); + }, 60_000); +}); diff --git a/server/src/__tests__/heartbeat-terminate-pending-native-retry.test.ts b/server/src/__tests__/heartbeat-terminate-pending-native-retry.test.ts new file mode 100644 index 00000000000..1ab7ee3c733 --- /dev/null +++ b/server/src/__tests__/heartbeat-terminate-pending-native-retry.test.ts @@ -0,0 +1,140 @@ +import { randomUUID } from "node:crypto"; +import { and, eq } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { + agents, + companies, + createDb, + environmentLeases, + environments, + heartbeatRunEvents, + heartbeatRuns, + issues, + nativeRunFinalizations, + plugins, +} from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +const mockTelemetryClient = vi.hoisted(() => ({ track: vi.fn() })); +vi.mock("../telemetry.ts", () => ({ getTelemetryClient: () => mockTelemetryClient })); + +import { createLifecycleDriver } from "../services/agent-lifecycle-driver.js"; +import { configureAgentLifecycle, createAgentLifecycle } from "../services/agent-lifecycle.js"; +import { PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED } from "../services/native-local-process-stop.js"; +import type { PluginWorkerManager } from "../services/plugin-worker-manager.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = support.supported ? describe : describe.skip; + +describeEmbeddedPostgres("terminating an agent whose failed run has a scheduled bootstrap retry", () => { + let db!: ReturnType; + let tempDb: Awaited> | null = null; + const workers: Array<{ stop(): Promise }> = []; + + beforeAll(async () => { + tempDb = await startEmbeddedPostgresTestDatabase("paperclip-terminate-pending-retry-"); + db = createDb(tempDb.connectionString); + }, 30_000); + + afterEach(async () => { + for (const worker of workers.splice(0)) await worker.stop(); + }); + + afterAll(async () => { + await tempDb?.cleanup(); + }); + + async function seed(issueStatus: "in_progress" | "cancelled") { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(); + const environmentId = randomUUID(), leaseId = randomUUID(), pluginId = randomUUID(); + const providerLeaseId = `sandbox-${randomUUID()}`; + const pluginKey = `paperclip.pending-retry-${pluginId.slice(0, 8)}`; + await db.insert(plugins).values({ id: pluginId, pluginKey, packageName: "@paperclipai/plugin-fake-sandbox", version: "1.0.0", + apiVersion: 1, categories: ["automation"], status: "ready", installOrder: 1, updatedAt: new Date(), + manifestJson: { id: pluginKey, apiVersion: 1, version: "1.0.0", displayName: "Fake sandbox", description: "Test provider", + author: "Paperclip", categories: ["automation"], capabilities: ["environment.drivers.register"], + entrypoints: { worker: "dist/worker.js" }, + environmentDrivers: [{ driverKey: "fake-plugin", kind: "sandbox_provider", displayName: "Fake Plugin", + configSchema: { type: "object" } }] } } as never); + await db.insert(companies).values({ id: companyId, name: "Paperclip", + issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`, requireBoardApprovalForNewAgents: false }); + await db.insert(agents).values({ id: agentId, companyId, name: "OpenCoder", role: "engineer", status: "idle", + adapterType: "paperclip_runner", adapterConfig: { provider: "opencode" }, runtimeConfig: {}, permissions: {} }); + await db.insert(issues).values({ id: issueId, companyId, title: "Short task", status: issueStatus, + priority: "medium", assigneeAgentId: agentId }); + const config = { provider: "fake-plugin", image: "fake:test", timeoutMs: 1234, reuseLease: false }; + await db.insert(environments).values({ id: environmentId, name: `Fake sandbox ${environmentId}`, driver: "sandbox", + status: "active", config }); + const failedAt = new Date(Date.now() - 5_000); + const retryAt = new Date(Date.now() + 17 * 60_000); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "assignment", status: "failed", + runtimeMode: "native", runtimeModeResolvedAt: failedAt, issueId, nativeIssueId: issueId, startedAt: failedAt, + finishedAt: failedAt, errorCode: "native_runner_process_exited", error: "The runner process exited", + contextSnapshot: { issueId }, nextEventSeq: 3, nativePhase: "retryable_failure", + resultJson: { executionRecovery: { kind: "bootstrap", recoverable: true, recoveryMode: "bootstrap_retry", + nextAttemptAt: retryAt.toISOString() } }, + runnerProfileJson: { nativeWorkspaceSync: { + schema: "paperclip.native-workspace-sync/v3", state: "prepared", descriptorSha256: "a".repeat(64), + baselineSha256: "b".repeat(64), finalHostSha256: null, workspaceId: randomUUID(), leaseId, providerLeaseId, + remoteCwd: "/workspace", resourceDisposition: "destroy" } } }); + await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "retryable_failure", attempt: 1, + controllerGeneration: 1, failureCode: "native_runner_process_exited", recoveryState: "scheduled", nextAttemptAt: retryAt }); + await db.insert(environmentLeases).values({ id: leaseId, companyId, environmentId, heartbeatRunId: runId, issueId, + status: "active", leasePolicy: "ephemeral", provider: "fake-plugin", providerLeaseId, + metadata: { ...config, agentId, driver: "sandbox", pluginId, pluginKey, sandboxProviderPlugin: true, + remoteCwd: "/workspace", sandboxState: "started" } }); + for (const [index, eventType] of [PROCESS_START_REQUESTED, PROCESS_IDENTITY_RECORDED].entries()) { + await db.insert(heartbeatRunEvents).values({ companyId, runId, agentId, seq: index + 1, eventType, + stream: "system", level: "info", message: eventType }); + } + const call = vi.fn(async (_pluginId: string, method: string, params: { providerLeaseId?: string }) => { + if (method === "environmentStopLease") return { providerLeaseId: params.providerLeaseId, state: "stopped" }; + if (method === "environmentDestroyLease" || method === "environmentReleaseLease") { + return { providerLeaseId: params.providerLeaseId, state: "destroyed" }; + } + throw new Error(`Unexpected provider method ${method}`); + }); + const manager = { + isRunning: vi.fn((id: string) => id === pluginId), + getWorker: vi.fn(() => ({ supportedMethods: ["environmentReleaseLease", "environmentDestroyLease", "environmentStopLease"] })), + call, + } as unknown as PluginWorkerManager; + return { companyId, agentId, issueId, runId, leaseId, providerLeaseId, manager, call }; + } + + it.each([ + ["in_progress", "in_progress"], + ["cancelled", "cancelled"], + ] as const)("cancels the pending retry and releases its sandbox at once (task %s)", async (issueStatus, finalStatus) => { + const fixture = await seed(issueStatus); + const lifecycle = createAgentLifecycle(db); + const worker = configureAgentLifecycle(db, createLifecycleDriver(db, fixture.manager)); + workers.push(worker); + const startedAt = Date.now(); + await lifecycle.pauseAgent(fixture.agentId); + await worker.process(fixture.agentId); + await lifecycle.terminateAgent(fixture.agentId); + await worker.process(fixture.agentId); + const agent = (await db.select().from(agents).where(eq(agents.id, fixture.agentId)))[0]!; + expect(agent.lifecycleState).toBe("terminated"); + expect(Date.now() - startedAt).toBeLessThan(15_000); + + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId)); + expect(run!.status).toBe("cancelled"); + const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, fixture.runId)); + expect(coordinator).toMatchObject({ phase: "terminal_failure", nextAttemptAt: null, leaseOwner: null }); + + const [lease] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, fixture.leaseId)); + expect(lease!.status).not.toBe("active"); + expect(lease!.releasedAt).not.toBeNull(); + expect(fixture.call).toHaveBeenCalledWith(expect.any(String), expect.stringMatching(/^environment(Stop|Destroy|Release)Lease$/), + expect.objectContaining({ providerLeaseId: fixture.providerLeaseId }), expect.any(Number)); + + expect(await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, fixture.companyId), + eq(heartbeatRuns.retryOfRunId, fixture.runId)))).toHaveLength(0); + const [task] = await db.select().from(issues).where(eq(issues.id, fixture.issueId)); + expect(task!.status).toBe(finalStatus); + expect(run!.resultJson).toMatchObject({ pauseStop: { holds: ["manual"] }, + workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [fixture.leaseId] } }); + }, 60_000); +}); diff --git a/server/src/modules/agent-lifecycle/__tests__/driver-scope.test.ts b/server/src/modules/agent-lifecycle/__tests__/driver-scope.test.ts index da514753201..96d31c984af 100644 --- a/server/src/modules/agent-lifecycle/__tests__/driver-scope.test.ts +++ b/server/src/modules/agent-lifecycle/__tests__/driver-scope.test.ts @@ -1,8 +1,8 @@ import type { Db } from "@paperclipai/db"; import { describe, expect, it, vi } from "vitest"; -const stop = vi.hoisted(() => vi.fn(async () => true)); -vi.mock("../../../services/heartbeat.js", () => ({ heartbeatService: () => ({ stopInvocationsForAgents: stop }) })); +const stop = vi.hoisted(() => vi.fn(async () => null)); +vi.mock("../../../services/heartbeat.js", () => ({ heartbeatService: () => ({ agentInvocationStopBlocker: stop }) })); vi.mock("../../../services/agent-harness-verification.js", () => ({ agentHarnessVerificationService: () => ({ verify: vi.fn() }) })); import { createLifecycleDriver } from "../../../services/agent-lifecycle-driver.js"; diff --git a/server/src/modules/agent-lifecycle/__tests__/pending-backoff.test.ts b/server/src/modules/agent-lifecycle/__tests__/pending-backoff.test.ts new file mode 100644 index 00000000000..ea7da2eae97 --- /dev/null +++ b/server/src/modules/agent-lifecycle/__tests__/pending-backoff.test.ts @@ -0,0 +1,86 @@ +import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { agents, companies, createDb, type Db } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js"; +import { configureAgentLifecycle, createAgentLifecycle } from "../../../services/agent-lifecycle.js"; +import { lifecyclePendingRetryDelayMs } from "../adapters/postgres.js"; +import { wakeStoppingAgentLifecycle } from "../../../services/environment-lease-release-deferral.js"; + +const support = await getEmbeddedPostgresTestSupport(); + +(support.supported ? describe : describe.skip)("lifecycle host step that stays pending", () => { + let database: Awaited> | undefined; + let db: Db; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("paperclip-lifecycle-pending-backoff-"); + db = createDb(database.connectionString); + }, 60_000); + + afterAll(async () => { + await database?.cleanup(); + }); + + it("records why termination is waiting and spaces out its passes", async () => { + const companyId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Lifecycle", issuePrefix: `P${companyId.slice(0, 7)}` }); + const [agent] = await db.insert(agents).values({ companyId, name: "Stuck", role: "engineer", status: "idle", + adapterType: "process", adapterConfig: {}, runtimeConfig: {}, permissions: {} }).returning(); + let hostCalls = 0; + const worker = configureAgentLifecycle(db, { requiredPluginIds: async () => [], runPlugin: async () => "complete", + runHost: async () => { hostCalls += 1; return { pending: "environment_lease_unreleased" }; } }); + try { + await createAgentLifecycle(db).terminateAgent(agent!.id); + const delays: number[] = []; + for (let pass = 1; pass <= 7; pass++) { + const before = Date.now(); + await worker.process(agent!.id); + await worker.process(agent!.id); + const [current] = await db.select().from(agents).where(eq(agents.id, agent!.id)); + expect(current!.lifecycleState).toBe("terminating"); + expect(current!.lifecycleOperation).toMatchObject({ pendingReason: "environment_lease_unreleased", pendingPasses: pass }); + delays.push(Date.parse(current!.lifecycleOperation!.retryAt!) - before); + await db.update(agents).set({ lifecycleOperation: { ...current!.lifecycleOperation!, retryAt: new Date(0).toISOString() } }) + .where(eq(agents.id, agent!.id)); + } + expect(hostCalls).toBe(7); + for (const [index, delay] of delays.entries()) { + expect(delay).toBeGreaterThanOrEqual(lifecyclePendingRetryDelayMs(index + 1) - 1_000); + } + expect(delays.at(-1)).toBeGreaterThanOrEqual(60_000 - 1_000); + expect(delays.at(-1)).toBeLessThanOrEqual(60_000 + 1_000); + expect(lifecyclePendingRetryDelayMs(11)).toBe(60_000); + expect(lifecyclePendingRetryDelayMs(500)).toBe(60_000); + } finally { + await worker.stop(); + } + }, 60_000); + + it("finishes a stop at once when its blocker clears, without waiting out the backoff", async () => { + const companyId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Lifecycle", issuePrefix: `W${companyId.slice(0, 7)}` }); + const [agent] = await db.insert(agents).values({ companyId, name: "Waiting", role: "engineer", status: "idle", + adapterType: "process", adapterConfig: {}, runtimeConfig: {}, permissions: {} }).returning(); + let blocked = true; + const worker = configureAgentLifecycle(db, { requiredPluginIds: async () => [], runPlugin: async () => "complete", + runHost: async () => blocked ? { pending: "environment_lease_unreleased" } : "complete" }); + try { + await createAgentLifecycle(db).terminateAgent(agent!.id); + for (let pass = 1; pass <= 11; pass++) { + await worker.process(agent!.id); + const [current] = await db.select().from(agents).where(eq(agents.id, agent!.id)); + if (pass < 11) await db.update(agents).set({ lifecycleOperation: { ...current!.lifecycleOperation!, + retryAt: new Date(0).toISOString() } }).where(eq(agents.id, agent!.id)); + } + const [waiting] = await db.select().from(agents).where(eq(agents.id, agent!.id)); + expect(Date.parse(waiting!.lifecycleOperation!.retryAt!)).toBeGreaterThan(Date.now() + 30_000); + blocked = false; + expect(await db.transaction(tx => wakeStoppingAgentLifecycle(tx as unknown as Db, agent!.id))).toBe(true); + await worker.process(agent!.id); + expect((await db.select().from(agents).where(eq(agents.id, agent!.id)))[0]!.lifecycleState).toBe("terminated"); + } finally { + await worker.stop(); + } + }, 60_000); +}); diff --git a/server/src/modules/agent-lifecycle/adapters/postgres.ts b/server/src/modules/agent-lifecycle/adapters/postgres.ts index 6378e51dd05..99871678dc5 100644 --- a/server/src/modules/agent-lifecycle/adapters/postgres.ts +++ b/server/src/modules/agent-lifecycle/adapters/postgres.ts @@ -11,6 +11,13 @@ export function assertRootDatabase(db: Db) { } type LifecycleRow = typeof agents.$inferSelect; + +const LIFECYCLE_PENDING_BASE_MS = 2_000; +const LIFECYCLE_PENDING_MAX_MS = 60_000; + +export function lifecyclePendingRetryDelayMs(passes: number) { + return Math.min(LIFECYCLE_PENDING_MAX_MS, LIFECYCLE_PENDING_BASE_MS * 2 ** Math.max(0, passes - 1)); +} type ChangeOptions = { version?: number; owner?: string; reason?: string }; // Prepared drafts wait for the wizard; they have no background verification obligation. @@ -83,6 +90,24 @@ export async function requestAgentLifecycleRecheckInTransaction( return true; } +export async function wakeStoppingAgentLifecycleInTransaction( + tx: Pick, + agentId: string, + notify: () => Promise, +): Promise { + if (!("nestedIndex" in tx)) throw new AgentLifecycleConflict("Lifecycle wakes require the producer transaction"); + const [agent] = await tx.select({ lifecycleState: agents.lifecycleState, lifecycleOperation: agents.lifecycleOperation }) + .from(agents).where(eq(agents.id, agentId)).for("update"); + const operation = agent?.lifecycleOperation; + if (!agent || !operation || !["pausing", "terminating", "cleaning_up"].includes(agent.lifecycleState) + || (!operation.retryAt && !operation.leaseOwner)) return false; + await notify(); + await tx.update(agents).set({ lifecycleOperation: sql`(${agents.lifecycleOperation} - 'retryAt') + || case when ${agents.lifecycleOperation} ? 'leaseOwner' then '{"recheckRequested":true}'::jsonb else '{}'::jsonb end` }) + .where(eq(agents.id, agentId)); + return true; +} + /** The caller owns the accounting transaction and has locked this agent. */ async function changeLockedAgent(tx: Db, effects: LifecycleEffects, agent: LifecycleRow, command: LifecycleCommand, options: ChangeOptions = {}, policyHolds?: string[], restartPause = false) { @@ -268,9 +293,12 @@ export function createLifecycleStore(db: Db, effects: LifecycleEffects): Lifecyc sql`${agents.lifecycleOperation}->>'leaseOwner' = ${owner}`)).returning({ id: agents.id }); return rows.length > 0; } + const previousPasses = (agent.lifecycleOperation as { pendingPasses?: unknown } | null)?.pendingPasses; + const pendingPasses = options?.pendingReason ? (typeof previousPasses === "number" ? previousPasses : 0) + 1 : undefined; const retry: Partial = options?.retryRequired && ["verifying", "resuming"].includes(agent.lifecycleState) ? { retryRequired: true } - : { retryAt: new Date(now.getTime() + (error ? 60_000 : 2_000)).toISOString() }; + : { retryAt: new Date(now.getTime() + (error ? 60_000 : pendingPasses ? lifecyclePendingRetryDelayMs(pendingPasses) : 2_000)).toISOString() }; + if (options?.pendingReason && pendingPasses) Object.assign(retry, { pendingReason: options.pendingReason, pendingPasses }); if (options?.verificationFailures !== undefined && agent.lifecycleState === "verifying") { retry.verificationFailures = options.verificationFailures; } diff --git a/server/src/modules/agent-lifecycle/application/ports.ts b/server/src/modules/agent-lifecycle/application/ports.ts index ade8e539011..a7e99599c30 100644 --- a/server/src/modules/agent-lifecycle/application/ports.ts +++ b/server/src/modules/agent-lifecycle/application/ports.ts @@ -20,14 +20,14 @@ export interface LifecycleStore { setRequiredPlugins(agent: LifecycleAgent, owner: string, pluginIds: string[]): Promise; completeHost(agent: LifecycleAgent, owner: string): Promise; completePlugin(agent: LifecycleAgent, owner: string, pluginId: string): Promise; - defer(agent: LifecycleAgent, owner: string, error: string | null, now: Date, options?: { retryRequired?: boolean; verificationFailures?: number; waitForSignal?: boolean }): Promise; + defer(agent: LifecycleAgent, owner: string, error: string | null, now: Date, options?: { retryRequired?: boolean; verificationFailures?: number; waitForSignal?: boolean; pendingReason?: string }): Promise; pending(limit: number, now: Date): Promise; } export interface LifecycleDriver { requiredPluginIds(agent: LifecycleAgent): Promise; /** waiting is only a healthy verifying phase owned by an external event. */ - runHost(agent: LifecycleAgent): Promise<"complete" | "pending" | "waiting">; + runHost(agent: LifecycleAgent): Promise<"complete" | "pending" | "waiting" | { pending: string }>; runPlugin(agent: LifecycleAgent, pluginId: string): Promise<"complete" | "pending">; /** Notify the scheduler only after readiness has committed. */ onReady?(agent: LifecycleAgent): Promise; diff --git a/server/src/modules/agent-lifecycle/application/worker.ts b/server/src/modules/agent-lifecycle/application/worker.ts index 5a83aec531e..b45f0564533 100644 --- a/server/src/modules/agent-lifecycle/application/worker.ts +++ b/server/src/modules/agent-lifecycle/application/worker.ts @@ -51,8 +51,9 @@ export function createLifecycleWorker(store: LifecycleStore, driver: LifecycleDr if (!await runStep("defer", () => store.defer(agent, owner, null, new Date(), { waitForSignal: true }))) continue; return; } - if (host === "pending") { - if (!await runStep("defer", () => store.defer(agent, owner, null, new Date()))) continue; + if (host === "pending" || typeof host === "object") { + const pendingReason = typeof host === "object" ? host.pending : "host_step_pending"; + if (!await runStep("defer", () => store.defer(agent, owner, null, new Date(), { pendingReason }))) continue; return; } if (!await runStep("complete_host", () => store.completeHost(agent, owner))) continue; @@ -65,7 +66,7 @@ export function createLifecycleWorker(store: LifecycleStore, driver: LifecycleDr } if (!await runStep("renew", () => store.renew(agent, owner, new Date()))) continue phase; if (await runStep("plugin", () => driver.runPlugin(agent, pluginId), pluginId) === "pending") { - if (!await runStep("defer", () => store.defer(agent, owner, null, new Date()))) continue phase; + if (!await runStep("defer", () => store.defer(agent, owner, null, new Date(), { pendingReason: "plugin_step_pending" }))) continue phase; return; } if (!await runStep("complete_plugin", () => store.completePlugin(agent, owner, pluginId), pluginId)) continue phase; diff --git a/server/src/modules/agent-lifecycle/index.ts b/server/src/modules/agent-lifecycle/index.ts index a958e8e65b9..33c9d8f73ae 100644 --- a/server/src/modules/agent-lifecycle/index.ts +++ b/server/src/modules/agent-lifecycle/index.ts @@ -15,7 +15,7 @@ import { hasCompanyHoldMismatch, projectCompanyHolds } from "./adapters/company- import { createLifecycleWorker } from "./application/worker.js"; import type { LifecycleDriver } from "./application/ports.js"; -export { applyAgentPolicyHoldsInTransaction, releaseAgentLifecycleLeaseOfHolderInTransaction, requestAgentLifecycleRecheckInTransaction } from "./adapters/postgres.js"; +export { applyAgentPolicyHoldsInTransaction, releaseAgentLifecycleLeaseOfHolderInTransaction, requestAgentLifecycleRecheckInTransaction, wakeStoppingAgentLifecycleInTransaction } from "./adapters/postgres.js"; export { companyHoldMismatch, fenceActiveCompanyAgentStopsInTransaction } from "./adapters/company-policy.js"; export { AgentLifecycleConflict, canConfigureAgentConnection, isAgentAwaitingSetup, isAgentSetupDraft } from "./domain/policy.js"; diff --git a/server/src/services/agent-execution-stop.ts b/server/src/services/agent-execution-stop.ts index 92e9e5964bb..481b216e6d3 100644 --- a/server/src/services/agent-execution-stop.ts +++ b/server/src/services/agent-execution-stop.ts @@ -1,4 +1,5 @@ import { readProcessStartedAt } from "./hot-restart.js"; +import { readLeaseReleaseDeferral } from "./environment-lease-release-deferral.js"; import { runUsedConversationAdapter } from "./conversation-continuation.js"; import { and, eq, inArray, isNull, or, sql } from "drizzle-orm"; import { environmentLeases, heartbeatRuns, nativeRunFinalizations, type Db } from "@paperclipai/db"; @@ -8,20 +9,26 @@ import { isCancelledNativeStartup } from "./cancelled-native-startup.js"; /** Cancellation changes admission. Process and lease evidence controls cleanup. */ export async function agentExecutionsHaveStopped(db: Db, agentIds: string[]) { - if (!agentIds.length) return true; + return (await agentExecutionStopBlocker(db, agentIds)) === null; +} + +export async function agentExecutionStopBlocker(db: Db, agentIds: string[]): Promise { + if (!agentIds.length) return null; const runs = await db.select().from(heartbeatRuns).where(inArray(heartbeatRuns.agentId, agentIds)); const runIds = db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(inArray(heartbeatRuns.agentId, agentIds)); const leases = await db.select().from(environmentLeases).where(or( inArray(environmentLeases.heartbeatRunId, runIds), inArray(sql`${environmentLeases.metadata}->>'agentId'`, agentIds), )); - if (leases.some(lease => (!lease.releasedAt && !(lease.status === "retained" && lease.cleanupStatus === "success")) || lease.status === "pending_cleanup" || lease.cleanupStatus === "failed")) return false; + const deferred = leases.find(lease => lease.status === "active" && readLeaseReleaseDeferral(lease.metadata)); + if (deferred) return `environment_lease_release_deferred:${readLeaseReleaseDeferral(deferred.metadata)!.reason}`; + if (leases.some(lease => (!lease.releasedAt && !(lease.status === "retained" && lease.cleanupStatus === "success")) || lease.status === "pending_cleanup" || lease.cleanupStatus === "failed")) return "environment_lease_unreleased"; const coordinators = await db.select().from(nativeRunFinalizations) .where(inArray(nativeRunFinalizations.runId, runIds)); const now = new Date(); const abandoned = coordinators.filter(row => row.leaseOwner); if (abandoned.some(row => !row.leaseExpiresAt || row.leaseExpiresAt > now || row.resultId || - runs.find(run => run.id === row.runId)?.status !== "cancelled")) return false; + runs.find(run => run.id === row.runId)?.status !== "cancelled")) return "native_finalization_owned"; const absent = (pid: number) => { try { process.kill(pid, 0); return false; } catch (error) { return (error as NodeJS.ErrnoException).code === "ESRCH"; } @@ -30,14 +37,14 @@ export async function agentExecutionsHaveStopped(db: Db, agentIds: string[]) { if (!coordinator.controllerPid || absent(coordinator.controllerPid)) continue; const observed = await readProcessStartedAt(coordinator.controllerPid).catch(() => null); if (!observed || !coordinator.controllerProcessStartedAt || - new Date(observed).getTime() === coordinator.controllerProcessStartedAt.getTime()) return false; + new Date(observed).getTime() === coordinator.controllerProcessStartedAt.getTime()) return "native_controller_alive"; } for (const run of runs) { - if (!["succeeded", "failed", "cancelled", "timed_out", "interrupted"].includes(run.status)) return false; - if (run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date()) return false; + if (!["succeeded", "failed", "cancelled", "timed_out", "interrupted"].includes(run.status)) return "run_not_terminal"; + if (run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date()) return "run_controller_lease_held"; const runLeases = leases.filter(lease => lease.heartbeatRunId === run.id); if (runLeases.some(lease => lease.provider && lease.provider !== "local")) { - if (run.status === "cancelled" && !runLeases.every(hasRemoteTerminationReceipt)) return false; + if (run.status === "cancelled" && !runLeases.every(hasRemoteTerminationReceipt)) return "remote_stop_unconfirmed"; continue; } let processAlive = Boolean(run.processPid && !absent(run.processPid)); @@ -49,15 +56,15 @@ export async function agentExecutionsHaveStopped(db: Db, agentIds: string[]) { if (run.processGroupId === run.processPid) groupAlive = false; } } - if (processAlive || groupAlive) return false; + if (processAlive || groupAlive) return "run_process_alive"; if (run.status !== "cancelled" || !run.startedAt) continue; if (run.runtimeMode === "native" && !run.processPid && !run.processGroupId && !await hasNativeLocalProcessStop(db, run.companyId, run.id) && - !await isCancelledNativeStartup(db, run, coordinators.find(row => row.runId === run.id))) return false; + !await isCancelledNativeStartup(db, run, coordinators.find(row => row.runId === run.id))) return "native_stop_unproven"; if (run.runtimeMode === "legacy" && !run.processPid && !run.processGroupId && (run.resultJson?.executionCancellation as Record | undefined)?.state !== "acknowledged" && !(run.executionStage === "settled" && !await runUsedConversationAdapter(db, run)) && - !await isCancelledNativeStartup(db, run, coordinators.find(row => row.runId === run.id))) return false; + !await isCancelledNativeStartup(db, run, coordinators.find(row => row.runId === run.id))) return "legacy_stop_unproven"; } // Release an expired owner only after its cancelled execution has stop proof. for (const coordinator of abandoned) { @@ -68,7 +75,7 @@ export async function agentExecutionsHaveStopped(db: Db, agentIds: string[]) { eq(nativeRunFinalizations.controllerGeneration, coordinator.controllerGeneration), eq(nativeRunFinalizations.phase, coordinator.phase), isNull(nativeRunFinalizations.resultId))) .returning({ runId: nativeRunFinalizations.runId }); - if (!cleared) return false; + if (!cleared) return "native_finalization_release_raced"; } - return true; + return null; } diff --git a/server/src/services/agent-lifecycle-driver.ts b/server/src/services/agent-lifecycle-driver.ts index a74ff0c5115..8cbc3a2c272 100644 --- a/server/src/services/agent-lifecycle-driver.ts +++ b/server/src/services/agent-lifecycle-driver.ts @@ -1,4 +1,5 @@ -import { and, eq, inArray, sql } from "drizzle-orm"; +import { and, eq, inArray, or, sql } from "drizzle-orm"; +import { pendingFailedNativeRetryCancellationCondition } from "./native-runtime/native-cancellation-request.js"; import { CANCELLABLE_HEARTBEAT_RUN_STATUSES } from "./heartbeat/recovery.js"; import { promoteDeferredWorkIntents } from "./work-intent-outbox.js"; import { agents, companies, environments, heartbeatRuns, plugins, pluginCompanySettings, type Db } from "@paperclipai/db"; @@ -87,11 +88,13 @@ export function createLifecycleDriver(db: Db, manager: PluginWorkerManager): Lif await db.update(heartbeatRuns).set({ resultJson: sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) || ${pauseStop}`, }).where(and(eq(heartbeatRuns.companyId, agent.companyId), eq(heartbeatRuns.agentId, agent.id), - inArray(heartbeatRuns.status, [...CANCELLABLE_HEARTBEAT_RUN_STATUSES]), + or(inArray(heartbeatRuns.status, [...CANCELLABLE_HEARTBEAT_RUN_STATUSES]), pendingFailedNativeRetryCancellationCondition()), sql`not (coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) ? 'pauseStop')`)); } - if (!await heartbeat.stopInvocationsForAgents(ids, reason, - { preservePauseDeferred: agent.lifecycleState === "pausing" })) return "pending"; + const blocker = await heartbeat.agentInvocationStopBlocker(ids, reason, + { preservePauseDeferred: agent.lifecycleState === "pausing", + ...(agent.lifecycleOperation?.id ? { trigger: `lifecycle:${agent.lifecycleOperation.id}` } : {}) }); + if (blocker) return { pending: blocker }; } return "complete"; }, diff --git a/server/src/services/environment-lease-release-deferral.test.ts b/server/src/services/environment-lease-release-deferral.test.ts new file mode 100644 index 00000000000..1b867624f1b --- /dev/null +++ b/server/src/services/environment-lease-release-deferral.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it, vi } from "vitest"; + +const boot = vi.hoisted(() => ({ id: "boot-a" })); +vi.mock("./controller-process-identity.js", async importOriginal => ({ + ...await importOriginal(), + currentControllerBootId: () => boot.id, +})); + +import { leaseReleaseRetryDueAt, nextLeaseReleaseBootIds, nextLeaseReleaseRetryAt, + type LeaseReleaseDeferral } from "./environment-lease-release-deferral.js"; + +describe("lease release retry across live server boots", () => { + function fail(previous: LeaseReleaseDeferral | null, now: number): LeaseReleaseDeferral { + const attempts = (previous?.attempts ?? 0) + 1; + return { reason: "release_failed", attempts, retryAt: nextLeaseReleaseRetryAt(previous, attempts, now), + failingSince: previous?.failingSince ?? new Date(now).toISOString(), attemptedByBootIds: nextLeaseReleaseBootIds(previous), + providerResourceDisposition: null }; + } + + function simulate(boots: string[]) { + const start = Date.parse("2026-11-15T12:00:00Z"); + boot.id = boots[0]!; + let deferral = fail(null, start); + let attempts = 1; + let latestRetryAt = Date.parse(deferral.retryAt); + for (let minute = 1; minute <= 60; minute++) { + const now = start + minute * 60_000; + for (const id of [...boots].reverse()) { + boot.id = id; + if (leaseReleaseRetryDueAt(deferral, now) > now) continue; + deferral = fail(deferral, now); + attempts += 1; + const retryAt = Date.parse(deferral.retryAt); + expect(retryAt).toBeGreaterThanOrEqual(latestRetryAt); + latestRetryAt = retryAt; + } + } + return { deferral, attempts }; + } + + it("keeps the saved retry time for every live boot after each has made its first attempt", () => { + const single = simulate(["boot-a"]); + const overlapping = simulate(["boot-a", "boot-b"]); + expect(overlapping.deferral.attemptedByBootIds).toEqual(["boot-a", "boot-b"]); + expect(overlapping.attempts).toBeLessThanOrEqual(single.attempts + 1); + }); + + it("gives a restarted server one immediate attempt and keeps the boot list bounded", () => { + const now = Date.parse("2026-11-15T12:00:00Z"); + let deferral: LeaseReleaseDeferral | null = null; + for (let index = 0; index < 15; index++) { + boot.id = `boot-${index}`; + deferral = fail(deferral, now); + } + expect(deferral!.attemptedByBootIds).toHaveLength(10); + boot.id = "boot-restarted"; + expect(leaseReleaseRetryDueAt(deferral!, now)).toBe(now); + boot.id = "boot-14"; + expect(leaseReleaseRetryDueAt(deferral!, now)).toBe(Date.parse(deferral!.retryAt)); + }); +}); diff --git a/server/src/services/environment-lease-release-deferral.ts b/server/src/services/environment-lease-release-deferral.ts new file mode 100644 index 00000000000..058b4510c89 --- /dev/null +++ b/server/src/services/environment-lease-release-deferral.ts @@ -0,0 +1,96 @@ +import { and, eq, sql } from "drizzle-orm"; +import { environmentLeases, heartbeatRunEvents, heartbeatRuns, type Db } from "@paperclipai/db"; +import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; +import { currentControllerBootId } from "./controller-process-identity.js"; +import { wakeStoppingAgentLifecycleInTransaction } from "../modules/agent-lifecycle/index.js"; +import type { ProviderResourceDisposition } from "./environment-runtime.js"; +import { executionStartedEventPredicate } from "./pre-dispatch-execution-evidence.js"; + +export const LEASE_RELEASE_DEFERRAL_KEY = "releaseDeferral"; +const LEASE_RELEASE_RETRY_BASE_MS = 30_000; +const LEASE_RELEASE_RETRY_MAX_MS = 15 * 60_000; +export const LEASE_RELEASE_FAST_ATTEMPTS = 6; +export const LEASE_RELEASE_SLOW_RETRY_MS = 60 * 60_000; + +export type LeaseReleaseDeferral = { + reason: string; + attempts: number; + retryAt: string; + failingSince: string; + triggers?: string[]; + attemptedByBootIds?: string[]; + providerResourceDisposition: ProviderResourceDisposition | null; +}; + +const LEASE_RELEASE_TRIGGER_LIMIT = 20; + +const LEASE_RELEASE_BOOT_LIMIT = 10; + +export function leaseReleaseAttemptedByThisBoot(deferral: LeaseReleaseDeferral | null) { + return Boolean(deferral?.attemptedByBootIds?.includes(currentControllerBootId())); +} + +export function leaseReleaseRetryDueAt(deferral: LeaseReleaseDeferral, now = Date.now()) { + if (!leaseReleaseAttemptedByThisBoot(deferral)) return now; + const retryAt = Date.parse(deferral.retryAt); + return Number.isFinite(retryAt) ? retryAt : now; +} + +export function nextLeaseReleaseBootIds(previous: LeaseReleaseDeferral | null) { + const current = currentControllerBootId(); + const bootIds = (previous?.attemptedByBootIds ?? []).filter(bootId => bootId !== current); + return [...bootIds, current].slice(-LEASE_RELEASE_BOOT_LIMIT); +} + +export function nextLeaseReleaseRetryAt(previous: LeaseReleaseDeferral | null, attempts: number, now = Date.now()) { + const scheduled = now + leaseReleaseRetryDelayMs(attempts); + const saved = previous ? Date.parse(previous.retryAt) : Number.NaN; + return new Date(Number.isFinite(saved) && saved > scheduled ? saved : scheduled).toISOString(); +} + +export function nextLeaseReleaseTriggers(previous: LeaseReleaseDeferral | null, trigger: string | undefined) { + const triggers = [...(previous?.triggers ?? [])]; + if (trigger && !triggers.includes(trigger)) triggers.push(trigger); + return triggers.slice(-LEASE_RELEASE_TRIGGER_LIMIT); +} + +export function readLeaseReleaseDeferral(metadata: Record | null | undefined): LeaseReleaseDeferral | null { + const value = metadata?.[LEASE_RELEASE_DEFERRAL_KEY]; + if (!value || typeof value !== "object" || Array.isArray(value)) return null; + const deferral = value as Record; + if (typeof deferral.reason !== "string" || typeof deferral.retryAt !== "string" || typeof deferral.attempts !== "number") return null; + return deferral as LeaseReleaseDeferral; +} + +export function leaseReleaseRetryDelayMs(attempts: number) { + if (attempts > LEASE_RELEASE_FAST_ATTEMPTS) return LEASE_RELEASE_SLOW_RETRY_MS; + return Math.min(LEASE_RELEASE_RETRY_MAX_MS, LEASE_RELEASE_RETRY_BASE_MS * 2 ** Math.max(0, attempts - 1)); +} + +export function wakeStoppingAgentLifecycle(tx: Db, agentId: string) { + return wakeStoppingAgentLifecycleInTransaction(tx, agentId, () => notifyDeliveryWork(tx, DELIVERY_QUEUES.agentLifecycle)); +} + +export async function settleUnchangedNativeWorkspace(db: Db, runId: string, companyId: string): Promise { + const settled = await db.update(heartbeatRuns).set({ + runnerProfileJson: sql`(${heartbeatRuns.runnerProfileJson} - 'nativeWorkspaceSync') + || jsonb_build_object('nativeWorkspaceSyncReleasedUnchanged', ${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync')`, + }).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.status, "cancelled"), + sql`${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync'->>'state' = 'prepared'`, + sql`coalesce(${heartbeatRuns.runnerProfileJson}->'remoteWorkspace', 'null'::jsonb) = 'null'::jsonb`, + sql`not exists (select 1 from ${environmentLeases} where ${environmentLeases.companyId} = ${companyId} + and ${environmentLeases.heartbeatRunId} = ${runId} and (${environmentLeases.status} in ('active', 'pending_cleanup', 'retained') + or coalesce(${environmentLeases.metadata}, '{}'::jsonb) ? 'sandboxStopAndRetainReceipt'))`)) + .returning({ id: heartbeatRuns.id }); + return settled.length > 0; +} + +export async function nativeRunNeverLaunchedRunner(db: Db, runId: string, companyId: string): Promise { + const [run] = await db.select({ processPid: heartbeatRuns.processPid, processGroupId: heartbeatRuns.processGroupId }) + .from(heartbeatRuns).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId))); + if (!run || run.processPid || run.processGroupId) return false; + const [started] = await db.select({ id: heartbeatRunEvents.id }).from(heartbeatRunEvents).where(and( + eq(heartbeatRunEvents.companyId, companyId), eq(heartbeatRunEvents.runId, runId), executionStartedEventPredicate(), + )).limit(1); + return !started; +} diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 4d66ec03d4a..3648d2c5770 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -81,7 +81,7 @@ import { formatIssueIdentifierLink, } from "./heartbeat/scheduling.js"; import { canApplyTaskWorkspaceSelectionAtAdmission, taskWorkspaceRuntimeSelectionEnabled } from "./execution-workspace-policy.js"; -import { agentExecutionsHaveStopped } from "./agent-execution-stop.js"; +import { agentExecutionStopBlocker } from "./agent-execution-stop.js"; import { cancelHeartbeatNativeRun, terminateHeartbeatRunProcess, @@ -4444,31 +4444,45 @@ export function heartbeatService( } } - async function stopInvocationsForAgents(agentIds: string[], reason: string, options: StopInvocationOptions = {}) { + async function agentInvocationStopBlocker(agentIds: string[], reason: string, options: StopInvocationOptions = {}) { await cancelInvocationsForAgentsInternal(agentIds, reason, options); const runs = await db.select().from(heartbeatRuns).where(inArray(heartbeatRuns.agentId, agentIds)); const leasesToRelease = await db.select({ runId: environmentLeases.heartbeatRunId }).from(environmentLeases) .innerJoin(heartbeatRuns, eq(heartbeatRuns.id, environmentLeases.heartbeatRunId)) .where(and(inArray(heartbeatRuns.agentId, agentIds), or(and(eq(heartbeatRuns.status, "cancelled"), inArray(environmentLeases.status, ["active", "pending_cleanup"])), - and(eq(environmentLeases.status, "retained"), eq(environmentLeases.cleanupStatus, "failed"))))); + and(eq(environmentLeases.status, "retained"), eq(environmentLeases.cleanupStatus, "failed"))), + sql`not (coalesce((${environmentLeases.metadata}->'releaseDeferral'->>'retryAt')::timestamptz > now(), false) + and (${options.trigger ?? null}::text is null + or coalesce(${environmentLeases.metadata}->'releaseDeferral'->'triggers', '[]'::jsonb) ? ${options.trigger ?? ""}::text))`)); const needsRelease = new Set(leasesToRelease.map(lease => lease.runId)); + let blocker: string | null = null; for (const run of runs) { - if (!isHeartbeatRunTerminalStatus(run.status) || liveRunExecutions.has(run.id) || - adapterExecutionControls.has(run.id) || processRunCancellationSettlements.has(run.id) || - (run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date())) return false; + const runBlocker = !isHeartbeatRunTerminalStatus(run.status) ? "run_not_terminal" + : liveRunExecutions.has(run.id) || adapterExecutionControls.has(run.id) || processRunCancellationSettlements.has(run.id) + ? "run_executing_here" + : run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date() ? "run_controller_lease_held" : null; + if (runBlocker) { + blocker ??= runBlocker; + continue; + } if (needsRelease.has(run.id)) { - // Retry incomplete cleanup after a run becomes terminal. await releaseEnvironmentLeasesForRun({ runId: run.id, companyId: run.companyId, - agentId: run.agentId, status: run.status, providerResourceDisposition: "destroy" }); + agentId: run.agentId, status: run.status, providerResourceDisposition: "destroy", + ...(options.trigger ? { trigger: options.trigger } : {}) }); } } - return agentExecutionsHaveStopped(db, agentIds); + return blocker ?? agentExecutionStopBlocker(db, agentIds); + } + + async function stopInvocationsForAgents(agentIds: string[], reason: string, options: StopInvocationOptions = {}) { + return (await agentInvocationStopBlocker(agentIds, reason, options)) === null; } return { recoverLegacyAccountingReceipt, stopInvocationsForAgents, + agentInvocationStopBlocker, waitForRunExecutionDrain: async ( runId: string, options: { timeoutMs?: number; intervalMs?: number } = {}, diff --git a/server/src/services/heartbeat/live-recovery-work.ts b/server/src/services/heartbeat/live-recovery-work.ts index 07bc8d14950..c5698decb97 100644 --- a/server/src/services/heartbeat/live-recovery-work.ts +++ b/server/src/services/heartbeat/live-recovery-work.ts @@ -7,6 +7,12 @@ import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator import { DELIVERY_QUEUES, type DeliveryQueue } from "../delivery-work-notifications.js"; import type { LiveResourceRecoveryScope, LiveRunRecoveryScope } from "../live-run-recovery-notifications.js"; import { registerScopedDeadlineWork } from "../scoped-deadline-work.js"; +import { leaseReleaseRetryDueAt, readLeaseReleaseDeferral } from "../environment-lease-release-deferral.js"; + +function leaseDueAt(metadata: Record | null) { + const deferral = readLeaseReleaseDeferral(metadata); + return deferral ? leaseReleaseRetryDueAt(deferral) : 0; +} const TERMINAL = ["succeeded", "failed", "cancelled", "timed_out", "interrupted"]; const SETTLED_PENDING_BASE_DELAY_MS = 30_000; @@ -64,7 +70,8 @@ export function registerLiveRecoveryWork(db: Db, coordinator: ReturnType)?.deadlineAt)) || Date.now(), })); } else if (kind === "settled") { diff --git a/server/src/services/heartbeat/recovery.ts b/server/src/services/heartbeat/recovery.ts index 186f855e7e7..1d595baf587 100644 --- a/server/src/services/heartbeat/recovery.ts +++ b/server/src/services/heartbeat/recovery.ts @@ -2,6 +2,7 @@ import { settleOwnableKind } from "../recovery/ownership-invariant-report.js"; import { isRunHandedOffForShutdown, markRunHandedOffForShutdown } from "./shutdown-handoff.js"; import { ORPHANED_RUN_LEASE_FAILURE_REASON } from "../environment-run-lease-settlement.js"; import { ENVIRONMENT_LEASE_CONTROLLER_KEY } from "../environment-lease-controller.js"; +import { leaseReleaseRetryDueAt, readLeaseReleaseDeferral } from "../environment-lease-release-deferral.js"; import { readNativeStartupCleanup, readNativeStartupContext } from "../native-runtime/native-startup-cleanup.js"; import { legacyWorkspaceRecoveryNotMigrated } from "../legacy-workspace-recovery-migration.js"; import { pendingFailedNativeRetryCancellationCondition } from "../native-runtime/native-cancellation-request.js"; @@ -1676,6 +1677,40 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD ); } + async function retryTerminalRunLeaseRelease(lease: typeof environmentLeases.$inferSelect, + localRuns: { has(runId: string): boolean }, onDeferredDeadline?: (at: number) => void): Promise { + if (!lease.heartbeatRunId || localRuns.has(lease.heartbeatRunId)) return false; + const deferral = readLeaseReleaseDeferral(lease.metadata); + const dueAt = deferral ? leaseReleaseRetryDueAt(deferral) : Number.NaN; + if (deferral && dueAt > Date.now()) { + onDeferredDeadline?.(dueAt); + return false; + } + const [run] = await db.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId, + status: heartbeatRuns.status, error: heartbeatRuns.error, runtimeMode: heartbeatRuns.runtimeMode, + controllerLeaseExpiresAt: heartbeatRuns.controllerLeaseExpiresAt }) + .from(heartbeatRuns).where(and(eq(heartbeatRuns.id, lease.heartbeatRunId), eq(heartbeatRuns.companyId, lease.companyId))); + if (!run || !HEARTBEAT_RUN_TERMINAL_STATUSES.some(status => status === run.status)) return false; + if (!deferral && !(run.runtimeMode === "native" && run.status === "cancelled")) return false; + const [owner] = await db.select({ leaseOwner: nativeRunFinalizations.leaseOwner, leaseExpiresAt: nativeRunFinalizations.leaseExpiresAt }) + .from(nativeRunFinalizations).where(and(eq(nativeRunFinalizations.runId, run.id), eq(nativeRunFinalizations.companyId, run.companyId))); + const heldUntil = Math.max(run.controllerLeaseExpiresAt?.getTime() ?? 0, + owner?.leaseOwner ? owner.leaseExpiresAt?.getTime() ?? 0 : 0); + if (heldUntil > Date.now()) { + onDeferredDeadline?.(heldUntil); + return false; + } + await releaseEnvironmentLeasesForRun({ runId: run.id, companyId: run.companyId, agentId: run.agentId, + status: run.status, failureReason: run.error ?? undefined, + providerResourceDisposition: deferral ? deferral.providerResourceDisposition ?? undefined : "destroy" }); + const [after] = await db.select({ status: environmentLeases.status, metadata: environmentLeases.metadata }) + .from(environmentLeases).where(eq(environmentLeases.id, lease.id)); + if (after?.status !== "active") return true; + const next = readLeaseReleaseDeferral(after.metadata); + if (next) onDeferredDeadline?.(Date.parse(next.retryAt)); + return false; + } + // A run's active lease outlives a crash between the terminal run write and // the lease release, or a release that skipped the lease (for example when // its environment row is gone). No production query finds such a lease by @@ -1730,6 +1765,9 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD && await nativeWorkspaceExportPendingForLease(db, lease) && await preserveOrphanedNativeWorkspace(db, lease, { onDeferredDeadline: opts.onDeferredDeadline })) recovered += 1; } + for (const { lease } of scoped) { + if (await retryTerminalRunLeaseRelease(lease, localRuns, opts.onDeferredDeadline)) recovered += 1; + } const runIds = [...new Set(scoped.flatMap(({ lease }) => lease.heartbeatRunId ? [lease.heartbeatRunId] : []))]; if (runIds.length > 0) { diff --git a/server/src/services/heartbeat/run-control.test.ts b/server/src/services/heartbeat/run-control.test.ts index 81955fcd065..bfbaff21d1f 100644 --- a/server/src/services/heartbeat/run-control.test.ts +++ b/server/src/services/heartbeat/run-control.test.ts @@ -30,6 +30,8 @@ import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js"; import { acknowledgedNativeApiStopExecutionHasStopped } from "../acknowledged-native-stop.js"; import { nativeSha256 } from "../native-runtime/canonical.js"; import { callbacks, runControlPostgresSupport, setupRunControlDatabase } from "./__tests__/run-control-fixtures.js"; +import { LEASE_RELEASE_FAST_ATTEMPTS, LEASE_RELEASE_SLOW_RETRY_MS } from "../environment-lease-release-deferral.js"; +import { agentExecutionStopBlocker } from "../agent-execution-stop.js"; vi.mock("../live-events.js", () => ({ publishLiveEvent: vi.fn() })); vi.mock("../acknowledged-native-stop.js", async (importOriginal) => { @@ -125,7 +127,7 @@ describe("heartbeat run-control module boundary", () => { expect(database.access).not.toHaveBeenCalled(); }); - it("defers destruction when a warm session remains busy", async () => { + it("defers destruction and records a retry when a warm session remains busy", async () => { const database = guardedDatabase(); const deps = callbacks(database.db); deps.getRunCleanupState.mockResolvedValue({ status: "failed", runtimeMode: "legacy" } as Run); @@ -133,7 +135,7 @@ describe("heartbeat run-control module boundary", () => { await createHeartbeatRunControl(database.db, deps).releaseEnvironmentLeasesForRun({ runId: "busy", companyId: "company", agentId: "agent", status: "failed", providerResourceDisposition: "destroy" }); expect(deps.options.closeWarmNativeSessionsForRun).toHaveBeenCalledWith({ runId: "busy", reason: "terminal heartbeat run destroyed its environment lease" }); expect(deps.envOrchestrator.releaseForRun).not.toHaveBeenCalled(); - expect(database.access).not.toHaveBeenCalled(); + expect(database.access).toHaveBeenCalledWith(expect.anything(), "select", expect.anything()); }); }); @@ -869,6 +871,8 @@ describe.skipIf(!runControlPostgresSupport.supported)("heartbeat run-control dat await db.insert(environmentLeases).values({ id: leaseId, companyId: company.id, heartbeatRunId: runId, issueId: issue.id, provider: "daytona", providerLeaseId, status: "active", leasePolicy, metadata: { driver: "sandbox", pluginId: randomUUID(), sandboxProviderPlugin: true, remoteCwd: "/work" } }); + await db.insert(heartbeatRunEvents).values({ companyId: company.id, runId, agentId: agent.id, seq: 1, + eventType: "native.process_start_requested", stream: "system", level: "info", message: "Runner launch requested" }); const deps = callbacks(db), control = createHeartbeatRunControl(db, deps); let ready!: () => void, release!: () => void; const acquired = new Promise(resolve => { ready = resolve; }); @@ -883,7 +887,8 @@ describe.skipIf(!runControlPostgresSupport.supported)("heartbeat run-control dat status: "cancelled", providerResourceDisposition: "stop_and_retain" }); expect(deps.envOrchestrator.releaseForRun).not.toHaveBeenCalled(); expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0]) - .toMatchObject({ status: "active", leasePolicy }); + .toMatchObject({ status: "active", leasePolicy, metadata: expect.objectContaining({ releaseDeferral: expect.objectContaining({ + reason: "workspace_retention_busy", attempts: 1, providerResourceDisposition: "stop_and_retain" }) }) }); } finally { release(); await holding; } await preserveCancelledNativeWorkspaces(db); expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0]) @@ -898,6 +903,109 @@ describe.skipIf(!runControlPostgresSupport.supported)("heartbeat run-control dat expect((await db.select().from(issues).where(eq(issues.id, issue.id)))[0].status).toBe("in_progress"); }, 15_000); + async function deferralFixture(runtimeMode: "legacy" | "native") { + const { company, agent } = await fixture(); + const runId = randomUUID(), leaseId = randomUUID(); + await db.insert(heartbeatRuns).values({ id: runId, companyId: company.id, agentId: agent.id, runtimeMode, + status: "cancelled", finishedAt: new Date() }); + await db.insert(environmentLeases).values({ id: leaseId, companyId: company.id, heartbeatRunId: runId, + provider: "daytona", providerLeaseId: randomUUID(), status: "active", leasePolicy: "ephemeral", + metadata: { driver: "sandbox", pluginId: randomUUID(), sandboxProviderPlugin: true } }); + if (runtimeMode === "native") await db.insert(heartbeatRunEvents).values({ companyId: company.id, runId, agentId: agent.id, + seq: 1, eventType: "native.process_start_requested", stream: "system", level: "info", message: "Runner launch requested" }); + const deferral = async () => (await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0]! + .metadata?.releaseDeferral as { reason: string; attempts: number; retryAt: string; providerResourceDisposition: string | null }; + return { company, agent, runId, deferral }; + } + + it("records a failed release with its disposition and a growing retry time", async () => { + const { company, agent, runId, deferral } = await deferralFixture("legacy"); + const deps = callbacks(db); + vi.mocked(deps.envOrchestrator.releaseForRun).mockResolvedValue({ released: [], errors: [{ leaseId: "*", error: new Error("provider down") }] }); + const control = createHeartbeatRunControl(db, deps); + const before = Date.now(); + await control.releaseEnvironmentLeasesForRun({ runId, companyId: company.id, agentId: agent.id, status: "cancelled" }); + const first = await deferral(); + expect(first).toMatchObject({ reason: "release_failed", attempts: 1, providerResourceDisposition: null }); + expect(Date.parse(first.retryAt) - before).toBeGreaterThanOrEqual(30_000); + expect(Date.parse(first.retryAt) - before).toBeLessThan(40_000); + await control.releaseEnvironmentLeasesForRun({ runId, companyId: company.id, agentId: agent.id, status: "cancelled" }); + const second = await deferral(); + expect(second).toMatchObject({ reason: "release_failed", attempts: 2 }); + expect(Date.parse(second.retryAt) - before).toBeGreaterThanOrEqual(60_000); + }); + + it("never gives up on a failing release: hourly retries after the fast backoff, then release and wake the stopping agent", async () => { + const { company, agent, runId, deferral } = await deferralFixture("legacy"); + const leaseId = (await db.select().from(environmentLeases).where(eq(environmentLeases.heartbeatRunId, runId)))[0]!.id; + await db.update(agents).set({ lifecycleState: "terminating", lifecycleOperation: { id: randomUUID(), hostComplete: false, + completedPluginIds: [], attempts: 3, retryAt: new Date(Date.now() + 60_000).toISOString() } }).where(eq(agents.id, agent.id)); + const deps = callbacks(db); + let outageCalls = 0; + vi.mocked(deps.envOrchestrator.releaseForRun).mockImplementation(async () => { + outageCalls += 1; + return { released: [], errors: [{ leaseId: "*", error: new Error("provider down") }] }; + }); + const control = createHeartbeatRunControl(db, deps); + const fastSteps = LEASE_RELEASE_FAST_ATTEMPTS; + const dueRetriesInThreeHours = fastSteps + 3; + let firstFailure: string | undefined; + for (let attempt = 1; attempt <= dueRetriesInThreeHours; attempt++) { + const before = Date.now(); + await control.releaseEnvironmentLeasesForRun({ runId, companyId: company.id, agentId: agent.id, status: "cancelled" }); + const current = await deferral() as Record & { retryAt: string }; + firstFailure ??= current.failingSince as string; + expect(current).toMatchObject({ reason: "release_failed", attempts: attempt, failingSince: firstFailure }); + const delay = Date.parse(current.retryAt) - before; + if (attempt > fastSteps) expect(delay).toBeGreaterThanOrEqual(LEASE_RELEASE_SLOW_RETRY_MS - 1_000); + else expect(delay).toBeLessThanOrEqual(15 * 60_000 + 1_000); + } + expect(outageCalls).toBe(dueRetriesInThreeHours); + expect(await agentExecutionStopBlocker(db, [agent.id])).toBe("environment_lease_release_deferred:release_failed"); + vi.mocked(deps.envOrchestrator.releaseForRun).mockImplementation(async () => { + await db.update(environmentLeases).set({ status: "expired", releasedAt: new Date(), cleanupStatus: "success" }) + .where(eq(environmentLeases.id, leaseId)); + return { released: [{} as never], errors: [] }; + }); + await control.releaseEnvironmentLeasesForRun({ runId, companyId: company.id, agentId: agent.id, status: "cancelled" }); + expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0]!.status).toBe("expired"); + expect((await db.select().from(agents).where(eq(agents.id, agent.id)))[0]!.lifecycleOperation).not.toHaveProperty("retryAt"); + }); + + it("records a destroy held back by a busy warm session", async () => { + const { company, agent, runId, deferral } = await deferralFixture("native"); + const deps = callbacks(db); + deps.options.closeWarmNativeSessionsForRun.mockResolvedValue({ closed: 0, busy: 1, failed: 0 }); + await createHeartbeatRunControl(db, deps).releaseEnvironmentLeasesForRun({ runId, companyId: company.id, + agentId: agent.id, status: "cancelled", providerResourceDisposition: "destroy" }); + expect(deps.envOrchestrator.releaseForRun).not.toHaveBeenCalled(); + expect(await deferral()).toMatchObject({ reason: "warm_session_busy", attempts: 1, providerResourceDisposition: "destroy" }); + }); + + it("stops and retains a launched cancelled run's sandbox when no file retention is owed", async () => { + const { company, agent } = await fixture(); + const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Stopped task", + status: "in_progress", assigneeAgentId: agent.id }).returning(); + const runId = randomUUID(), leaseId = randomUUID(), providerLeaseId = randomUUID(); + await db.insert(heartbeatRuns).values({ id: runId, companyId: company.id, agentId: agent.id, + issueId: issue.id, nativeIssueId: issue.id, runtimeMode: "native", status: "cancelled", finishedAt: new Date(), + runnerProfileJson: { nativeWorkspaceSync: { schema: "paperclip.native-workspace-sync/v3", state: "prepared", + descriptorSha256: "a".repeat(64), baselineSha256: "b".repeat(64), finalHostSha256: null, + workspaceId: randomUUID(), leaseId, providerLeaseId, remoteCwd: "/work", resourceDisposition: "destroy" } } }); + await db.insert(nativeRunFinalizations).values({ runId, companyId: company.id, issueId: issue.id, + phase: "terminal_failure", failureCode: "native_retry_cancelled" }); + await db.insert(environmentLeases).values({ id: leaseId, companyId: company.id, heartbeatRunId: runId, + issueId: null, provider: "daytona", providerLeaseId, status: "active", leasePolicy: "ephemeral", + metadata: { driver: "sandbox", pluginId: randomUUID(), sandboxProviderPlugin: true, remoteCwd: "/work" } }); + await db.insert(heartbeatRunEvents).values({ companyId: company.id, runId, agentId: agent.id, seq: 1, + eventType: "native.process_start_requested", stream: "system", level: "info", message: "Runner launch requested" }); + const deps = callbacks(db); + await createHeartbeatRunControl(db, deps).releaseEnvironmentLeasesForRun({ runId, companyId: company.id, + agentId: agent.id, status: "cancelled", providerResourceDisposition: "destroy" }); + expect(deps.envOrchestrator.releaseForRun).toHaveBeenCalledWith(expect.objectContaining({ + heartbeatRunId: runId, providerResourceDisposition: "stop_and_retain" })); + }); + it("reports a missing run without entering cancellation", async () => { const deps = callbacks(db); await expect(createHeartbeatRunControl(db, deps).cancelRunInternal(randomUUID())).rejects.toThrow("Heartbeat run not found"); diff --git a/server/src/services/heartbeat/run-control.ts b/server/src/services/heartbeat/run-control.ts index ccc2a21b872..3b26f4f01cc 100644 --- a/server/src/services/heartbeat/run-control.ts +++ b/server/src/services/heartbeat/run-control.ts @@ -7,6 +7,10 @@ import { notifyChatInboundWakeNotices } from "../chat-inbound-wake-notice-notifi import { resumeDeferredChatWake } from "../durable-chat-wakeup.js"; import { notifyEnvironmentCleanup } from "../environment-cleanup-notifications.js"; import { readNativeStopExecutionEvidence } from "./native-stop-evidence-read.js"; +import { LEASE_RELEASE_DEFERRAL_KEY, nativeRunNeverLaunchedRunner, readLeaseReleaseDeferral, + settleUnchangedNativeWorkspace, wakeStoppingAgentLifecycle, nextLeaseReleaseTriggers, nextLeaseReleaseBootIds, nextLeaseReleaseRetryAt, + type LeaseReleaseDeferral } from "../environment-lease-release-deferral.js"; +import { pendingFailedNativeRetryCancellationCondition } from "../native-runtime/native-cancellation-request.js"; import { readTaskRetryIntent, reconcileTaskChatRetryReceipts } from "../task-retry.js"; import { PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED, readNativeLocalProcessStop, recordedLocalExecutionStopped } from "../native-local-process-stop.js"; import { isHeartbeatRunTerminalStatus } from "./run-lifecycle.js"; @@ -20,8 +24,9 @@ import { type WakeupOptions, } from "./run-preparation.js"; import { preserveWorkspaceRestoreRecoveryMetadataSql } from "../legacy-workspace-restore-recovery.js"; -import { hasRequiredWorkspaceRecovery, nativeRunHasNoWorkspaceAccess } from "../workspace-restore-recovery-state.js"; +import { nativeRunHasNoWorkspaceAccess } from "../workspace-restore-recovery-state.js"; import { preserveNativeFailedWorkspace } from "../native-runtime/native-failed-workspace-recovery.js"; +import { NativeWorkspaceFinalizationBusyError } from "../native-runtime/native-workspace-finalization-ownership.js"; import { readNativeWorkspaceSyncReference } from "../native-runtime/native-workspace-sync.js"; import { isAiAuthenticationBlocked } from "../ai-auth-failure.js"; import { @@ -182,7 +187,7 @@ async function withBudgetStopDelivery(db: Db, work: () => Promise): Promis /** `preservePauseDeferred`: the stop comes from a pause, which keeps the * messages it deferred for delivery once the pause lifts. */ -export type StopInvocationOptions = { preservePauseDeferred?: boolean }; +export type StopInvocationOptions = { preservePauseDeferred?: boolean; trigger?: string }; /** Cancellation shares executor ownership and delegates lifecycle and admission effects. */ @@ -382,6 +387,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont failureReason?: string | null; providerResourceDisposition?: ProviderResourceDisposition; respectCleanupDeadlines?: boolean; + trigger?: string; nativeLifecycleTelemetry?: { provider: string; harness: string; @@ -402,21 +408,34 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont input.providerResourceDisposition, status, ); + let neverLaunched: boolean | undefined; + const runnerNeverLaunched = async () => neverLaunched ??= leaseOwnerRun?.runtimeMode === "native" + && isHeartbeatRunTerminalStatus(status) && await nativeRunNeverLaunchedRunner(db, input.runId, input.companyId); + const defer = (reason: string) => deferEnvironmentLeaseRelease(input, reason, providerResourceDisposition); if (cancelledRun?.runtimeMode === "native" && status === "cancelled" && readNativeWorkspaceSyncReference(cancelledRun.runnerProfileJson?.nativeWorkspaceSync)?.state === "prepared" - && !nativeRunHasNoWorkspaceAccess(cancelledRun)) { - try { - const preserved = await preserveNativeFailedWorkspace(db, cancelledRun, { allowPreterminal: true }); - if (!preserved || !hasRequiredWorkspaceRecovery(preserved.resultJson)) return; - } catch { + && !nativeRunHasNoWorkspaceAccess(cancelledRun) && !await runnerNeverLaunched()) { + let deferral: string | null = null; + for (let attempt = 0; attempt < 2; attempt++) { + try { + await preserveNativeFailedWorkspace(db, cancelledRun, { allowPreterminal: true }); + deferral = null; + break; + } catch (error) { + const busy = error instanceof NativeWorkspaceFinalizationBusyError; + deferral = busy ? "workspace_owner_active" : "workspace_retention_busy"; + if (!busy || attempt > 0 || !await clearExpiredNativeFinalizationOwner(input.runId, input.companyId)) break; + } + } + if (deferral) { // Keep the active source eligible for the bounded retention sweep. // Teardown must not release it after retention lost a lock or DB write. logger.warn({ runId: input.runId }, "Deferred cancelled workspace teardown until file retention is recorded"); - return; + return await defer(deferral); } providerResourceDisposition = "stop_and_retain"; } - if (providerResourceDisposition === "destroy") { + if (providerResourceDisposition === "destroy" && !await runnerNeverLaunched()) { const closeResult = await ( options.closeWarmNativeSessionsForRun ?? (async ({ runId, reason }) => { @@ -476,7 +495,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont { runId: input.runId, warmNativeSessions: closeResult }, "deferred environment lease destruction until warm native sessions close", ); - return; + return await defer(closeResult.busy > 0 ? "warm_session_busy" : "warm_session_close_failed"); } } const releaseResult = await envOrchestrator @@ -507,9 +526,71 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont "failed to release environment lease for heartbeat run", ); } + if (isHeartbeatRunTerminalStatus(status) && (!releaseResult || releaseResult.errors.length > 0)) await defer("release_failed"); + else if (isHeartbeatRunTerminalStatus(status) && leaseOwnerRun?.runtimeMode === "native") await defer("release_skipped"); + if (cancelledRun && neverLaunched + && readNativeWorkspaceSyncReference(cancelledRun.runnerProfileJson?.nativeWorkspaceSync)?.state === "prepared") { + await settleUnchangedNativeWorkspace(db, input.runId, input.companyId).catch(() => { + logger.warn({ runId: input.runId }, "could not record that a stopped run left no files to recover"); + }); + } + if (isHeartbeatRunTerminalStatus(status) && releaseResult?.released.length) await wakeAgentAfterRunLeasesSettled(input).catch(() => { + logger.warn({ runId: input.runId }, "could not wake the agent's stop after its run leases settled"); + }); await acknowledgeRemoteStop(input.runId, input.companyId); } + async function wakeAgentAfterRunLeasesSettled(input: { runId: string; companyId: string; agentId: string }) { + const [unsettled] = await db.select({ id: environmentLeases.id }).from(environmentLeases).where(and( + eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.heartbeatRunId, input.runId), + inArray(environmentLeases.status, ["active", "pending_cleanup"]))).limit(1); + if (!unsettled) await db.transaction(tx => wakeStoppingAgentLifecycle(tx as unknown as Db, input.agentId)); + } + + async function clearExpiredNativeFinalizationOwner(runId: string, companyId: string) { + const cleared = await db.update(nativeRunFinalizations).set({ leaseOwner: null, leaseExpiresAt: null, updatedAt: new Date() }) + .where(and(eq(nativeRunFinalizations.runId, runId), eq(nativeRunFinalizations.companyId, companyId), + isNotNull(nativeRunFinalizations.leaseOwner), lte(nativeRunFinalizations.leaseExpiresAt, new Date()), + isNull(nativeRunFinalizations.resultId), + sql`exists (select 1 from ${heartbeatRuns} where ${heartbeatRuns.id} = ${runId} + and ${heartbeatRuns.companyId} = ${companyId} and ${heartbeatRuns.status} = 'cancelled')`)) + .returning({ runId: nativeRunFinalizations.runId }); + return cleared.length > 0; + } + + async function deferEnvironmentLeaseRelease(input: { runId: string; companyId: string; trigger?: string }, reason: string, + providerResourceDisposition: ProviderResourceDisposition | undefined) { + const leases = await Promise.resolve().then(() => db.select({ id: environmentLeases.id, metadata: environmentLeases.metadata }) + .from(environmentLeases).where(and(eq(environmentLeases.companyId, input.companyId), + eq(environmentLeases.heartbeatRunId, input.runId), eq(environmentLeases.status, "active")))) + .catch(() => { + logger.warn({ runId: input.runId, reason }, "could not record a deferred environment lease release"); + return []; + }); + for (const lease of leases) { + const previous = readLeaseReleaseDeferral(lease.metadata); + const attempts = (previous?.attempts ?? 0) + 1; + const deferral: LeaseReleaseDeferral = { reason, attempts, + retryAt: nextLeaseReleaseRetryAt(previous, attempts), + failingSince: previous?.failingSince ?? new Date().toISOString(), + triggers: nextLeaseReleaseTriggers(previous, input.trigger), attemptedByBootIds: nextLeaseReleaseBootIds(previous), + providerResourceDisposition: providerResourceDisposition ?? null }; + const recorded = await db.transaction(async tx => { + await notifyDeliveryWork(tx, DELIVERY_QUEUES.orphanActiveLeases, + JSON.stringify({ companyId: input.companyId, runId: input.runId, leaseId: lease.id })); + await tx.update(environmentLeases).set({ metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) + || ${JSON.stringify({ [LEASE_RELEASE_DEFERRAL_KEY]: deferral })}::jsonb` }) + .where(and(eq(environmentLeases.id, lease.id), eq(environmentLeases.status, "active"))); + }).then(() => true, () => false); + if (!recorded) { + logger.warn({ runId: input.runId, leaseId: lease.id, reason }, "could not record a deferred environment lease release"); + continue; + } + logger.warn({ runId: input.runId, leaseId: lease.id, reason, attempts, retryAt: deferral.retryAt, + failingSince: deferral.failingSince }, "deferred environment lease release; a background pass retries it"); + } + } + async function acknowledgeRemoteStop(runId: string, companyId: string) { // The provider receipt arrives after adapter settlement. A remote ACP child // has no host PID, so only this target-aware boundary can acknowledge Stop. @@ -1728,12 +1809,13 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont errorCode = "cancelled", ) { const runs = await db - .select() + .select({ id: heartbeatRuns.id }) .from(heartbeatRuns) .where( and( eq(heartbeatRuns.agentId, agentId), - inArray(heartbeatRuns.status, [...CANCELLABLE_HEARTBEAT_RUN_STATUSES]), + or(inArray(heartbeatRuns.status, [...CANCELLABLE_HEARTBEAT_RUN_STATUSES]), + pendingFailedNativeRetryCancellationCondition()), ), ); diff --git a/server/src/services/native-runtime/native-cancelled-workspace-preservation-idle.test.ts b/server/src/services/native-runtime/native-cancelled-workspace-preservation-idle.test.ts new file mode 100644 index 00000000000..34ebec77d61 --- /dev/null +++ b/server/src/services/native-runtime/native-cancelled-workspace-preservation-idle.test.ts @@ -0,0 +1,103 @@ +import { randomUUID } from "node:crypto"; +import { eq, inArray } from "drizzle-orm"; +import { afterAll, afterEach, describe, expect, it, vi } from "vitest"; +import { agents, companies, createDb, environmentLeases, environments, heartbeatRunEvents, heartbeatRuns, issues, + nativeRunFinalizations } from "@paperclipai/db"; +import { recoveryPostgresSupport, startRecoveryPostgres } from "../../__tests__/helpers/recovery-postgres.js"; +import { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js"; +import { registerCancelledWorkspacePreservationWork } from "./native-failed-workspace-recovery.js"; + +(recoveryPostgresSupport.supported ? describe : describe.skip)("cancelled workspace preservation idle cost", () => { + let database: Awaited>; + let db: ReturnType; + const fixtures = new Set(); + + async function seed(input: { launched: boolean; lease: "destroyed" | "active" }) { + if (!database) { + database = await startRecoveryPostgres("cancelled-workspace-idle-"); + db = createDb(database.connectionString); + } + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(); + const leaseId = randomUUID(), environmentId = randomUUID(), providerLeaseId = `allocation-${randomUUID()}`; + fixtures.add(runId); + await db.insert(companies).values({ id: companyId, name: "Stopped native files", issuePrefix: companyId.slice(0, 8) }); + await db.insert(agents).values({ id: agentId, companyId, name: "Stopped worker", adapterType: "paperclip_runner", + status: "terminated", lifecycleState: "terminating" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Stopped task", status: "in_progress", assigneeAgentId: agentId }); + await db.insert(environments).values({ id: environmentId, name: `Idle ${runId}`, driver: "sandbox" }); + const nativeCancellation = { schema: "paperclip.native-cancellation.v1", companyId, issueId, runId, + scope: "run", reasonCode: "cancellation_run_only", dispatchState: "acknowledged", dispatched: true, + intentAuditId: randomUUID(), acknowledgementAuditId: randomUUID(), acknowledgedAt: new Date().toISOString(), + effects: ["release_run_resources"] }; + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, issueId, nativeIssueId: issueId, + runtimeMode: "native", runtimeModeResolvedAt: new Date(), status: "cancelled", errorCode: "cancelled", + error: "Agent lifecycle stop requested", finishedAt: new Date(), contextSnapshot: { issueId }, + nextEventSeq: input.launched ? 2 : 1, + runnerProfileJson: { nativeWorkspaceSync: { schema: "paperclip.native-workspace-sync/v3", state: "prepared", + descriptorSha256: "a".repeat(64), baselineSha256: "b".repeat(64), finalHostSha256: null, + workspaceId: randomUUID(), leaseId, providerLeaseId, remoteCwd: "/work", resourceDisposition: "destroy" } }, + resultJson: { nativeCancellation, startupCancellation: { beforeNativeSelection: false } } }); + await db.insert(nativeRunFinalizations).values(input.launched + ? { runId, companyId, issueId, phase: "terminal_failure", failureCode: "native_retry_cancelled" } + : { runId, companyId, issueId, phase: "observed", attempt: 1, controllerGeneration: 1, + leaseOwner: `executor-${runId}`, leaseExpiresAt: new Date(Date.now() - 60_000) }); + if (input.launched) await db.insert(heartbeatRunEvents).values({ companyId, runId, agentId, seq: 1, + eventType: "native.process_start_requested", stream: "system", level: "info", message: "Runner launch requested" }); + const destroyed = input.lease === "destroyed"; + await db.insert(environmentLeases).values({ id: leaseId, companyId, environmentId, heartbeatRunId: runId, issueId, + provider: "daytona", providerLeaseId, leasePolicy: "ephemeral", status: destroyed ? "expired" : "active", + releasedAt: destroyed ? new Date() : null, cleanupStatus: destroyed ? "success" : null, + metadata: { driver: "sandbox", pluginId: randomUUID(), sandboxProviderPlugin: true, remoteCwd: "/work", + ...(destroyed ? { remoteExecutionTermination: { schema: "paperclip.remote-termination.v1", state: "destroyed", + runId, leaseId, companyId, provider: "daytona", providerLeaseId, confirmedAt: new Date().toISOString() } } : {}) } }); + return { companyId, runId, leaseId }; + } + + afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); + afterEach(async () => { + vi.useRealTimers(); vi.restoreAllMocks(); + if (fixtures.size) await db.update(heartbeatRuns).set({ status: "failed" }).where(inArray(heartbeatRuns.id, [...fixtures])); + fixtures.clear(); + }); + + async function idleStatements(minutes: number) { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] }); + const reads = vi.spyOn(db, "select"), transactions = vi.spyOn(db, "transaction"), writes = vi.spyOn(db, "update"); + await vi.advanceTimersByTimeAsync(minutes * 60_000); + const count = reads.mock.calls.length + transactions.mock.calls.length + writes.mock.calls.length; + reads.mockRestore(); transactions.mockRestore(); writes.mockRestore(); vi.useRealTimers(); + return count; + } + + it("leaves a stopped run that never started a runner alone, before and after a restart", async () => { + const f = await seed({ launched: false, lease: "destroyed" }); + for (let boot = 0; boot < 2; boot++) { + const worker = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: error => { throw error; } }); + const checks = vi.spyOn(db, "update"); + try { + await registerCancelledWorkspacePreservationWork(db, worker, () => true, async () => true).ready; + expect(checks.mock.calls.length).toBe(boot === 0 ? 1 : 0); + checks.mockRestore(); + expect(worker.nextWakeAt()).toBeNull(); + expect(await idleStatements(30)).toBe(0); + } finally { checks.mockRestore(); await worker.stop(); } + } + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + expect(run.runnerProfileJson).not.toHaveProperty("nativeWorkspaceSync"); + expect(run.runnerProfileJson).toHaveProperty("nativeWorkspaceSyncReleasedUnchanged.state", "prepared"); + expect(run.resultJson).not.toHaveProperty("workspaceRestoreRecovery"); + }, 120_000); + + it("still preserves the files of a stopped run that started a runner, then goes idle", async () => { + const f = await seed({ launched: true, lease: "active" }); + const worker = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: error => { throw error; } }); + try { + await registerCancelledWorkspacePreservationWork(db, worker, () => true, async () => true).ready; + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + expect(run.resultJson).toMatchObject({ workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", + leaseIds: [f.leaseId] } }); + expect(worker.nextWakeAt()).toBeNull(); + expect(await idleStatements(30)).toBe(0); + } finally { await worker.stop(); } + }, 120_000); +}); diff --git a/server/src/services/native-runtime/native-failed-workspace-recovery.ts b/server/src/services/native-runtime/native-failed-workspace-recovery.ts index f693698265d..54de27f1887 100644 --- a/server/src/services/native-runtime/native-failed-workspace-recovery.ts +++ b/server/src/services/native-runtime/native-failed-workspace-recovery.ts @@ -9,6 +9,7 @@ import { recordRequiredWorkspaceRestoreFailure } from "../legacy-execution-recov import { hasRequiredWorkspaceRecovery, nativeRunHasNoWorkspaceAccess } from "../workspace-restore-recovery-state.js"; import { logActivity } from "../activity-log.js"; import { readNativeWorkspaceSyncReference } from "./native-workspace-sync.js"; +import { nativeRunNeverLaunchedRunner, settleUnchangedNativeWorkspace } from "../environment-lease-release-deferral.js"; import type { NativeRestartRecoveryClaim } from "./native-restart-recovery.js"; import { NativeWorkspaceFinalizationBusyError } from "./native-workspace-finalization-ownership.js"; import { hasAcknowledgedNativeRunStopRequest } from "../acknowledged-native-stop.js"; @@ -329,9 +330,16 @@ export function registerCancelledWorkspacePreservationWork(db: Db, eq(nativeRunFinalizations.issueId, run.nativeIssueId!), )); if (finalization?.resultId && !stoppedAcceptedCopyback(finalization)) return null; - if (finalization?.phase !== "terminal_failure" || finalization.leaseOwner) + if (finalization?.phase !== "terminal_failure" || finalization.leaseOwner) { + const ownerDeadline = finalization?.leaseOwner ? finalization.leaseExpiresAt?.getTime() ?? null : null; + if (ownerDeadline && ownerDeadline > Date.now()) return { ...entry, dueAt: ownerDeadline }; + if (await nativeRunNeverLaunchedRunner(db, run.id, run.companyId) + && await settleUnchangedNativeWorkspace(db, run.id, run.companyId)) return null; return { ...entry, dueAt: Date.now() + 30_000 }; + } if (await cancelledWorkspaceSource(db, run)) await preserveNativeFailedWorkspace(db, run, { allowPreterminal: true, requireCancelledStop: true }); + else if (await nativeRunNeverLaunchedRunner(db, run.id, run.companyId) + && await settleUnchangedNativeWorkspace(db, run.id, run.companyId)) return null; const [current] = await db.select().from(heartbeatRuns) .where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, run.companyId))); const currentControllerDeadline = current?.controllerLeaseExpiresAt?.getTime(); diff --git a/server/src/services/native-runtime/native-workspace-finalization-state.ts b/server/src/services/native-runtime/native-workspace-finalization-state.ts index 1921029dafb..430096da99d 100644 --- a/server/src/services/native-runtime/native-workspace-finalization-state.ts +++ b/server/src/services/native-runtime/native-workspace-finalization-state.ts @@ -1,4 +1,5 @@ -import { environmentLeases, executionWorkspaces, heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db"; +import { environmentLeases, executionWorkspaces, heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db"; +import { executionStartedEventPredicate } from "../pre-dispatch-execution-evidence.js"; import { and, eq, exists, sql } from "drizzle-orm"; import { hasRequiredWorkspaceRecovery, nativeRunHasNoWorkspaceAccess } from "../workspace-restore-recovery-state.js"; import { recordRequiredWorkspaceRestoreFailure } from "../legacy-execution-recovery.js"; @@ -63,6 +64,10 @@ function nativeWorkspaceRunProjection() { 'schema', ${input}->'schema', 'binding', ${input}->'binding', 'workspace', ${input}->'workspace', 'provider', jsonb_build_object('kind', ${input}#>'{provider,kind}', 'bridgeRevision', ${input}#>'{provider,bridgeRevision}'))`, controllerBootId: heartbeatRuns.controllerBootId, + cancelledBeforeRunnerLaunch: sql`${heartbeatRuns.status} = 'cancelled' + and ${heartbeatRuns.processPid} is null and ${heartbeatRuns.processGroupId} is null + and not exists (select 1 from ${heartbeatRunEvents} where ${and(eq(heartbeatRunEvents.companyId, heartbeatRuns.companyId), + eq(heartbeatRunEvents.runId, heartbeatRuns.id), executionStartedEventPredicate())})`, contextIssueId: sql`${heartbeatRuns.contextSnapshot}->>'issueId'`, remoteReference: sql`${heartbeatRuns.runnerProfileJson}->'remoteWorkspace'`, }; @@ -71,9 +76,11 @@ function nativeWorkspaceRunProjection() { function nativeWorkspaceSourcePending(run: Pick & { reference: unknown; executionScope: Record; observedRemoteWorkspace: boolean; + cancelledBeforeRunnerLaunch: boolean; }, lease: WorkspaceSourceLease) { if (run.runtimeMode !== "native") return false; if (run.observedRemoteWorkspace) return true; + if (run.cancelledBeforeRunnerLaunch) return false; if (nativeRunHasNoWorkspaceAccess({ ...run, runnerProfileJson: { nativeExecutionInput: run.executionScope } })) return false; const reference = readNativeWorkspaceSyncReference(run.reference); return reference?.state === "prepared" && reference.leaseId === lease.id