From 14cb69245f04362f28046b72bd97b124fd90c604 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Wed, 11 Nov 2026 09:49:33 -0800 Subject: [PATCH 01/12] fix(projects): do not offer a single project storage option (#20875) 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 uses one workspace storage owner. The user chooses it when they create the project. > - The **Available in** selector shows the storage owners that the user can choose. > - Sometimes the default environment cannot be used, and only one storage owner is available. In that case, the dialog shows a selector with only one option. The user must select it before they can create the project. > - A selector with only one option is not a real choice. > - This pull request uses the only available storage owner as the default. The selector appears only when the user has two or more options. > - The benefit is that project creation asks for a choice only when there is one. ## Linked Issues or Issue Description Refs #20835 **What happened?** An example is an instance in managed-sandbox-only mode that has the agent-computer plugin but no managed sandbox. The local environment is hidden, and the managed-only rule finds no default. The project-environments endpoint returns one storage group and an error. The new project dialog shows **Available in** with only one option and disables **Create project** until the user selects it. An API request without `environmentId` fails with `project_environment_unavailable`. **What did you expect?** When only one storage owner is available, the project uses it. No selector appears. **Steps to reproduce** 1. Turn on `enableManagedSandboxOnly`. Install the agent-computer plugin. Do not add a sandbox environment. 2. Open **Create project**. 3. See an **Available in** selector with one option, and a disabled **Create project** button. ## What Changed - `projectEnvironmentOptions`: when the configured default is unavailable and only one storage group exists, the first environment of that group becomes `defaultEnvironmentId`, and `error` is null. When two or more groups exist, an unavailable default still produces the error. The server does not guess. - Project create uses the same default, so an API request without `environmentId` now succeeds in the single-group case. - `NewProjectDialog` shows the selector only when `groups.length > 1`. - Tests: - A new server test covers managed-only mode with only the agent-computer environment. - A new server test covers an unavailable default with two storage groups (the server still refuses to guess). - The archived-default test now expects the server to use the only remaining storage. - A new UI test checks that the dialog never shows one option. - Docs: `doc/project-environment-compatibility.md` and `docs/api/goals-and-projects.md`. ## Verification - `pnpm vitest run src/__tests__/project-environments.test.ts` in `server/`: 16 passed. - `pnpm vitest run src/components/NewProjectDialog` in `ui/`: 12 passed. - `tsc --noEmit` in `ui/`: clean. - Server `tsc` reports 9 errors on this machine. None are in the changed files. They are in `packages/adapter-utils` and a native-runtime test, because local dependencies are stale. CI typechecks with a fresh install. ## Risks - Low risk. The change applies only when the default is unavailable and exactly one storage group exists. In that case, the server picks the group that the user would have had to choose anyway. Run placement does not depend on the project, so this does not change where runs execute. - No migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits, 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 - [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: Claude Opus 5.5 --- doc/project-environment-compatibility.md | 8 +++-- docs/api/goals-and-projects.md | 5 ++-- .../__tests__/project-environments.test.ts | 30 +++++++++++++++++-- server/src/services/project-environments.ts | 5 ++-- ui/src/components/NewProjectDialog.test.tsx | 22 ++++++++++++++ ui/src/components/NewProjectDialog.tsx | 8 +++-- 6 files changed, 66 insertions(+), 12 deletions(-) diff --git a/doc/project-environment-compatibility.md b/doc/project-environment-compatibility.md index 47ed72bb872..39ac8854044 100644 --- a/doc/project-environment-compatibility.md +++ b/doc/project-environment-compatibility.md @@ -63,8 +63,12 @@ The hidden repository-free β€œMy private tasks” project is independent of environment/storage availability, so creating a private note never requires repairing an environment. -An unavailable configured default produces an error and permits an explicit -available choice. It does not silently select another storage owner. Existing +When the configured default is unavailable and only one storage owner is +available, that owner becomes the default, because there is nothing to choose. +When two or more owners are available, an unavailable default produces an error +and permits an explicit available choice. It does not silently select another +storage owner. The UI shows the **Available in** selector only when there are two +or more storage owners. Existing projects keep their stored owner. This change does not migrate managed storage or detach projects that contain existing work. A managed project run in an incompatible environment fails with `project_environment_incompatible` before a diff --git a/docs/api/goals-and-projects.md b/docs/api/goals-and-projects.md index 2436c9a4daf..e508f997a72 100644 --- a/docs/api/goals-and-projects.md +++ b/docs/api/goals-and-projects.md @@ -86,8 +86,9 @@ Notes: - `environmentId` optionally selects the project's workspace storage: the storage that this environment uses. When omitted, storage follows the creator's effective - default environment. The project does not save the environment, and it does not - change where runs execute. + default environment. If that default is unavailable and only one storage owner is + available, the project uses that owner. The project does not save the environment, + and it does not change where runs execute. - `expectedStorageProviderPluginId` optionally guards the observed storage owner. Use `GET /api/companies/{companyId}/project-environments` to discover compatible groups and the creator's default. Unknown or changed storage is rejected. diff --git a/server/src/__tests__/project-environments.test.ts b/server/src/__tests__/project-environments.test.ts index 53680272e43..db951894ed6 100644 --- a/server/src/__tests__/project-environments.test.ts +++ b/server/src/__tests__/project-environments.test.ts @@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto"; import express from "express"; import request from "supertest"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; -import { eq, sql } from "drizzle-orm"; +import { eq, inArray, sql } from "drizzle-orm"; import { agents, authUsers, companyMemberships, builtInManagedResources, companies, createDb, environments, instanceSettings, plugins, userCompanyPreferences } from "@paperclipai/db"; import { projectEnvironmentOptions, withDefaultProjectStorage } from "../services/project-environments.js"; import { assertProjectStorageEnvironment, projectStorageForEnvironment } from "../services/project-workspace-provider.js"; @@ -172,16 +172,40 @@ describe.skipIf(!support.supported)("project environment compatibility", () => { } }); - it("keeps a cold worker's storage identity, but refuses an archived default", async () => { + it("keeps a cold worker's storage identity, and uses the only storage left after its default is archived", async () => { const f = await fixture(); await db.update(instanceSettings).set({ defaultEnvironmentId: f.computer.id }); await db.update(plugins).set({ status: "error" }).where(eq(plugins.id, f.pluginId)); expect(await withDefaultProjectStorage(db, f.companyId, null)).toMatchObject({ storageProviderPluginId: f.pluginId }); await db.update(environments).set({ status: "archived" }).where(eq(environments.id, f.computer.id)); - expect((await projectEnvironmentOptions(db, f.companyId)).error).toBeTruthy(); + expect(await projectEnvironmentOptions(db, f.companyId)).toMatchObject({ defaultEnvironmentId: f.ssh.id, error: null }); + expect(await withDefaultProjectStorage(db, f.companyId, null)).toBeNull(); + }); + + it("refuses to guess storage when the default is unavailable and several storage options remain", async () => { + const f = await fixture(); + const [fake] = await db.insert(environments).values({ name: "Fake", driver: "sandbox", config: { provider: "fake" } }).returning(); + await db.update(instanceSettings).set({ defaultEnvironmentId: fake.id }); + const options = await projectEnvironmentOptions(db, f.companyId); + expect(options.groups).toHaveLength(2); + expect(options.defaultEnvironmentId).toBeNull(); + expect(options.error).toBeTruthy(); await expect(withDefaultProjectStorage(db, f.companyId, null)).rejects.toMatchObject({ status: 409 }); }); + it("uses agent computer storage without a choice when managed-only leaves no other environment", async () => { + const f = await fixture(); + await db.update(environments).set({ status: "archived" }).where(inArray(environments.id, [f.sandbox.id, f.ssh.id])); + await db.update(instanceSettings).set({ experimental: { enableManagedSandboxOnly: true } }); + const options = await projectEnvironmentOptions(db, f.companyId); + expect(options).toEqual({ + groups: [{ storageProviderPluginId: f.pluginId, environments: [{ id: f.computer.id, name: f.computer.name }] }], + defaultEnvironmentId: f.computer.id, + error: null, + }); + expect(await withDefaultProjectStorage(db, f.companyId, null)).toMatchObject({ storageProviderPluginId: f.pluginId }); + }); + it.each(["instance", "primary"] as const)("creates repository-free private tasks despite an archived %s default", async source => { const f = await fixture(); const userId = randomUUID(); diff --git a/server/src/services/project-environments.ts b/server/src/services/project-environments.ts index 3115a5da36c..ad97e410a9c 100644 --- a/server/src/services/project-environments.ts +++ b/server/src/services/project-environments.ts @@ -61,10 +61,11 @@ export async function projectEnvironmentOptions(db: Db, companyId: string, actor for (const group of groups) group.environments.sort((a, b) => a.name.localeCompare(b.name)); groups.sort((a, b) => a.environments[0].name.localeCompare(b.environments[0].name)); const defaultAvailable = preferred && groups.some(group => group.environments.some(environment => environment.id === preferred.id)); + const defaultEnvironmentId = defaultAvailable ? preferred!.id : groups.length === 1 ? groups[0].environments[0].id : null; return { groups, - defaultEnvironmentId: defaultAvailable ? preferred?.id ?? null : null, - error: !defaultAvailable && (preferredEnvironmentId || forcedKubernetes || managedOnly || environments.length > 0) + defaultEnvironmentId, + error: !defaultEnvironmentId && (preferredEnvironmentId || forcedKubernetes || managedOnly || environments.length > 0) ? "The default environment cannot use project workspace storage. Select an available environment or repair the default environment configuration." : null, }; diff --git a/ui/src/components/NewProjectDialog.test.tsx b/ui/src/components/NewProjectDialog.test.tsx index 0923f7a9ae9..52758177e3c 100644 --- a/ui/src/components/NewProjectDialog.test.tsx +++ b/ui/src/components/NewProjectDialog.test.tsx @@ -131,6 +131,13 @@ describe("project environment selection", () => { expect(projectsApi.create).toHaveBeenCalledWith("company-1", expect.objectContaining({ environmentId: "ssh" })); }); + it("never offers a single storage option, even when the default is unavailable", async () => { + vi.mocked(projectsApi.environmentOptions).mockResolvedValue({ groups: [groups[1]], defaultEnvironmentId: null, error: "Default is unavailable" }); + await renderForm(); + expect(container.querySelector("select")).toBeNull(); + expect(container.querySelector("#project-environment")).toBeNull(); + }); + it("blocks submission while discovery is pending", async () => { let resolve!: (value: Awaited>) => void; vi.mocked(projectsApi.environmentOptions).mockReturnValue(new Promise(value => { resolve = value; })); @@ -168,6 +175,21 @@ describe("project environment selection", () => { expect(container.querySelector('button[type="submit"]')!.disabled).toBe(false); }); + it("uses the only remaining storage when a refresh removes the chosen one", async () => { + vi.mocked(projectsApi.environmentOptions).mockResolvedValueOnce({ groups, defaultEnvironmentId: "sandbox", error: null }) + .mockResolvedValue({ groups: [groups[0]], defaultEnvironmentId: "ssh", error: null }); + const client = await renderForm(); + const select = container.querySelector("select")!; + act(() => { select.value = "computer"; select.dispatchEvent(new Event("change", { bubbles: true })); }); + await act(async () => { await client.refetchQueries({ queryKey: queryKeys.projects.environments("company-1") }); }); + await settle(); + expect(container.querySelector("select")).toBeNull(); + expect(container.querySelector('button[type="submit"]')!.disabled).toBe(false); + act(() => container.querySelector("form")!.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }))); + await settle(); + expect(projectsApi.create).toHaveBeenCalledWith("company-1", expect.objectContaining({ environmentId: "ssh", expectedStorageProviderPluginId: null })); + }); + it("does not silently substitute storage when the default is unavailable", async () => { vi.mocked(projectsApi.environmentOptions).mockResolvedValue({ groups, defaultEnvironmentId: null, error: "Default is unavailable" }); await renderForm(); diff --git a/ui/src/components/NewProjectDialog.tsx b/ui/src/components/NewProjectDialog.tsx index ce169136bf3..074f954453d 100644 --- a/ui/src/components/NewProjectDialog.tsx +++ b/ui/src/components/NewProjectDialog.tsx @@ -34,8 +34,10 @@ export function NewProjectForm({ companyId, onClose }: { companyId: string; onCl const environments = useQuery({ queryKey: queryKeys.projects.environments(companyId), queryFn: () => projectsApi.environmentOptions(companyId), gcTime: 0 }); const environmentView = useQueryView(environments); const options = environmentView.data; - const environmentId = selectedEnvironmentId ?? options?.defaultEnvironmentId; - const selectedGroup = options?.groups.find(group => group.environments.some(environment => environment.id === environmentId)); + const groupOf = (id: string | null | undefined) => options?.groups.find(group => group.environments.some(environment => environment.id === id)); + const onlyGroupRemains = options?.groups.length === 1 && Boolean(selectedEnvironmentId) && !groupOf(selectedEnvironmentId); + const environmentId = onlyGroupRemains ? options?.defaultEnvironmentId : selectedEnvironmentId ?? options?.defaultEnvironmentId; + const selectedGroup = groupOf(environmentId); const environmentReady = Boolean(environmentView.kind !== "error" && options && (!options.error || selectedGroup) && (!options.groups.length || selectedGroup)); const create = useMutation({ @@ -69,7 +71,7 @@ export function NewProjectForm({ companyId, onClose }: { companyId: string; onCl
- {options && (options.groups.length > 1 || (options.error && options.groups.length > 0)) &&
+ {options && options.groups.length > 1 &&
setSelectedEnvironmentId(event.target.value)}> From a52f622be87dbab576b315683f039e4874471d8c Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:55:15 -0600 Subject: [PATCH 02/12] fix(native): retry a remote provider startup failure once its runner exit is proven (#20874) 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 > - Native runs on a remote sandbox (Daytona) start a Runner in the sandbox, and the Runner opens the provider session > - When the provider rejects `session.open` at startup, no provider work began > - #20808 ends every such remote rejection at once with Retry, because restart recovery could not prove that the failed runner was gone. A fault that clears by itself therefore needs one human click > - The Runner transport already settles the failed runner on close and observes its exit. That is the missing proof > - This pull request records that proof on the failure and lets the same-run bootstrap retry use it. It stops a startup error that repeats, so an image fault that a retry cannot fix does not loop > - The benefit is that a transient remote startup failure recovers without a person, and a permanent one still rests at once with a working Retry that names the error ## Linked Issues or Issue Description Refs #20808 Refs #20832 Refs #20820 **What happened?** A remote (Daytona) native run whose provider rejected `session.open` at startup ended as `native_provider_startup_rejected` with Retry. This happened even when the Runner had settled and exited, and no provider session, event or checkpoint existed. A person had to click Retry for a fault that the durable record proves did no provider work. **Expected behavior** With a proven runner exit and no provider work, the run retries its bootstrap on the same run automatically. A startup error that repeats on the next attempt stops at once with Retry and names that error. Failures saved without the proof keep today's behaviour. **Steps to reproduce** 1. `cd server && npx vitest run src/services/native-runtime/native-startup-rejected-retry.integration.test.ts src/services/native-runtime/native-runner-restart-recovery.integration.test.ts -t "remote startup rejection|session.open rejection"` 2. On master, 3 cases fail: the proven remote rejection is `terminal_failure`, the repeat does not name its error, and restart recovery holds the proven failure on `ambiguous_remote_recovery_evidence`. **Paperclip version or commit** master at 3ded7bbd91. ## What Changed - Runner transport (`runnerd-codex-transport.ts`): new `runnerExitConfirmed()`. It is true only after a completed close settled the runner (provider stopped, runner suspended) and the runner process exit was observed. - Codex driver (`codex-app-server-driver-impl.ts`): after it closes the transport for a failed session open, it sets `runnerExitConfirmed` on the error when the transport proves the exit. - Executor (`native-session-executor.ts`): - A remote `provider_session_open_rejected` with a startup `providerFailure` keeps the same-run `bootstrap_retry` only with that proof. The saved failure records `runnerExitConfirmed: true`. - Each failed attempt's recovery history entry records a startup failure signature: provider, category and message, with numbers ignored. When the next attempt fails with the same signature, it stops as `native_provider_startup_rejected`. Its next action names the startup error and keeps "Retry starts a new run". - Deterministic rejections (`requires_action` authentication, permission or invalid request) stop at once as before. - Local targets are unchanged. - Restart recovery (`native-restart-recovery.ts`): `remoteRunnerExitedBeforeProviderWork` also accepts a settled `provider_session_open_rejected` with `runnerExitConfirmed: true`. All its other checks still apply: no provider session, no provider event, no checkpoint, no runner-sent event, no successor. - Docs: `doc/execution-semantics.md` and `packages/paperclip-runner/docs/durable-recovery.md`. ## Verification - Red on master, green here: - `native-startup-rejected-retry.integration.test.ts`: proven remote rejection β†’ `retryable_failure` with `runnerExitConfirmed`; unproven β†’ terminal; repeat β†’ terminal, the next action names `bwrap: loopback`, and Retry is offered. - `native-runner-restart-recovery.integration.test.ts`: proven failure β†’ `bootstrap_incomplete` (`remote_runner_exited_before_provider_work`); an older release's failure without the proof stays held. - `codex-app-server-driver.lifecycle.test.ts`: the driver records the proof only when the transport reports it after close. - `native-session-executor.test.ts`: unit cases for the rule, the `cause` chain, the repeat signature and deterministic rejections. - Local runs: the 3 server files above pass (1380 tests); restart recovery `-t remote` 75 pass; driver lifecycle 25 pass. - `tsc --noEmit` clean for `server` and `packages/paperclip-runner`. - Not run: a Daytona chaos wave. There is no in-sandbox startup fault seam yet (see Risks). ## Risks - The proof depends on the transport's close settling the runner after a failed `session.open`. The Rust runner keeps serving after a failed `session.open` (lifecycle `Continue`) and accepts `runner.suspend`, so close should settle. If it does not settle, there is no proof and the run ends at once with Retry, which is today's behaviour. It is never less safe than today. - Retries stay bounded: the startup retry budget (3 attempts) and the repeat rule both apply. A repeated identical error stops after one automatic retry. - Saved state: failures saved by older releases have no `runnerExitConfirmed` and keep the old rule. History entries without a signature never match a repeat. A mid-run deploy is safe: an old executor never writes the proof. - Not covered by chaos: a remote "Codex fails at startup N times" fault needs a hook inside the sandbox Runner or Codex. DF1's seam is server-side only, and no open chaos PR adds a seam inside the sandbox. > 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 (Anthropic) Opus 5.5, model ID `claude-opus-5-5`, run in Claude Code with tool use (shell, file edit) and extended reasoning. ## 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 --- doc/execution-semantics.md | 8 +- .../paperclip-runner/docs/durable-recovery.md | 11 ++- .../src/bin/fake-codex-app-server.rs | 6 ++ .../src/drivers/codex/app-server-transport.ts | 2 + .../codex/codex-app-server-driver-impl.ts | 5 ++ .../codex-app-server-driver.lifecycle.test.ts | 15 ++++ .../src/live/runnerd-codex-transport.ts | 17 ++++ .../runnerd-startup-rejection-exit.test.ts | 81 ++++++++++++++++++ .../native-runtime/native-restart-recovery.ts | 7 +- ...unner-restart-recovery.integration.test.ts | 22 +++++ .../native-session-executor.test.ts | 30 +++++++ .../native-runtime/native-session-executor.ts | 85 +++++++++++++++++-- ...startup-rejected-retry.integration.test.ts | 37 +++++++- 13 files changed, 310 insertions(+), 16 deletions(-) create mode 100644 packages/paperclip-runner/src/live/runnerd-startup-rejection-exit.test.ts diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 40903c46bee..61125608984 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -1358,8 +1358,12 @@ same-run bootstrap retry, and leaves an active board recovery action that asks for a supported model. A definite rejection whose startup `providerFailure` is `requires_action` for `authentication`, `permission` or `invalid_request` stops on its first attempt as `native_provider_startup_rejected`. On a remote -execution target, any definite rejection with a startup `providerFailure` stops -the same way, because a remote same-run bootstrap cannot prove ownership. No +execution target, another definite rejection with a startup `providerFailure` +retries on the same run only when the Runner transport proved, at close, that +the failed runner settled and its process exited (`runnerExitConfirmed` in the +saved failure). Restart recovery then launches a new runner. A rejection +without that proof, or one that repeats the previous attempt's startup error, +stops as `native_provider_startup_rejected`; the repeat names that error. No provider work began, so the board offers Retry, which starts a new run with a fresh provider session. Other local `session.open` rejections keep the bounded startup retry and end with Retry when it is spent. An diff --git a/packages/paperclip-runner/docs/durable-recovery.md b/packages/paperclip-runner/docs/durable-recovery.md index 30423e9983e..92dd99e1d03 100644 --- a/packages/paperclip-runner/docs/durable-recovery.md +++ b/packages/paperclip-runner/docs/durable-recovery.md @@ -159,10 +159,13 @@ which proves that the sidecar and the provider are gone. `authentication`, `permission` or `invalid_request` records `native_provider_startup_rejected`. No provider work began, so the controller stops same-run bootstrap retries and the board offers Retry at once - with the provider message. On a remote execution target, every definite - `session.open` failure with a startup `providerFailure` records the same code, - because a remote same-run bootstrap after the runner launched cannot prove - ownership and would stop on `ambiguous_remote_recovery_evidence`. On a local + with the provider message. On a remote execution target, a definite + `session.open` failure with a startup `providerFailure` keeps a same-run + bootstrap retry only when the transport's close settled the runner and + observed its exit (`runnerExitConfirmed`); restart recovery accepts that proof + as it accepts a runner's own exit. Without it, or when the failure repeats the + previous attempt's startup error, it records the same code, because a remote + same-run bootstrap cannot then prove ownership. On a local target, other startup failures (unknown, transient, rate limit, quota, model) keep the bounded same-run startup retries and end as `native_session_retry_exhausted` with Retry. A run an older release held on diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-codex-app-server.rs b/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-codex-app-server.rs index 194f81ad1a4..f3bd0906d73 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-codex-app-server.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-codex-app-server.rs @@ -1327,6 +1327,12 @@ fn run() -> Result<(), Box> { if let Some(delay) = argument(&args, "--thread-start-delay-ms") { thread::sleep(Duration::from_millis(delay.parse()?)); } + // A definite provider startup rejection, as Codex answers when + // its sandbox helper cannot start (no thread is created). + if let Some(reason) = argument(&args, "--reject-thread-start") { + send(json!({"id": id, "error": {"code": -32603, "message": reason}}))?; + continue; + } if require_external_sandbox && (message.pointer("/params/sandbox") != Some(&json!("danger-full-access")) || message.pointer("/params/permissions").is_some()) diff --git a/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts b/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts index ff0affb416f..2502927f526 100644 --- a/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts +++ b/packages/paperclip-runner/src/drivers/codex/app-server-transport.ts @@ -76,6 +76,8 @@ export interface CodexAppServerTransport { * diagnostic context; transports must not forward it to the provider. */ close(reason?: string): Promise; + /** After close: the runner settled and its process exit was observed. */ + runnerExitConfirmed?(): boolean; /** Return the confirmed released source, or false when active use was not released. */ release?(): Promise; /** Relinquish controller authority while leaving durable runner work alive. */ diff --git a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts index 633616a30eb..6b3a67ccc6d 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts @@ -373,6 +373,11 @@ export class CodexAppServerDriver implements HarnessDriver { await cancellation.close().catch(() => {}); if (error instanceof NativeSessionProtocolIntegrityError) throw error; if (input.signal?.aborted) input.signal.throwIfAborted(); + // The controller may retry this bootstrap on the same run only when the + // failed runner is proven gone; record that proof on the failure. + if (error && typeof error === "object" && transport.runnerExitConfirmed?.() === true) { + Object.defineProperty(error, "runnerExitConfirmed", { value: true, enumerable: false }); + } if (error instanceof CodexRpcError && (this.#options.driverIdentity?.kind ?? DRIVER_KIND) === DRIVER_KIND) { const providerFailure = codexProviderFailure(error, "startup", this.#options.environment); if (providerFailure) Object.defineProperty(error, "providerFailure", { value: providerFailure, enumerable: false }); diff --git a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.lifecycle.test.ts b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.lifecycle.test.ts index 62e97dc75e4..8e5d466c6d8 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.lifecycle.test.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.lifecycle.test.ts @@ -126,6 +126,21 @@ describe("Codex app-server Codex driver", () => { else expect(error.providerFailure).toBeUndefined(); }); + it.each([true, false])("records the transport's runner exit proof (%s) on a failed session open after close", async (proven) => { + class ExitProofTransport extends FakeCodexTransport { + closed = false; + override async close(): Promise { await super.close(); this.closed = true; } + // Proof is read only after the driver's close completed. + runnerExitConfirmed(): boolean { return proven && this.closed; } + } + const transport = new ExitProofTransport(); + transport.rejectMethods.set("thread/start", new CodexRpcError("error creating thread: bwrap: loopback: Failed RTM_NEWADDR", -32603)); + const error = await makeDriver([transport]).openSession({ runId: "exit-proof", normalizedSessionId: "exit-proof", + workingDirectory: WORKSPACE }).catch(error => error); + expect(transport.closed).toBe(true); + expect(error.runnerExitConfirmed === true).toBe(proven); + }); + it("accepts runner-proven warm attachment when the host active-turn reducer is stale", async () => { const transport = new WarmAttachTransport(); const driver = makeDriver([transport]); diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index 0275f959d0d..d0c16c5a7de 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -4045,6 +4045,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { #resolveClosedSignal!: () => void; #closePromise: Promise | null = null; #shutdownSettled = false; + #closeFinished = false; #probeRetirement: Promise | null = null; readonly prepareConversationResume?: CodexAppServerTransport["prepareConversationResume"]; #detachPromise: Promise | null = null; @@ -4275,6 +4276,20 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { return structuredClone(this.#evidence); } + /** + * True only when this transport's startup failed before any provider + * identity existed, its close has finished, and the runner process's exit + * was observed (it suspended and exited, or close killed it and waited). + * A runner that failed session.open cannot always suspend, and its + * controller checkpoint can be refused for lack of a provider identity, so + * neither is required. A remote same-run bootstrap retry may then launch a + * new runner: the old one is gone, and its provider never opened a thread. + */ + runnerExitConfirmed(): boolean { + return this.#closeFinished && !this.#startupComplete && this.#providerIdentity === null + && this.#evidence.runnerExited === true && this.#handle?.isExitConfirmed?.() !== false; + } + async request( method: string, params: Record, @@ -5421,7 +5436,9 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { const deadline = Date.now() + runnerCloseGraceMs(this.options); try { await this.#closeAndSettle(); + this.#closeFinished = true; } catch (error) { + this.#closeFinished = true; this.#queue.close(); try { await this.#retireControllerForRecovery(deadline); } catch (retirementError) { diff --git a/packages/paperclip-runner/src/live/runnerd-startup-rejection-exit.test.ts b/packages/paperclip-runner/src/live/runnerd-startup-rejection-exit.test.ts new file mode 100644 index 00000000000..99e8038cf1d --- /dev/null +++ b/packages/paperclip-runner/src/live/runnerd-startup-rejection-exit.test.ts @@ -0,0 +1,81 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { expect, it } from "vitest"; +import { createCapabilityRunnerdCodexTransport, defaultCapabilityRunnerdBinary } from "./runnerd-codex-transport.js"; + +const REJECTION = "error creating thread: fs sandbox helper failed: bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted"; + +function processAbsent(pid: number): boolean { + try { process.kill(pid, 0); return false; } catch { return true; } +} + +it.each([ + ["saves an unsettled checkpoint", false], + // The controller's real remote checkpoint refuses a session with no provider + // identity, which is exactly the state a rejected session.open leaves. + ["refuses the checkpoint for lack of a provider identity", true], +])("proves a runner whose provider rejected session.open stopped, when the controller %s", async (_label, refuseCheckpoint) => { + const root = await mkdtemp(join(tmpdir(), "runner-startup-rejection-")); + const settlements: string[] = []; + const bundle = createCapabilityRunnerdCodexTransport({ + runnerBinary: defaultCapabilityRunnerdBinary(), + codexCommand: resolve(import.meta.dirname, "../../runner/target/debug/fake-codex-app-server"), + codexArgs: ["--state-file", join(root, "provider.json"), "--reject-thread-start", REJECTION], + stateDirectory: root, + controlPlaneRegistration: async authority => { + await authority.start(); + return { + release: () => undefined, + checkpoint: (settlement: "settled" | "unsettled") => { + settlements.push(settlement); + if (refuseCheckpoint) throw new Error("runnerd did not report its provider identity"); + }, + }; + }, + }); + let pid: number | null = null; + try { + const failure = await bundle.transport.request("thread/start", { cwd: root }).then(() => null, (error: unknown) => error); + expect(String(failure)).toContain("session.open"); + pid = bundle.evidence().runnerPid; + expect(pid).not.toBeNull(); + expect(bundle.transport.runnerExitConfirmed?.()).toBe(false); + // The runner cannot suspend without a session, so close kills it and waits + // for its exit; the checkpoint is "unsettled" and may be refused. + await bundle.transport.close().catch(() => undefined); + expect(settlements).toEqual(["unsettled"]); + expect(bundle.transport.runnerExitConfirmed?.()).toBe(true); + expect(processAbsent(pid!)).toBe(true); + } finally { + await bundle.transport.close().catch(() => undefined); + if (pid) { try { process.kill(-pid, "SIGKILL"); } catch { /* already stopped */ } } + await rm(root, { recursive: true, force: true }); + } +}, 30_000); + +it("gives no exit proof for a runner whose session opened", async () => { + const root = await mkdtemp(join(tmpdir(), "runner-startup-opened-")); + const bundle = createCapabilityRunnerdCodexTransport({ + runnerBinary: defaultCapabilityRunnerdBinary(), + codexCommand: resolve(import.meta.dirname, "../../runner/target/debug/fake-codex-app-server"), + codexArgs: ["--state-file", join(root, "provider.json")], + stateDirectory: root, + controlPlaneRegistration: async authority => { + await authority.start(); + return { release: () => undefined }; + }, + }); + let pid: number | null = null; + try { + await bundle.transport.request("thread/start", { cwd: root }); + pid = bundle.evidence().runnerPid; + await bundle.transport.close().catch(() => undefined); + // Provider work could follow an opened session; this proof never covers it. + expect(bundle.transport.runnerExitConfirmed?.()).toBe(false); + } finally { + await bundle.transport.close().catch(() => undefined); + if (pid) { try { process.kill(-pid, "SIGKILL"); } catch { /* already stopped */ } } + await rm(root, { recursive: true, force: true }); + } +}, 30_000); diff --git a/server/src/services/native-runtime/native-restart-recovery.ts b/server/src/services/native-runtime/native-restart-recovery.ts index 244d7120c77..88dbb08f7f2 100644 --- a/server/src/services/native-runtime/native-restart-recovery.ts +++ b/server/src/services/native-runtime/native-restart-recovery.ts @@ -1571,7 +1571,12 @@ export async function claimNativeRestartRecoveries(input: { && row.run.runnerProfileJson?.nativePreparationFencingVersion === NATIVE_PREPARATION_FENCING_VERSION && row.coordinator.phase === "retryable_failure" && row.run.status === "failed" && !row.coordinator.leaseOwner && settledFailure?.recoveryMode === "bootstrap_retry" - && settledFailure?.originalFailureCode === "native_runner_process_exited" + // The runner exited on its own, or it rejected session.open and the + // controller's close then proved it settled and exited. A failure + // saved without that proof (older releases) stays held. + && (settledFailure?.originalFailureCode === "native_runner_process_exited" + || (settledFailure?.originalFailureCode === "provider_session_open_rejected" + && settledFailure?.runnerExitConfirmed === true)) && settledFailure?.providerSessionEstablished === false && settledFailure?.providerEventsExist === false && settledFailure?.checkpointExists === false && !settledFailure?.successorRunId && !row.run.sessionIdBefore && !row.run.sessionIdAfter diff --git a/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts b/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts index 63678a59f2a..f58fa27e351 100644 --- a/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts +++ b/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts @@ -3157,6 +3157,28 @@ process.on("SIGTERM", () => child.kill("SIGTERM")); kind: "blocked", runId: fixture.runId, reason })]); }); + it("bootstraps again after a remote session.open rejection whose runner exit the controller proved", async () => { + // Staging run 61d2e06e with the new proof: the runner answered session.open + // with a definite startup failure, then the controller's close settled it + // and observed its exit. No provider session, event or checkpoint exists. + const fixture = await seedExitedRemoteRunner("STARTUP-REJECTED-EXIT-PROVEN", { + originalFailureCode: "provider_session_open_rejected", runnerExitConfirmed: true }, 1); + expect(await claimNativeRestartRecoveries({ db: fixture.db, controller: successor, + restartKind: "hard", runIds: [fixture.runId] })).toEqual([expect.objectContaining({ + kind: "bootstrap_incomplete", runId: fixture.runId })]); + const [coordinator] = await fixture.db.select().from(nativeRunFinalizations) + .where(eq(nativeRunFinalizations.runId, fixture.runId)); + expect(coordinator.recoveryHistory.at(-1)).toMatchObject({ reason: "remote_runner_exited_before_provider_work" }); + }); + + it("keeps an older release's remote session.open rejection held without the runner exit proof", async () => { + const fixture = await seedExitedRemoteRunner("STARTUP-REJECTED-NO-PROOF", { + originalFailureCode: "provider_session_open_rejected" }, 1); + expect(await claimNativeRestartRecoveries({ db: fixture.db, controller: successor, + restartKind: "hard", runIds: [fixture.runId] })).toEqual([expect.objectContaining({ + kind: "blocked", runId: fixture.runId, reason: "ambiguous_remote_recovery_evidence" })]); + }); + it("records that a held same-run retry was not a server restart", async () => { // Staging run 61d2e06e: a remote session.open rejection saved by an older // release, held when its due retry re-entered restart recovery. No server diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index b723fd1d0b5..c5f40043e9c 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -446,6 +446,9 @@ import { NATIVE_PROVIDER_SESSION_CLOSED, NATIVE_PROVIDER_STARTUP_REJECTED, nativeRemoteStartupRejectionCode, + nativeRepeatedStartupFailureAction, + nativePreviousStartupFailureSignature, + nativeStartupFailureSignature, nativeSessionRecoveryProjection, nativeGovernedWaitResult, nativeConversationReplyResult, @@ -14169,6 +14172,33 @@ describe("native session bounded recovery", () => { .toBe("provider_session_open_rejected"); expect(nativeRemoteStartupRejectionCode("native_session_interrupted", failure, true)).toBe("native_session_interrupted"); }); + + it("retries a remote startup rejection on the same run once the runner's exit is proven, but not a repeat", () => { + const confirmed = (fields: Record = {}) => + Object.defineProperty(sessionOpenFailure(startupFailure(fields)), "runnerExitConfirmed", { value: true, enumerable: false }); + const first = confirmed(); + expect(nativeRemoteStartupRejectionCode(nativeSessionFailureSourceCode(first), first, true)) + .toBe("provider_session_open_rejected"); + // Wrapped by a caller: the proof still reads through `cause`. + const wrapped = new Error("native session bootstrap failed", { cause: first }); + expect(nativeRemoteStartupRejectionCode("provider_session_open_rejected", wrapped, true)) + .toBe("provider_session_open_rejected"); + // The same startup error as the previous attempt stops, with the message named. + const previous = nativePreviousStartupFailureSignature([ + { disposition: "retryable_failure", startupFailureSignature: nativeStartupFailureSignature(startupFailure({})) }, + { disposition: "bootstrap_incomplete", reason: "remote_runner_exited_before_provider_work" }, + ]); + expect(previous).not.toBeNull(); + expect(nativeRemoteStartupRejectionCode("provider_session_open_rejected", confirmed(), true, previous)) + .toBe(NATIVE_PROVIDER_STARTUP_REJECTED); + expect(nativeRepeatedStartupFailureAction(startupFailure({}).message as string)).toContain("bwrap: loopback"); + // A different startup error is not a repeat. + expect(nativeRemoteStartupRejectionCode("provider_session_open_rejected", + confirmed({ message: "Query closed before response received" }), true, previous)).toBe("provider_session_open_rejected"); + // A deterministic rejection never retries, even with exit proof. + const deterministic = confirmed({ category: "authentication", retryability: "requires_action" }); + expect(nativeSessionFailureSourceCode(deterministic)).toBe(NATIVE_PROVIDER_STARTUP_REJECTED); + }); }); it("stops same-run retries for an operator while a saved side-effecting call has no result", () => { diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index f59b41980fa..077ce813b59 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -8517,14 +8517,62 @@ function deterministicProviderStartupFailure(error: unknown): boolean { && ["authentication", "permission", "invalid_request"].includes(failure.category); } +/** The Runner transport proved the failed runner settled and its process exited. */ +export function nativeRunnerExitConfirmed(error: unknown, depth = 0): boolean { + if (!error || typeof error !== "object" || depth > 5) return false; + const value = error as Record; + if (value.runnerExitConfirmed === true) return true; + return nativeRunnerExitConfirmed(value.cause, depth + 1) + || (Array.isArray(value.errors) && value.errors.slice(0, 3).some(item => nativeRunnerExitConfirmed(item, depth + 1))); +} + +/** Same provider, category and message (numbers ignored): a retry would meet the same fault. */ +export function nativeStartupFailureSignature(failure: unknown): string | null { + const value = record(failure); + if (value.phase !== "startup" || typeof value.message !== "string" || !value.message.trim()) return null; + return JSON.stringify([value.provider ?? null, value.category ?? null, value.message.replace(/\d+/g, "#").trim()]); +} + +/** + * On a remote target, a definite startup rejection retries on the same run + * only when the Runner proved its failed runner exited (so no second runner + * can own the sandbox) and the previous attempt did not fail with the same + * startup error. Otherwise it ends at once with Retry. A deterministic + * rejection never reaches here: it is already NATIVE_PROVIDER_STARTUP_REJECTED. + */ export function nativeRemoteStartupRejectionCode( sourceFailureCode: Code, error: unknown, remoteTarget: boolean, + previousStartupSignature?: string | null, ): Code | typeof NATIVE_PROVIDER_STARTUP_REJECTED { - return remoteTarget && sourceFailureCode === "provider_session_open_rejected" - && providerFailureFromError(error)?.phase === "startup" - ? NATIVE_PROVIDER_STARTUP_REJECTED : sourceFailureCode; + if (!remoteTarget || sourceFailureCode !== "provider_session_open_rejected") return sourceFailureCode; + const failure = providerFailureFromError(error); + if (failure?.phase !== "startup") return sourceFailureCode; + return nativeRunnerExitConfirmed(error) && !nativeRepeatedStartupFailure(error, previousStartupSignature) + ? sourceFailureCode : NATIVE_PROVIDER_STARTUP_REJECTED; +} + +export function nativeRepeatedStartupFailure(error: unknown, previousStartupSignature: string | null | undefined): boolean { + const current = nativeStartupFailureSignature(providerFailureFromError(error)); + return current !== null && current === previousStartupSignature; +} + +/** The startup failure signature this run's previous failed attempt recorded. The + * execution claim clears the saved failure, but its history entry remains. */ +export function nativePreviousStartupFailureSignature(recoveryHistory: unknown): string | null { + if (!Array.isArray(recoveryHistory)) return null; + for (let index = recoveryHistory.length - 1; index >= 0; index -= 1) { + const entry = record(recoveryHistory[index]); + if (entry.disposition === "retryable_failure" || entry.disposition === "terminal_failure") { + return typeof entry.startupFailureSignature === "string" ? entry.startupFailureSignature : null; + } + } + return null; +} + +export function nativeRepeatedStartupFailureAction(message: string): string { + return `Provider startup failed the same way on consecutive attempts, so automatic retries stopped: "${message.slice(0, 500)}". No provider work began. Fix the cause in the agent's environment if needed, then Retry. Retry starts a new run with a fresh provider session.`; } /** Reads the Runner's closed class from an authenticated turn.start failure. */ @@ -12330,12 +12378,27 @@ async function executePaperclipNativeSessionAttempt( !prepareNativeSessionOpenTimeoutRetry(input.execution, input.runnerExecutionTarget?.kind !== "remote") ? "native_session_interrupted" as const : startupClassifiedFailureCode; + // The previous attempt's saved failure survives the retry claim; a + // remote startup rejection compares against it to stop a repeat. + const remoteStartupRejection = classifiedFailureCode === "provider_session_open_rejected" + && input.runnerExecutionTarget?.kind === "remote"; + const previousStartupSignature = remoteStartupRejection + ? await input.db.select({ recoveryHistory: nativeRunFinalizations.recoveryHistory }).from(nativeRunFinalizations) + .where(and(eq(nativeRunFinalizations.runId, input.execution.binding.runId), + eq(nativeRunFinalizations.companyId, input.execution.binding.companyId))) + .limit(1).then(rows => nativePreviousStartupFailureSignature(rows[0]?.recoveryHistory)) + // Without the history no repeat is provable; the attempt budget still bounds retries. + .catch(() => null) + : null; + const repeatedRemoteStartupFailure = remoteStartupRejection + && nativeRepeatedStartupFailure(error, previousStartupSignature); const sourceFailureCode = classifiedFailureCode === "native_event_replay_conflict" ? classifiedFailureCode : providerUsageLimitObserved ? "native_provider_usage_limit" - : nativeRemoteStartupRejectionCode(classifiedFailureCode, error, input.runnerExecutionTarget?.kind === "remote"); + : nativeRemoteStartupRejectionCode(classifiedFailureCode, error, input.runnerExecutionTarget?.kind === "remote", + previousStartupSignature); const bootstrap = input.useRunnerd && input.runnerExecutionTarget?.kind === "remote" && !input.restartRecovery && !retainedTransition && !remoteWarmRecovery ? { @@ -12368,6 +12431,10 @@ async function executePaperclipNativeSessionAttempt( ? sourceFailureCode : disposition.failureCode; const providerFailure = providerFailureFromError(error); + const startupFailureSignature = recoveryEvidence.recoveryMode === "bootstrap_retry" + ? nativeStartupFailureSignature(providerFailure) : null; + const startupRejectedAction = repeatedRemoteStartupFailure && providerFailure + ? nativeRepeatedStartupFailureAction(providerFailure.message) : NATIVE_PROVIDER_STARTUP_REJECTED_ACTION; // Pre-provider startup retries back off and wait out a known provider // limit; their exhaustion explains the startup failure. const startupRetryExhausted = @@ -12482,6 +12549,10 @@ async function executePaperclipNativeSessionAttempt( recoveryEvidence.providerSessionEstablished, providerEventsExist: recoveryEvidence.providerEventsExist, checkpointExists: recoveryEvidence.checkpointExists, + // Restart recovery relaunches a remote runner for this retry only + // with this proof that the failed runner is gone. + ...(recoveryEvidence.recoveryMode === "bootstrap_retry" && nativeRunnerExitConfirmed(error) + ? { runnerExitConfirmed: true } : {}), ...(providerCooldownAt ? { providerCooldownAt: providerCooldownAt.toISOString() } : {}), ...(providerLimit?.plan.resetAt ? { providerLimitResetAt: providerLimit.plan.resetAt.toISOString() } : {}), recoveryOwner: recoveryProjection.recoveryOwner, @@ -12495,7 +12566,7 @@ async function executePaperclipNativeSessionAttempt( : sourceFailureCode === NATIVE_PROVIDER_SESSION_CLOSED ? NATIVE_PROVIDER_SESSION_CLOSED_ACTION : sourceFailureCode === NATIVE_PROVIDER_STARTUP_REJECTED - ? NATIVE_PROVIDER_STARTUP_REJECTED_ACTION + ? startupRejectedAction : sourceFailureCode === "native_session_cleanup_quarantined" ? nativeCleanupRefusalAction(completedTurnCleanup) : sourceFailureCode === "runner_remote_provider_verification_unavailable" @@ -12552,6 +12623,7 @@ async function executePaperclipNativeSessionAttempt( providerSessionEstablished: recoveryEvidence.providerSessionEstablished, checkpointExists: recoveryEvidence.checkpointExists, + ...(startupFailureSignature ? { startupFailureSignature } : {}), })}::jsonb) ) with ordinality as history(item, ordinal) where ordinal > greatest( @@ -12569,6 +12641,7 @@ async function executePaperclipNativeSessionAttempt( providerSessionEstablished: recoveryEvidence.providerSessionEstablished, checkpointExists: recoveryEvidence.checkpointExists, + ...(startupFailureSignature ? { startupFailureSignature } : {}), })}::jsonb) ) - 20, 0 @@ -12772,7 +12845,7 @@ async function executePaperclipNativeSessionAttempt( : sourceFailureCode === NATIVE_PROVIDER_SESSION_CLOSED ? NATIVE_PROVIDER_SESSION_CLOSED_ACTION : sourceFailureCode === NATIVE_PROVIDER_STARTUP_REJECTED - ? NATIVE_PROVIDER_STARTUP_REJECTED_ACTION + ? startupRejectedAction : sourceFailureCode === "native_session_cleanup_quarantined" ? nativeCleanupRefusalAction(completedTurnCleanup) : sourceFailureCode === "runner_task_admission_rejected" diff --git a/server/src/services/native-runtime/native-startup-rejected-retry.integration.test.ts b/server/src/services/native-runtime/native-startup-rejected-retry.integration.test.ts index 20586d0b943..b2421734634 100644 --- a/server/src/services/native-runtime/native-startup-rejected-retry.integration.test.ts +++ b/server/src/services/native-runtime/native-startup-rejected-retry.integration.test.ts @@ -46,7 +46,7 @@ describe("native session.open the provider rejected before any provider work", ( message: "error creating thread: failed to load AGENTS.md instructions for environment `local`: fs sandbox helper failed with status exit status: 1: bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted", ...fields }); - async function rejectSessionOpen(failure: Error, attempt = 0) { + async function rejectSessionOpen(failure: Error, attempt = 0, options: { remote?: boolean; recoveryHistory?: Record[] } = {}) { const issueId = randomUUID(); await db.insert(issues).values({ id: issueId, companyId, title: "Plan the change", status: "in_progress", workMode: "standard", assigneeAgentId: agentId, createdByUserId: "board-user", responsibleUserId: "board-user" }); @@ -58,7 +58,8 @@ describe("native session.open the provider rejected before any provider work", ( await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId)); const native = await prepareNativeHeartbeatRun({ db, run, issue, environmentLeaseId: randomUUID() }); const [contract] = await db.select().from(completionContracts).where(eq(completionContracts.issueId, issueId)); - await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "observed", attempt }); + await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "observed", attempt, + ...(options.recoveryHistory ? { recoveryHistory: options.recoveryHistory } : {}) }); const execution: NativeExecutionInputV1 = { schema: "paperclip.native-execution-input.v1", binding: { companyId, runId, issueId, agentId, executionWorkspaceId: runId }, @@ -72,7 +73,9 @@ describe("native session.open the provider rejected before any provider work", ( }; await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: execution } }).where(eq(heartbeatRuns.id, runId)); provider.execute.mockReset().mockRejectedValue(failure); - await executePaperclipNativeSession({ db, execution, runnerInstanceId: native.runnerInstanceId, backend: { + await executePaperclipNativeSession({ db, execution, runnerInstanceId: native.runnerInstanceId, + ...(options.remote ? { runnerExecutionTarget: { kind: "remote", transport: "sandbox", providerKey: "test", remoteCwd: "/workspace", + runner: { execute: vi.fn() } } as never } : {}), backend: { descriptor: async () => { throw new Error("Unexpected provider call"); }, openSession: async () => { throw new Error("Unexpected provider call"); }, } }).catch(() => undefined); @@ -118,4 +121,32 @@ describe("native session.open the provider rejected before any provider work", ( const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); await expect(taskInterruptionPresentation(db, issue)).resolves.toMatchObject({ state: "failed", canRetry: true }); }, 120_000); + + const exitProven = (error: Error) => Object.defineProperty(error, "runnerExitConfirmed", { value: true, enumerable: false }); + + it("ends a remote startup rejection at once when the runner exit is not proven", async () => { + const { coordinator } = await rejectSessionOpen(rejection(startupFailure()), 0, { remote: true }); + expect(coordinator).toMatchObject({ phase: "terminal_failure", failureCode: NATIVE_PROVIDER_STARTUP_REJECTED }); + expect(coordinator.failureDetail).not.toHaveProperty("runnerExitConfirmed"); + }, 120_000); + + it("retries a remote startup rejection on the same run when the runner exit is proven", async () => { + const { coordinator } = await rejectSessionOpen(exitProven(rejection(startupFailure())), 0, { remote: true }); + expect(coordinator).toMatchObject({ phase: "retryable_failure", failureCode: "native_session_interrupted", + failureDetail: expect.objectContaining({ recoveryMode: "bootstrap_retry", originalFailureCode: "provider_session_open_rejected", + runnerExitConfirmed: true, providerSessionEstablished: false, providerEventsExist: false, checkpointExists: false }) }); + }, 120_000); + + it("stops a remote startup rejection that repeats the previous attempt's error, naming it, with Retry", async () => { + // The first attempt's own failure write records the signature the second compares with. + const first = await rejectSessionOpen(exitProven(rejection(startupFailure())), 0, { remote: true }); + const { issueId, coordinator } = await rejectSessionOpen(exitProven(rejection(startupFailure())), 1, { remote: true, + recoveryHistory: [...(first.coordinator.recoveryHistory as Record[]), + { disposition: "bootstrap_incomplete", reason: "remote_runner_exited_before_provider_work" }] }); + expect(coordinator).toMatchObject({ phase: "terminal_failure", failureCode: NATIVE_PROVIDER_STARTUP_REJECTED, nextAttemptAt: null, + failureDetail: expect.objectContaining({ nextAction: expect.stringContaining("bwrap: loopback: Failed RTM_NEWADDR") }) }); + expect(coordinator.failureDetail?.nextAction).toContain("Retry starts a new run"); + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + await expect(taskInterruptionPresentation(db, issue)).resolves.toMatchObject({ state: "failed", canRetry: true }); + }, 120_000); }); From b2edea575418fdab247b035b56d6c993a568398a Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Wed, 11 Nov 2026 10:04:18 -0800 Subject: [PATCH 03/12] fix(workspaces): verify existing worktrees before fresh retries (#20876) ## Thinking Path > - Paperclip manages work for AI agents. > - Retry checks whether the task can keep its existing workspace. > - A provider can complete checkout before Core receives the result. > - Recreating a completed worktree costs time and can change its base commit. > - Core uses the same ownership and writer checks for local and provider workspaces. > - The provider verifies its checkout before Core creates a fresh workspace. ## Linked Issues or Issue Description **What happened?** A retry can allocate a new provider worktree even though the original checkout completed. **Steps to reproduce** Complete workspace checkout through a storage provider. Fail Runner startup or lose the prepare reply. Retry the task. **Expected behavior** Reuse the same worktree when the provider confirms checkout and the prior run can no longer write to it. Related: #20865 addresses timeouts while the original prepare is in progress. This PR checks an earlier checkout when the user retries. ## What Changed - Check the prior task binding and writer state before asking a storage provider to verify a checkout. - Extend the existing prepare operation with an optional verification mode. Providers opt in through their manifest. - Return through normal workspace reuse after verification. Keep the fresh retry fallback when verification cannot establish checkout. ## Verification - Core workspace preparation, plugin workspace ownership, retry continuity, and SDK workspace-provider suites passed locally (213 tests). - Focused cases pass for provider verification, retry through heartbeat dispatch, and real local Git checkout verification with no plugin worker. The heartbeat test confirms that ordinary preparation and adapter dispatch keep the original workspace, branch, and base commit. - Core server typecheck passed before the final audit and timing edits. GitHub CI covers the final revision and broader regressions. ## Risks Provider verification adds one bounded call before a fresh retry. Older providers keep their current behavior. Verification must preserve the workspace, branch, and recorded base commit. The normal execution preparation checks still run before admission. No database migration is needed. ## Model Used OpenAI GPT-6 (Codex), with source inspection and local test 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 linked existing issues or described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal issue details - [x] I have run targeted 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 --------- Co-authored-by: Paperclip --- doc/plugins/PLUGIN_RUNNER_EXECUTION.md | 10 +++ .../plugins/sdk/src/workspace-provider.ts | 1 + packages/shared/src/types/plugin.ts | 1 + packages/shared/src/validators/plugin.ts | 1 + .../heartbeat-session-preparation.test.ts | 48 +++++++++-- .../plugin-workspaces.integration.test.ts | 46 ++++++++++ .../services/execution-preparation-timing.ts | 2 +- .../services/explicit-native-continuation.ts | 2 +- .../services/fresh-workspace-continuation.ts | 86 ++++++++++++++++--- server/src/services/heartbeat.ts | 9 +- server/src/services/plugin-workspaces.ts | 80 ++++++----------- .../services/project-workspace-provider.ts | 41 +++++++++ .../retry-workspace-continuity.test.ts | 13 ++- .../runner-e2e/source-sdk-public-inputs.json | 6 +- 14 files changed, 267 insertions(+), 79 deletions(-) diff --git a/doc/plugins/PLUGIN_RUNNER_EXECUTION.md b/doc/plugins/PLUGIN_RUNNER_EXECUTION.md index a4bc0be0b53..027da7c0021 100644 --- a/doc/plugins/PLUGIN_RUNNER_EXECUTION.md +++ b/doc/plugins/PLUGIN_RUNNER_EXECUTION.md @@ -172,6 +172,16 @@ It does not qualify a deployed plugin, live account, or production WSS proxy. ## Workspace completion and maintenance +A storage provider can declare `workspaceProvider.workspaceVerificationVersion: 1`. +Before creating a fresh workspace for an admitted Retry, Core may send the +original task-owned workspace's `prepare` request with `verifyExisting: true`. +The provider must verify a completed checkout without creating or fetching +one and return `prepared` with `created: false`. Core checks prior writer +settlement and continues normal preparation on the retained workspace after +verification. A missing or unconfirmed checkout leaves the fresh retry +fallback in place. Local workspaces use the same ownership and writer +checks with Core's existing local Git verification. + A storage provider can declare `workspaceProvider.finalizationVersion: 1`. Core then sends `workspaceOperation` with `operation.kind: "finalize"`, the retained binding, lifecycle generation, and originating `runId` and `agentId`. The operation diff --git a/packages/plugins/sdk/src/workspace-provider.ts b/packages/plugins/sdk/src/workspace-provider.ts index c212c3baffd..5db136efa4b 100644 --- a/packages/plugins/sdk/src/workspace-provider.ts +++ b/packages/plugins/sdk/src/workspace-provider.ts @@ -50,6 +50,7 @@ export const workspaceProviderOperationSchema = z.discriminatedUnion("kind", [ baseRef: z.string().nullable(), existing: workspaceProviderBindingSchema.nullable(), fresh: freshWorkspaceSchema.optional(), + verifyExisting: z.literal(true).optional(), }) .strict(), // Verify the retained workspace and flush run writes. This does not certify diff --git a/packages/shared/src/types/plugin.ts b/packages/shared/src/types/plugin.ts index 36e0f50d97f..016059b873c 100644 --- a/packages/shared/src/types/plugin.ts +++ b/packages/shared/src/types/plugin.ts @@ -721,6 +721,7 @@ export interface PaperclipPluginManifestV1 { workspaceProvider?: { /** Supports bounded run completion separately from removal-safety inspection. */ finalizationVersion?: 1; + workspaceVerificationVersion?: 1; supportsMergeAncestry?: boolean; recoveryPullRequestVersion?: 1; freshWorkspaceVersion?: 1; diff --git a/packages/shared/src/validators/plugin.ts b/packages/shared/src/validators/plugin.ts index 054de474635..2a90d3d00b6 100644 --- a/packages/shared/src/validators/plugin.ts +++ b/packages/shared/src/validators/plugin.ts @@ -812,6 +812,7 @@ export const pluginManifestV1Schema = z.object({ agentLifecycle: z.literal(true).optional(), workspaceProvider: z.object({ finalizationVersion: z.literal(1).optional(), + workspaceVerificationVersion: z.literal(1).optional(), supportsMergeAncestry: z.boolean().optional(), recoveryPullRequestVersion: z.literal(1).optional(), freshWorkspaceVersion: z.literal(1).optional(), diff --git a/server/src/__tests__/heartbeat-session-preparation.test.ts b/server/src/__tests__/heartbeat-session-preparation.test.ts index f918f482b12..8e1499e26f7 100644 --- a/server/src/__tests__/heartbeat-session-preparation.test.ts +++ b/server/src/__tests__/heartbeat-session-preparation.test.ts @@ -8,6 +8,7 @@ import { agents, agentTaskSessions, authUsers, companies, companyMemberships, cr import { registerServerAdapter, unregisterServerAdapter, type AdapterExecutionContext } from "../adapters/index.js"; import { heartbeatService } from "../services/heartbeat.js"; import { instanceSettingsService } from "../services/instance-settings.js"; +import { requestTaskRetry } from "../services/task-retry.js"; import type { PluginWorkerManager } from "../services/plugin-worker-manager.js"; import * as environmentOrchestrator from "../services/environment-run-orchestrator.js"; import { createPluginWorkspaceFixture } from "./helpers/plugin-workspaces.js"; @@ -56,7 +57,7 @@ describePostgres("heartbeat session preparation through adapter dispatch", () => await db.insert(companyMemberships).values({ companyId, principalId: userId, principalType: "user", status: "active", membershipRole: "member" }); await db.insert(agents).values({ id: agentId, companyId, name: "Session reader", adapterType, status: "idle", adapterConfig: { model: "model-a" }, runtimeConfig }); await db.insert(issues).values({ id: issueId, companyId, title: "Session fixture", status: "todo", assigneeAgentId: agentId, responsibleUserId: userId, issueNumber: 1 }); - return { companyId, agentId, issueId }; + return { companyId, agentId, issueId, userId }; } async function execute(f: Awaited>, context: Record = {}) { @@ -113,10 +114,11 @@ describePostgres("heartbeat session preparation through adapter dispatch", () => }); it.each([ - null, - { mode: "isolated_workspace" }, - { workspaceStrategy: { type: "git_worktree", branchTemplate: "work" } }, - ])("keeps a default-attached repository policy stable through binding with settings %j and retains the provider on policy changes", async (settings) => { + { settings: null, retry: false }, + { settings: { mode: "isolated_workspace" }, retry: false }, + { settings: { workspaceStrategy: { type: "git_worktree", branchTemplate: "work" } }, retry: false }, + { settings: null, retry: true }, + ])("keeps a default-attached repository policy stable through binding ($settings, Retry: $retry)", async ({ settings, retry }) => { const f = await seed(); const storage = await createPluginWorkspaceFixture(db, f.companyId); const [plugin] = await db.select().from(plugins).where(eq(plugins.id, storage.pluginId)); @@ -125,7 +127,8 @@ describePostgres("heartbeat session preparation through adapter dispatch", () => await db.update(plugins).set({ manifestJson: { ...plugin.manifestJson, capabilities: [...plugin.manifestJson.capabilities, "environment.drivers.register"], environmentDrivers: [{ driverKey: "tasks", displayName: "Tasks", supportsTasks: true, configSchema: { type: "object" } }], - workspaceProvider: { ...plugin.manifestJson.workspaceProvider!, defaultForProjects: { mode: "isolated_workspace", strategy: "git_worktree" } }, + workspaceProvider: { ...plugin.manifestJson.workspaceProvider!, defaultForProjects: { mode: "isolated_workspace", strategy: "git_worktree" }, + ...(retry ? { workspaceVerificationVersion: 1 as const } : {}) }, } }).where(eq(plugins.id, storage.pluginId)); await db.update(agents).set({ defaultEnvironmentId: environment.id }).where(eq(agents.id, f.agentId)); await db.update(projects).set({ executionWorkspacePolicy: { enabled: true, storageProviderPluginId: storage.pluginId } }).where(eq(projects.id, storage.input.projectId)); @@ -134,6 +137,7 @@ describePostgres("heartbeat session preparation through adapter dispatch", () => }).where(eq(issues.id, f.issueId)); await instanceSettingsService(db).updateExperimental({ enableIsolatedWorkspaces: true, enableIsolatedWorkspacesByDefault: true }); const cwd = await mkdtemp(join(tmpdir(), "session-provider-fixture-")); + const realizedBase = new Map(); const createOrchestrator = environmentOrchestrator.environmentRunOrchestrator; const realization = vi.spyOn(environmentOrchestrator, "environmentRunOrchestrator").mockImplementation((...args) => ({ ...createOrchestrator(...args), @@ -141,13 +145,21 @@ describePostgres("heartbeat session preparation through adapter dispatch", () => // transport while preserving the configured storage/task-driver identity. acquireForRun: async input => createOrchestrator(...args).acquireForRun({ ...input, selectedEnvironmentId: input.localEnvironmentId }), realizeForRun: async input => { + realizedBase.set(input.heartbeatRunId, input.executionWorkspace.baseRefSha); input.executionWorkspace.cwd = cwd; return { lease: input.lease, persistedExecutionWorkspace: input.persistedExecutionWorkspace, workspaceRealization: {}, executionTarget: null, remoteExecution: null }; }, })); const originalHeartbeat = heartbeat; - heartbeat = heartbeatService(db, { pluginWorkerManager: storage.workers as PluginWorkerManager }); + const storageWorkers = { + ...storage.workers, + call: async (...args: Parameters) => { + const result = await storage.workers.call(...args) as Record; + return storage.calls.at(-1)?.operation.verifyExisting ? { ...result, created: false } : result; + }, + }; + heartbeat = heartbeatService(db, { pluginWorkerManager: storageWorkers as PluginWorkerManager }); try { const first = await execute(f); const [bound] = await db.select().from(issues).where(eq(issues.id, f.issueId)); @@ -157,6 +169,28 @@ describePostgres("heartbeat session preparation through adapter dispatch", () => const [workspace] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, bound.executionWorkspaceId!)); expect([...captured.values()].filter(input => input.context.issueId === f.issueId)).toHaveLength(1); expect(workspace).toMatchObject({ providerType: "plugin", strategyType: "git_worktree" }); + if (retry) { + await db.update(heartbeatRuns).set({ status: "failed", errorCode: "setup_failed" }) + .where(eq(heartbeatRuns.id, first.finished.id)); + await db.update(issues).set({ status: "todo" }).where(eq(issues.id, f.issueId)); + const receipt = await requestTaskRetry({ db, companyId: f.companyId, issueId: f.issueId, + actorId: f.userId, actorSource: "local_implicit", observedRunId: first.finished.id, idempotencyKey: randomUUID() }); + expect(receipt.accepted).toBe(true); + await heartbeat.resumeTaskRetry(f.companyId, receipt.requestId!); + await heartbeat.drainActiveRunExecutions(); + const [resumed] = [...captured.values()].filter(input => input.context.issueId === f.issueId && input.runId !== first.finished.id); + expect(resumed?.context.paperclipWorkspace).toMatchObject({ branchName: workspace.branchName }); + expect(realizedBase.get(first.finished.id)).toBe("a".repeat(40)); + expect(realizedBase.get(resumed.runId)).toBe(realizedBase.get(first.finished.id)); + const preparations = storage.calls.filter(call => call.runId === resumed.runId && call.operation.kind === "prepare"); + expect(preparations).toHaveLength(2); + expect(preparations[0]).toMatchObject({ executionWorkspaceId: workspace.id, operation: { verifyExisting: true } }); + expect(preparations[1]).toMatchObject({ executionWorkspaceId: workspace.id }); + expect(preparations[1].operation.verifyExisting).toBeUndefined(); + const [afterRetry] = await db.select().from(issues).where(eq(issues.id, f.issueId)); + expect(afterRetry.executionWorkspaceId).toBe(workspace.id); + return; + } for (let turn = 0; turn < 2; turn++) { const next = await execute(f); expect(next.input.runtime.sessionId).toBe("saved-session"); diff --git a/server/src/__tests__/plugin-workspaces.integration.test.ts b/server/src/__tests__/plugin-workspaces.integration.test.ts index 372431d8711..ae1a45b3fcd 100644 --- a/server/src/__tests__/plugin-workspaces.integration.test.ts +++ b/server/src/__tests__/plugin-workspaces.integration.test.ts @@ -5,6 +5,7 @@ import { and, eq, sql } from "drizzle-orm"; import { createDb, subscribeDatabaseWork, + environmentLeases, executionWorkspaces, heartbeatRuns, issues, @@ -19,6 +20,7 @@ import { removePluginWorkspace, type WorkspaceWorkers, } from "../services/plugin-workspaces.js"; +import { verifyRetryWorkspace } from "../services/fresh-workspace-continuation.js"; import { executionWorkspaceService } from "../services/execution-workspaces.js"; import { WorkspaceProviderFailureError } from "../services/workspace-provider-failure.js"; import { findPluginWorkerUnavailableError, PluginWorkerUnavailableError } from "../services/plugin-worker-unavailable-error.js"; @@ -47,6 +49,50 @@ const support = await getEmbeddedPostgresTestSupport(); }); const fixture = (companyId?: string) => createPluginWorkspaceFixture(db, companyId); + it.each(["ready", "lost_reply", "unconfirmed", "live_writer", "unsupported"] as const)( + "verifies the same checkout before choosing a fresh retry (%s)", async (state) => { + const f = await fixture(); + const [plugin] = await db.select().from(plugins).where(eq(plugins.id, f.pluginId)); + if (state !== "unsupported") await db.update(plugins).set({ manifestJson: { + ...plugin.manifestJson, workspaceProvider: { ...plugin.manifestJson.workspaceProvider!, workspaceVerificationVersion: 1 }, + } }).where(eq(plugins.id, f.pluginId)); + if (state === "lost_reply") { + f.lose(); + await expect(preparePluginWorkspace(db, f.workers, f.input)).rejects.toThrow(); + } else { + await preparePluginWorkspace(db, f.workers, f.input); + } + const [task] = await db.select().from(issues).where(eq(issues.id, f.issueId)); + const workspaceId = task.executionWorkspaceId!; + await db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date() }).where(eq(heartbeatRuns.id, f.runId)); + if (state !== "lost_reply") await db.insert(environmentLeases).values({ + companyId: f.companyId, issueId: f.issueId, heartbeatRunId: f.runId, + provider: "plugin:test:tasks", executionWorkspaceId: workspaceId, leasePolicy: "ephemeral", + status: state === "live_writer" ? "active" : "released", + releasedAt: state === "live_writer" ? null : new Date(), + }); + const retryIntentId = randomUUID(); + const [retry] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.input.agentId, + issueId: f.issueId, status: "running", contextSnapshot: { taskRetryRequestId: retryIntentId }, + }).returning(); + const fresh = { mode: "fresh_isolated_workspace", retryIntentId, sourceRunId: f.runId, retainedSourceIds: [] } as const; + const workers: WorkspaceWorkers = { ...f.workers, call: async (...args) => { + const result = await f.workers.call(...args) as { kind: string }; + if (state === "unconfirmed") throw new Error("checkout incomplete"); + return { ...result, created: false }; + } }; + const result = await verifyRetryWorkspace(db, workers, retry, f.issueId, null, + { ...fresh, retainedSourceIds: [] }); + const verified = state === "ready" || state === "lost_reply"; + expect(result).toEqual(verified + ? { mode: "reuse_issue_workspace", retryIntentId, sourceRunId: f.runId, workspaceId, cwd: null } + : fresh); + expect(f.calls.slice(1)).toHaveLength(state === "live_writer" || state === "unsupported" ? 0 : 1); + if (f.calls.length > 1) expect(f.calls[1]).toMatchObject({ executionWorkspaceId: workspaceId, + runId: retry.id, operation: { kind: "prepare", verifyExisting: true } }); + const [retained] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, workspaceId)); + expect(retained.providerRef).toBe(`checkout:${workspaceId}`); + }); it.each([ ["missing", undefined], ["stopped", { status: "stopped", supportedMethods: [] }], diff --git a/server/src/services/execution-preparation-timing.ts b/server/src/services/execution-preparation-timing.ts index 01041233d1a..3cc34e3f532 100644 --- a/server/src/services/execution-preparation-timing.ts +++ b/server/src/services/execution-preparation-timing.ts @@ -16,7 +16,7 @@ type PreparationPhase = "environment_selection" | "execution_configuration" | "s | "configuration_ai_runtime" | "configuration_skills" | "configuration_connector_assignments" | "configuration_connector_skills" | "configuration_connector_delivery" | "configuration_connection_instructions" | "configuration_agent_identity" - | "workspace_source_resolution" + | "workspace_source_resolution" | "workspace_verification" | "workspace_provision_policy" | "workspace_base_validation" | "workspace_source_authorization" diff --git a/server/src/services/explicit-native-continuation.ts b/server/src/services/explicit-native-continuation.ts index 0675377b3ce..836f636e109 100644 --- a/server/src/services/explicit-native-continuation.ts +++ b/server/src/services/explicit-native-continuation.ts @@ -591,7 +591,7 @@ export async function admitExplicitNativeContinuation(input: { // holds can describe the same failed run; each hold must permit the reuse. const sourceRunIds = new Set(freshCandidates.map(candidate => candidate.run.id)); const only = sourceRunIds.size === 1 && freshCandidates.every(candidate => !candidate.remote) ? freshCandidates[0]! : null; - let retained: { id: string; cwd: string } | null = null; + let retained: { id: string; cwd: string | null } | null = null; const gitProbes = new Map>(); for (const candidate of only ? freshCandidates : []) { const checked = await retainedIssueWorkspaceForRetry(db, { companyId, issueId, agentId, diff --git a/server/src/services/fresh-workspace-continuation.ts b/server/src/services/fresh-workspace-continuation.ts index c912df92970..9888ae7ebf3 100644 --- a/server/src/services/fresh-workspace-continuation.ts +++ b/server/src/services/fresh-workspace-continuation.ts @@ -19,19 +19,20 @@ import { readFailedPreparationSettlement } from "./failed-preparation-settlement import { taskRetryRunAncestry } from "./recovery-run-ancestry.js"; import { parseNativeExecutionInput } from "../vendor/paperclip-runner/index.js"; import { nativeExecutionUsesTaskWorkspace } from "./heartbeat/external-provider.js"; +import { preparePluginWorkspace, type WorkspaceWorkers } from "./plugin-workspaces.js"; export type ContinuationReadiness = | { mode: "resume_preserved_workspace"; preservationReceiptId: string } | { mode: "reuse_current_workspace"; retryIntentId: string; sourceRunId: string; workspaceId: string; cwd: string } | { mode: "resume_stopped_native_workspace"; retryIntentId: string; sourceRunId: string; workspaceId: string; cwd: string } - | { mode: "reuse_issue_workspace"; retryIntentId: string; sourceRunId: string; workspaceId: string; cwd: string } + | { mode: "reuse_issue_workspace"; retryIntentId: string; sourceRunId: string; workspaceId: string; cwd: string | null } | { mode: "fresh_isolated_workspace"; retryIntentId: string; sourceRunId: string; retainedSourceIds: string[] }; const freshReadinessSchema = z.discriminatedUnion("mode", [z.object({ mode: z.literal("fresh_isolated_workspace"), retryIntentId: z.string().uuid(), sourceRunId: z.string().uuid(), retainedSourceIds: z.array(z.string().uuid()), }), z.object({ mode: z.literal("reuse_issue_workspace"), retryIntentId: z.string().uuid(), - sourceRunId: z.string().uuid(), workspaceId: z.string().uuid(), cwd: z.string().min(1), + sourceRunId: z.string().uuid(), workspaceId: z.string().uuid(), cwd: z.string().min(1).nullable(), })]); const workspaceExportCauses = ["native_workspace_sync_out_unrecoverable", "native_workspace_sync_out_retry_exhausted"]; @@ -126,7 +127,9 @@ export async function retainedIssueWorkspaceForRetry(db: Db, input: { companyId: string; issueId: string; agentId: string; successorRunId: string; cause: string | null; source: Pick; evidence: Record | null; gitProbes?: Map>; -}): Promise<{ id: string; cwd: string } | null> { + verifyProviderWorkspace?: (workspace: typeof executionWorkspaces.$inferSelect) => Promise; + sourceRetryIntentId?: unknown; +}): Promise<{ id: string; cwd: string | null } | null> { const keepFresh = (reason: string) => { logger.info({ companyId: input.companyId, issueId: input.issueId, sourceRunId: input.source.id, successorRunId: input.successorRunId, reason }, "Retry keeps a fresh attempt; the task workspace is not reusable"); @@ -140,23 +143,38 @@ export async function retainedIssueWorkspaceForRetry(db: Db, input: { const leases = await db.select().from(environmentLeases).where(and( eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.heartbeatRunId, input.source.id), )); - if (!leases.length || leases.some(lease => lease.provider !== "local" || !lease.releasedAt || - lease.cleanupStatus === "failed" || !lease.executionWorkspaceId)) return keepFresh("source_lease_not_local_released"); + if (leases.some(lease => !lease.releasedAt || lease.cleanupStatus === "failed" || !lease.executionWorkspaceId)) + return keepFresh("source_lease_not_released"); const sourceWorkspaceIds = new Set(leases.map(lease => lease.executionWorkspaceId)); const [bound] = await db.select({ workspace: executionWorkspaces }).from(issues).innerJoin(executionWorkspaces, and( eq(executionWorkspaces.companyId, issues.companyId), eq(executionWorkspaces.id, issues.executionWorkspaceId), )).where(and(eq(issues.companyId, input.companyId), eq(issues.id, input.issueId), eq(issues.assigneeAgentId, input.agentId))).limit(1); const workspace = bound?.workspace; - if (!workspace?.cwd || sourceWorkspaceIds.size !== 1 || !sourceWorkspaceIds.has(workspace.id)) + if (!workspace || workspace.sourceIssueId !== input.issueId || workspace.mode === "shared_workspace" || + !reusableWorkspaceStatuses.includes(workspace.status)) return keepFresh("workspace_not_task_owned"); + const verifyProvider = workspace.providerType === "plugin" ? input.verifyProviderWorkspace : undefined; + const fresh = workspace.metadata?.workspaceProviderFresh as { attemptId?: unknown } | undefined; + const reservedBySource = verifyProvider && !leases.length && + (workspace.metadata?.workspaceProviderReservationRunId === input.source.id || + (typeof input.sourceRetryIntentId === "string" && fresh?.attemptId === input.sourceRetryIntentId)); + if (!reservedBySource && (sourceWorkspaceIds.size !== 1 || !sourceWorkspaceIds.has(workspace.id))) return keepFresh("binding_not_source_workspace"); - if (!isTaskOwnedLocalWorkspace(workspace, input.issueId)) return keepFresh("workspace_not_task_owned_local"); + if (!verifyProvider && (leases.some(lease => lease.provider !== "local") || + !isTaskOwnedLocalWorkspace(workspace, input.issueId) || !workspace.cwd)) + return keepFresh("workspace_not_task_owned_local"); const writer = await workspaceHasOtherWriter(db, { companyId: input.companyId, workspaceId: workspace.id, successorRunId: input.successorRunId, stoppedSource: input.source }); if (writer) return keepFresh(writer); + if (verifyProvider) { + if (!await verifyProvider(workspace)) return keepFresh("provider_workspace_unverified"); + return { id: workspace.id, cwd: workspace.cwd }; + } // The directory must still be the recorded one, not a replacement link. - const stat = await lstat(workspace.cwd).catch(() => null); - const real = stat?.isDirectory() && !stat.isSymbolicLink() ? await realpath(workspace.cwd).catch(() => null) : null; + const cwd = workspace.cwd; + if (!cwd) return keepFresh("directory_missing"); + const stat = await lstat(cwd).catch(() => null); + const real = stat?.isDirectory() && !stat.isSymbolicLink() ? await realpath(cwd).catch(() => null) : null; if (!real) return keepFresh("directory_missing"); let probe = input.gitProbes?.get(real); if (!probe) { @@ -407,7 +425,7 @@ export async function readFreshWorkspaceReadiness(db: Db, run: Pick>'runId' = ${source.id}`)); - let retained: { id: string; cwd: string } | null = null; + let retained: { id: string; cwd: string | null } | null = null; const gitProbes = new Map>(); for (const hold of holds.length ? holds : [{ cause: null, evidence: null }]) { const checked = await retainedIssueWorkspaceForRetry(db, { companyId: run.companyId, issueId, @@ -461,3 +479,51 @@ export async function readFreshWorkspaceReadiness(db: Db, run: Pick, + issueId: string, + responsibleUserId: string | null, + readiness: ContinuationReadiness, +): Promise { + if (readiness.mode !== "fresh_isolated_workspace" || + run.contextSnapshot?.taskRetryRequestId !== readiness.retryIntentId) return readiness; + const [source] = await db.select().from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, run.companyId), eq(heartbeatRuns.agentId, run.agentId), + eq(heartbeatRuns.id, readiness.sourceRunId), + sql`coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.issueId}::text, ${heartbeatRuns.contextSnapshot}->>'issueId') = ${issueId}`, + )); + if (!source) return readiness; + const holds = await db.select({ cause: issueRecoveryActions.cause, evidence: issueRecoveryActions.evidence }) + .from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, run.companyId), + eq(issueRecoveryActions.sourceIssueId, issueId), + sql`${issueRecoveryActions.evidence}->>'runId' = ${source.id}`)); + if (holds.some(hold => !recoveryGenerationSettled(hold.evidence, source.id) || + sourceNeedsWorkspaceRepair(hold.cause, source.resultJson))) return readiness; + const retained = await retainedIssueWorkspaceForRetry(db, { + companyId: run.companyId, issueId, agentId: run.agentId, successorRunId: run.id, + source, cause: null, evidence: null, + sourceRetryIntentId: source.contextSnapshot?.taskRetryRequestId, + verifyProviderWorkspace: workers ? async workspace => { + try { + return Boolean(await preparePluginWorkspace(db, workers, { + companyId: run.companyId, issueId, agentId: run.agentId, runId: run.id, responsibleUserId, + projectId: workspace.projectId, projectWorkspaceId: workspace.projectWorkspaceId, + existingWorkspaceId: workspace.id, mode: workspace.mode, strategy: workspace.strategyType, + verifyExisting: true, + })); + } catch { + return false; + } + } : undefined, + }); + if (!retained) return readiness; + const reuse: ContinuationReadiness = { mode: "reuse_issue_workspace", retryIntentId: readiness.retryIntentId, + sourceRunId: source.id, workspaceId: retained.id, cwd: retained.cwd }; + await persistActivity(db, { companyId: run.companyId, actorType: "system", actorId: "task-recovery", + action: "issue.retry_workspace_reused", entityType: "issue", entityId: issueId, runId: run.id, details: reuse }); + return reuse; +} diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 72916c807b0..c36a4eb7871 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -31,7 +31,7 @@ import { registerCancelledWorkspacePreservationWork } from "./native-runtime/nat import { readUpgradeReadiness } from "./heartbeat/upgrade-readiness.js"; import { DELIVERY_QUEUES } from "./delivery-work-notifications.js"; import { writeExecutionControl } from "./execution-control-notifications.js"; -import { readFreshWorkspaceReadiness } from "./fresh-workspace-continuation.js"; +import { readFreshWorkspaceReadiness, verifyRetryWorkspace } from "./fresh-workspace-continuation.js"; import { settleFailedNativeRecoveryPreparation } from "./native-runtime/native-recovery-preparation-failure.js"; import { promptInjectionPreventionService } from "./prompt-injection-prevention.js"; import { createHeartbeatAgentStatus } from "./heartbeat/agent-status.js"; @@ -2254,7 +2254,7 @@ export function heartbeatService( const taskKey = deriveTaskKeyWithHeartbeatFallback(context, null); const sessionCodec = getAdapterSessionCodec(agent.adapterType); const issueId = readNonEmptyString(context.issueId); - const freshWorkspace = await timePreparation("workspace_selection", async () => { + let freshWorkspace = await timePreparation("workspace_selection", async () => { const readiness = await readFreshWorkspaceReadiness(db, run); if (issueId && canApplyTaskWorkspaceSelectionAtAdmission({ admittedInput: parseObject(run.runnerProfileJson).nativeExecutionInput, restarting: Boolean(runOptions.nativeRestartRecovery), hasLeaseOwner: Boolean(runOptions.nativeLeaseOwner) })) { const changed = await executionWorkspacesSvc.applyPendingTaskWorkspaceSelection({ companyId: agent.companyId, @@ -2537,6 +2537,11 @@ export function heartbeatService( // Initialization has persisted the active context, including an explicit // absence of identity inherited from an automatic continuation. responsibleUserId = identityContext.responsibleUserId; + if (issueId && freshWorkspace?.mode === "fresh_isolated_workspace") { + const fallback = freshWorkspace; + freshWorkspace = await timePreparation("workspace_verification", () => + verifyRetryWorkspace(db, options.pluginWorkerManager, run, issueId, responsibleUserId, fallback)); + } run = { ...run, activeIdentityContextId: identityContext.id, diff --git a/server/src/services/plugin-workspaces.ts b/server/src/services/plugin-workspaces.ts index e7abdb4698d..6faed0e455b 100644 --- a/server/src/services/plugin-workspaces.ts +++ b/server/src/services/plugin-workspaces.ts @@ -1,5 +1,5 @@ import { notifyStatusCardIssueChange } from "./status-card-notifications.js"; -import { assertProjectStorageEnvironment, effectiveProjectWorkspacePolicy, isWorkspaceProvider } from "./project-workspace-provider.js"; +import { assertProjectStorageEnvironment, effectiveProjectWorkspacePolicy, requireWorkspaceProviderWorker, type WorkspaceWorkers } from "./project-workspace-provider.js"; import { releaseProviderRecoveryTransfers, stageProviderFreshWorkspace } from "./provider-fresh-workspace.js"; import { retireAbandonedPluginWorkspaceReservation } from "./plugin-workspace-reservations.js"; import { randomUUID, createHash } from "node:crypto"; @@ -8,8 +8,6 @@ import { executionWorkspaces, heartbeatRuns, issues, - pluginCompanySettings, - plugins, projects, projectWorkspaces, type Db, @@ -26,61 +24,22 @@ import { type PluginWorkspaceParams, type PluginFreshWorkspace, } from "@paperclipai/plugin-sdk"; -import type { PluginWorkerManager } from "./plugin-worker-manager.js"; import { notifyTerminalWorkspaceWork } from "./terminal-workspace-work.js"; import { withExecutionWorkspaceLifecycleLock } from "./execution-workspace-lifecycle-lock.js"; -import { workspaceProviderCallFailure, workspaceWorkerRefusal } from "./workspace-provider-failure.js"; +import { workspaceProviderCallFailure } from "./workspace-provider-failure.js"; import { assertTaskWorkspaceExecutionAccess, assertTaskWorkspaceSourceProjectAccess, } from "./task-workspace-access.js"; import { forbidden, conflict } from "../errors.js"; -export type WorkspaceWorkers = Pick; +export type { WorkspaceWorkers } from "./project-workspace-provider.js"; type Workspace = typeof executionWorkspaces.$inferSelect; -async function provider( - db: Db, - workers: WorkspaceWorkers | undefined, - companyId: string, - pluginId: string, - /** Before a call, a ready provider whose worker is not running is a retryable refusal: no request is sent. */ - beforeCall = false, -) { - const [plugin] = await db - .select() - .from(plugins) - .where(eq(plugins.id, pluginId)); - const [settings] = await db - .select() - .from(pluginCompanySettings) - .where( - and( - eq(pluginCompanySettings.pluginId, pluginId), - eq(pluginCompanySettings.companyId, companyId), - ), - ); - const worker = workers?.getWorker(pluginId); - const refusal = beforeCall && workers && plugin?.status === "ready" && settings?.enabled !== false && - isWorkspaceProvider(plugin.manifestJson) ? workspaceWorkerRefusal(pluginId, worker) : null; - if (refusal) throw refusal; - if ( - !workers || - !plugin || - plugin.status !== "ready" || - settings?.enabled === false || - !isWorkspaceProvider(plugin.manifestJson) || - !worker?.supportedMethods?.includes("workspaceOperation") - ) { - throw conflict("The workspace storage plugin is unavailable"); - } - return plugin; -} - export async function pluginWorkspaceSupportsMergeAncestry(db: Db, workers: WorkspaceWorkers | undefined, workspace: Workspace) { const pluginId = readWorkspaceProviderBinding(workspace.metadata)?.pluginId; if (!pluginId) return true; - const selected = await provider(db, workers, workspace.companyId, pluginId); + const selected = await requireWorkspaceProviderWorker(db, workers, workspace.companyId, pluginId); return selected.manifestJson.workspaceProvider?.supportsMergeAncestry !== false; } @@ -103,7 +62,10 @@ export async function callWorkspaceProvider( const pluginId = binding?.pluginId ?? input.pluginId; if (!pluginId || !workspace.projectId) throw conflict("Workspace storage ownership is missing"); - const selectedProvider = await provider(db, workers, workspace.companyId, pluginId, true); + const selectedProvider = await requireWorkspaceProviderWorker(db, workers, workspace.companyId, pluginId, true); + const verifyExisting = input.operation.kind === "prepare" && input.operation.verifyExisting === true; + if (verifyExisting && selectedProvider.manifestJson.workspaceProvider?.workspaceVerificationVersion !== 1) + throw conflict("Workspace verification is unavailable"); if (input.operation.kind === "prepare" && input.operation.fresh && selectedProvider.manifestJson.workspaceProvider?.freshWorkspaceVersion !== 1) throw conflict("Fresh workspace preparation is unavailable"); if (input.operation.kind === "finalize" && @@ -120,7 +82,7 @@ export async function callWorkspaceProvider( throw conflict("Workspace removal identity does not match its recorded payload"); if ((operation.kind === "inspect" || operation.kind === "remove") && input.removalOperationId === undefined && selectedProvider.manifestJson.workspaceProvider?.recoveryPullRequestVersion !== 1) delete operation.recoveryPullRequest; - if (operation.kind === "prepare" && operation.fresh) { + if (operation.kind === "prepare" && operation.fresh && !verifyExisting) { if (!workspace.sourceIssueId) throw conflict("Fresh workspace task ownership is missing"); operation.fresh = await stageProviderFreshWorkspace({ db, companyId: workspace.companyId, issueId: workspace.sourceIssueId, ...operation.fresh, existing: operation.fresh }); @@ -140,7 +102,7 @@ export async function callWorkspaceProvider( ) .digest("hex")), generation: operationGeneration, - deadline: new Date(Date.now() + (operation.kind === "finalize" ? 30_000 : 300_000)).toISOString(), + deadline: new Date(Date.now() + (verifyExisting ? 10_000 : operation.kind === "finalize" ? 30_000 : 300_000)).toISOString(), runId: input.runId ?? null, agentId: input.agentId ?? null, operation, @@ -151,7 +113,7 @@ export async function callWorkspaceProvider( pluginId, "workspaceOperation", params, - operation.kind === "finalize" ? 40_000 : 310_000, + verifyExisting ? 12_000 : operation.kind === "finalize" ? 40_000 : 310_000, ); } catch (error) { // A worker that never received the call, a lost reply and a provider-reported @@ -159,7 +121,7 @@ export async function callWorkspaceProvider( throw workspaceProviderCallFailure(error); } // Recheck enablement and ownership after an external effect, including an ambiguous retry. - await provider(db, workers, workspace.companyId, pluginId); + await requireWorkspaceProviderWorker(db, workers, workspace.companyId, pluginId); const [fresh] = await db .select() .from(executionWorkspaces) @@ -204,6 +166,7 @@ export async function preparePluginWorkspace( baseRef?: string | null; fresh?: PluginFreshWorkspace; expectedBindingRevision?: number; + verifyExisting?: true; }, ) { const [previous] = input.existingWorkspaceId @@ -223,6 +186,8 @@ export async function preparePluginWorkspace( sql`${executionWorkspaces.metadata}#>>'{workspaceProviderFresh,attemptId}' = ${input.fresh.attemptId}`, )).limit(1) : []; const existing = input.fresh ? reservation : previous; + if (input.verifyExisting && (!existing || existing.metadata?.workspaceProviderRemoved === true || + existing.metadata?.workspaceProviderRestoration)) return null; const prior = existing ?? previous; if ( existing?.metadata?.workspaceProviderRetired === true || @@ -276,7 +241,7 @@ export async function preparePluginWorkspace( throw conflict( "An existing local workspace cannot change storage providers", ); - const selectedProvider = await provider(db, workers, input.companyId, pluginId, true); + const selectedProvider = await requireWorkspaceProviderWorker(db, workers, input.companyId, pluginId, true); if (input.environment) assertProjectStorageEnvironment(selectedProvider, input.environment); const declaration = selectedProvider.manifestJson.workspaceProvider!; if (input.fresh && declaration.freshWorkspaceVersion !== 1) @@ -430,6 +395,7 @@ export async function preparePluginWorkspace( status: "idle", metadata: { workspaceProviderOwner: pluginId, + workspaceProviderReservationRunId: input.runId, workspaceProviderSource: sourceInput, workspaceProviderBranchMode: input.fresh ? "create" : input.branchMode ?? "create", ...(input.fresh ? { workspaceProviderFresh: input.fresh } : {}), @@ -492,11 +458,19 @@ export async function preparePluginWorkspace( "create", baseRef: workspace.baseRef, existing: saved, + ...(input.verifyExisting ? { verifyExisting: true } : {}), ...(workspace.metadata?.workspaceProviderFresh ? { fresh: workspace.metadata.workspaceProviderFresh as PluginFreshWorkspace } : {}), }, }); if (result.kind !== "prepared") throw conflict("Workspace preparation is incomplete"); + const savedBase = workspace.metadata?.workspaceProviderBaseSha; + if (input.verifyExisting && (result.created || !result.baseSha || + (saved && result.binding.workspaceRef !== saved.workspaceRef) || + (workspace.branchName !== null && result.branchName !== workspace.branchName) || + (typeof savedBase === "string" && result.baseSha !== savedBase))) { + throw conflict("The existing checkout could not be verified"); + } await authorize(); const [currentProject] = await tx .select() @@ -660,7 +634,7 @@ export async function finalizePluginWorkspace(db: Db, workers: WorkspaceWorkers throw conflict("Workspace was removed before finalization"); const binding = readWorkspaceProviderBinding(current.metadata); if (!binding) throw conflict("Workspace storage ownership is missing"); - const selected = await provider(db, workers, current.companyId, binding.pluginId); + const selected = await requireWorkspaceProviderWorker(db, workers, current.companyId, binding.pluginId); // Existing providers continue to use their established inspection contract. if (selected.manifestJson.workspaceProvider?.finalizationVersion !== 1) return inspectBinding(db, workers, current); @@ -848,7 +822,7 @@ export async function removePluginWorkspace( } await beforeRemove?.(); const generation = workspace.metadata?.lifecycleGeneration ?? 0; - const selectedProvider = await provider(db, workers, workspace.companyId, binding.pluginId); + const selectedProvider = await requireWorkspaceProviderWorker(db, workers, workspace.companyId, binding.pluginId); const operation = workspaceProviderOperationSchema.parse({ kind: "remove", binding, expectedHeadSha, ...(recoveryPullRequest && selectedProvider.manifestJson.workspaceProvider?.recoveryPullRequestVersion === 1 ? { recoveryPullRequest } : {}) }); const operationId = createHash("sha256").update(JSON.stringify([workspace.id, generation, operation])).digest("hex"); diff --git a/server/src/services/project-workspace-provider.ts b/server/src/services/project-workspace-provider.ts index 946244a7545..5285e7c61ed 100644 --- a/server/src/services/project-workspace-provider.ts +++ b/server/src/services/project-workspace-provider.ts @@ -2,6 +2,8 @@ import { and, eq, notInArray } from "drizzle-orm"; import { pluginCompanySettings, plugins, type Db } from "@paperclipai/db"; import type { Environment, PaperclipPluginManifestV1, ProjectExecutionWorkspacePolicy, ProjectWorkspaceProviderConfiguration } from "@paperclipai/shared"; import { parseProjectExecutionWorkspacePolicy } from "./execution-workspace-policy.js"; +import type { PluginWorkerManager } from "./plugin-worker-manager.js"; +import { workspaceWorkerRefusal } from "./workspace-provider-failure.js"; import { conflict } from "../errors.js"; export function isWorkspaceProvider(manifest: PaperclipPluginManifestV1) { @@ -10,6 +12,45 @@ export function isWorkspaceProvider(manifest: PaperclipPluginManifestV1) { } type ProviderDb = Pick; +export type WorkspaceWorkers = Pick; + +export async function requireWorkspaceProviderWorker( + db: ProviderDb, + workers: WorkspaceWorkers | undefined, + companyId: string, + pluginId: string, + /** Before a call, a ready provider whose worker is not running is a retryable refusal: no request is sent. */ + beforeCall = false, +) { + const [plugin] = await db + .select() + .from(plugins) + .where(eq(plugins.id, pluginId)); + const [settings] = await db + .select() + .from(pluginCompanySettings) + .where( + and( + eq(pluginCompanySettings.pluginId, pluginId), + eq(pluginCompanySettings.companyId, companyId), + ), + ); + const worker = workers?.getWorker(pluginId); + const refusal = beforeCall && workers && plugin?.status === "ready" && settings?.enabled !== false && + isWorkspaceProvider(plugin.manifestJson) ? workspaceWorkerRefusal(pluginId, worker) : null; + if (refusal) throw refusal; + if ( + !workers || + !plugin || + plugin.status !== "ready" || + settings?.enabled === false || + !isWorkspaceProvider(plugin.manifestJson) || + !worker?.supportedMethods?.includes("workspaceOperation") + ) { + throw conflict("The workspace storage plugin is unavailable"); + } + return plugin; +} export async function listProjectWorkspaceProviders(db: ProviderDb, companyId: string) { const rows = await db.select({ plugin: plugins, enabled: pluginCompanySettings.enabled }) diff --git a/server/src/services/retry-workspace-continuity.test.ts b/server/src/services/retry-workspace-continuity.test.ts index 803a8828648..092ac7f224d 100644 --- a/server/src/services/retry-workspace-continuity.test.ts +++ b/server/src/services/retry-workspace-continuity.test.ts @@ -13,7 +13,7 @@ import { import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; import { resolveExternalTestDatabaseUrl } from "../__tests__/helpers/external-test-database.js"; import { admitExplicitNativeContinuation } from "./explicit-native-continuation.js"; -import { readFreshWorkspaceReadiness } from "./fresh-workspace-continuation.js"; +import { readFreshWorkspaceReadiness, verifyRetryWorkspace } from "./fresh-workspace-continuation.js"; import { describeRetainedPriorWorkspace, parsePorcelainZ } from "./fresh-workspace-seed.js"; import { recordNativeLocalProcessStop } from "./native-local-process-stop.js"; import { createSystemRecovery, failSystemRecovery, readSystemRecovery, SystemRecoveryFailure } from "./system-recovery-state.js"; @@ -135,7 +135,7 @@ describe.skipIf(!support.supported)("Retry workspace continuity after exhausted expect(readiness).toEqual({ mode: "reuse_issue_workspace", retryIntentId: requestId, sourceRunId: f.source.id, workspaceId: f.workspace.id, cwd: f.worktree }); // The retained directory is the same worktree: git history, branch and pre-fault files are intact. - expect((await lstat(join(readiness!.mode === "reuse_issue_workspace" ? readiness!.cwd : "", ".git"))).isFile()).toBe(true); + expect((await lstat(join(readiness!.mode === "reuse_issue_workspace" ? (readiness!.cwd ?? "") : "", ".git"))).isFile()).toBe(true); expect(await git(f.worktree, "rev-parse", "--abbrev-ref", "HEAD")).toBe(f.branchName); expect(await readFile(join(f.worktree, "NOTES.md"), "utf8")).toBe("untracked pre-fault work\n"); expect(await readFile(join(f.worktree, "README.md"), "utf8")).toContain("edited before the fault"); @@ -149,6 +149,15 @@ describe.skipIf(!support.supported)("Retry workspace continuity after exhausted expect(await readFreshWorkspaceReadiness(db, { ...successor, id: randomUUID() })).toBeNull(); }, 30_000); + it("verifies a local checkout after fresh fallback without a plugin worker", async () => { + const f = await seed("blocked_without_generation"); + const { successor, requestId } = await retry(f); + expect(await verifyRetryWorkspace(db, undefined, successor, f.issueId, "board", { + mode: "fresh_isolated_workspace", retryIntentId: requestId, sourceRunId: f.source.id, retainedSourceIds: [], + })).toEqual({ mode: "reuse_issue_workspace", retryIntentId: requestId, + sourceRunId: f.source.id, workspaceId: f.workspace.id, cwd: f.worktree }); + }, 30_000); + it("lists renamed paths from either porcelain status column once", () => { expect(parsePorcelainZ("R new.md\0old.md\0 R moved.md\0before.md\0?? NOTES.md\0 M README.md\0")).toEqual([ "new.md", "moved.md", "NOTES.md", "README.md"]); diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 0244d33d848..2cb39222091 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -31,7 +31,7 @@ "packages/plugins/sdk/src/ui/types.ts": "5a5644acf6554d2e5e1d000bfd03b97d57001eb2", "packages/plugins/sdk/src/worker-rpc-host.ts": "72f844508f695737a44d34b01b3949ec3be10aec", "packages/plugins/sdk/src/workspace-operation-error.ts": "2cd247d002d83b163239229e631bca4e519e5075", - "packages/plugins/sdk/src/workspace-provider.ts": "c212c3baffd4151010060c9ec7393bd989a9e833", + "packages/plugins/sdk/src/workspace-provider.ts": "5db136efa4bd904044113e341f443e523e336d0d", "packages/plugins/sdk/tsconfig.json": "d62ebdff94bc4b75dabf1fcad187e1e7a90fc794", "packages/shared/package.json": "6417ef8baef0cb9b836b14f453dc8bc5025709e0", "packages/shared/src/__snapshots__/slack-app-manifest.test.ts.snap": "79020ba3aa6662923f70aa44e2c483844e9901d9", @@ -405,7 +405,7 @@ "packages/shared/src/types/issue.ts": "725bd6f677b9d461460697d1ce10dee739a66ebe", "packages/shared/src/types/live.ts": "b90e55e4de8600c6fc17d7fa8d89079d4ae655ec", "packages/shared/src/types/native-finalization.ts": "c026a73003ae232fea4f7624d561493b383df358", - "packages/shared/src/types/plugin.ts": "36e0f50d97f96532cb1fbdf3223368d92a7e9b1e", + "packages/shared/src/types/plugin.ts": "016059b873c7189b8e65bb0dfa1ffa039c97c2ca", "packages/shared/src/types/project.ts": "ae2e718acd652e362cf1ef91e69aad96d12042fe", "packages/shared/src/types/quota.ts": "a0686a9afb3111a4de093f66200dc0c9152e883e", "packages/shared/src/types/resource-memberships.ts": "9eab6fad50facf3e489f8c40e5bedd92e1d1faf8", @@ -486,7 +486,7 @@ "packages/shared/src/validators/onboarding-seed.ts": "de302a8400d4199053f379d9ed853522a3ac6d32", "packages/shared/src/validators/partial.ts": "fa60ec7481fc14175365e9e500c814b159f1ab53", "packages/shared/src/validators/plugin.test.ts": "23bc443850d46d815877a71a44625fd42aebb00a", - "packages/shared/src/validators/plugin.ts": "054de474635e080073e85413211cca4b3eb8681b", + "packages/shared/src/validators/plugin.ts": "2a90d3d00b64f802b9c30f957e97702250ab2db4", "packages/shared/src/validators/project.ts": "0257acc29400f438aefc0a657250d8f28ec60838", "packages/shared/src/validators/provider-trace.ts": "b38b6200a2e51513f5dca0f8b008f2fe68175e82", "packages/shared/src/validators/resource-memberships.ts": "b124ac8a8f24b4dbb03ae82bcc87541f6b4ecdfd", From ffe05b1b7c15079a74468767bc98799db7ccfce0 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:05:54 -0600 Subject: [PATCH 04/12] fix(heartbeat): retry every pre-provider lease acquisition failure and rest it on Retry (#20857) 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 task run takes an environment lease (for example a Daytona sandbox) before the agent starts. No provider work happens before that lease exists. > - Only a provider HTTP status or a connection errno counted as a transient lease failure. #20828 (merged while this was open) added the Daytona acquisition deadline. A database error while the lease was recorded, a plugin RPC deadline, and an unfinished provisional creation still did not count. > - Those failures became a generic `setup_failed` with no bounded retry. And when the bounded retries of any `environment_provider_unavailable` failure were used up, recovery still put the task on a board-owned `stranded_assigned_issue` action. > - A hosted instance saw this for six runs in 45 minutes when concurrent runs rose from about 8 to about 20. Two tasks stayed blocked and waited for the board. > - This pull request classifies every lease acquisition failure that has structured transient evidence as `environment_provider_unavailable`. When the bounded retries are used up, the task rests on a system-owned action and a working Retry. > - It also adds the restart-chaos fault EP1, so the harness covers lease acquisition failures from now on. > - The benefit is that a busy or slow sandbox provider no longer strands tasks on the board. ## Linked Issues or Issue Description No public issue exists. **What happened?** Five runs failed with `Failed to acquire lease for environment "Paperclip Sandbox" (sandbox): Daytona lease acquisition timed out; allocation cleanup is pending` after 5 to 6 minutes in `preparing`. One run failed with `Database query failed (lease_acquire_failed)` within 10 seconds. Every run recorded `executionRecovery: { kind: "bootstrap", providerWorkStarted: false }`, but the error code was `setup_failed`. No run got a bounded retry. Two tasks were left `blocked` with a board-owned `stranded_assigned_issue` recovery action. **Expected behavior** A lease acquisition failure happens before any provider work. The run must retry with a bounded, visible backoff. When the bound is used up, the task must rest with a Retry that works, and no board-owned recovery action. **Steps to reproduce** 1. Make lease acquisition fail with the provider's acquisition deadline (the validated acquisition diagnostic that the environment runtime records), or with a database driver error. 2. Let the run start. 3. Before this change, the run fails with `setup_failed`, no retry is scheduled, and recovery creates a board-owned `stranded_assigned_issue` action. ## What Changed **How this PR and #20828 divide the problem.** #20828 (merged) makes the Daytona plugin end a stuck create early and classifies the acquisition-deadline envelope as `environment_provider_unavailable`. This PR does not change the Daytona plugin or that deadline path. It adds only what #20828 leaves out: - a lease-acquisition failure that is not a create timeout: the plugin RPC deadline (`-32003`) and an unfinished provisional creation recorded for this run; - a transient database error while the lease is recorded; - the exhausted state: a system-owned recovery action and Retry instead of a board-owned `stranded_assigned_issue`, for every `environment_provider_unavailable` cause (including #20828's); - the chaos fault EP1 (EP1, EP1N, EP1D). - `readTransientLeaseAcquisitionFailure` (`server/src/services/environment-provider-unavailable-error.ts`) classifies a lease acquisition failure as transient when it has structured evidence: the provider status or errno (as before), the run's own validated acquisition diagnostic (deadline or unfinished provisional creation), the plugin RPC deadline, or a transient database error (a postgres.js connection code, or SQLSTATE class 08 or 53, 57P01-57P03, 57014, 55P03, 40001, 40P01). A deterministic SQL error (syntax, schema, constraint) is not retried. A definite non-transient status (for example HTTP 401 or 404) is still `setup_failed`. Message text is not parsed. - `environment-run-orchestrator.ts` uses this classifier, so these failures get `environment_provider_unavailable` and the existing bounded bootstrap retry (30 s, then 60 s, with jitter). The task shows "retry scheduled" while it waits. - When the retries are used up, recovery uses the cause `environment_provider_unavailable` with a system-owned action and no board routing. The notice says "Retry when ready" and does not ask for a board decision. The task's Retry starts a new acquisition. - Restart-chaos fault EP1: a test-mode server seam (`environment-lease-fault-injection.ts`, read from `PAPERCLIP_CHAOS_LEASE_FAULT_CONTROL`, ignored in production) throws the staging error shapes before any provider call. `tests/restart-chaos/env-provider-wave.ts` runs EP1 (deadline twice, then success), EP1N (deadline forever, then Retry after disarm) and EP1D (database error once). The oracle fails on any `setup_failed` run, any board-owned recovery action, a wrong retry count, or a task that does not complete. - Docs: `doc/execution-semantics.md` and `tests/restart-chaos/README.md`. ## Verification - RED on `origin/master` (`1d67e309e0`, before #20828): the three new tests in `heartbeat-process-recovery.test.ts` ("transient sandbox provider refusal during lease acquisition") fail with the staging result: `expected [ [ 'failed', 'setup_failed' ] ] to deeply equal [ [ 'failed', 'environment_provider_unavailable' ], [ 'scheduled_retry', null ] ]`. On current master the deadline now retries (#20828), but the exhausted case still rests on a board-owned `stranded_assigned_issue` action (the existing HTTP 502 exhaustion test showed `ownerType: "board"` before the recovery change), and the database error is still `setup_failed`. - GREEN: `pnpm --filter @paperclipai/server exec vitest run src/__tests__/heartbeat-process-recovery.test.ts -t "lease acquisition"` passes 5 of 5. This includes the deadline and the database error that retry once and then complete, and the deadline that never clears. That task rests `blocked` with a system-owned action, `canRetry: true`, no execution blocker, and Retry completes it. - Unit tests: `environment-provider-unavailable-error.test.ts` + `environment-lease-fault-injection.test.ts` (56), `tests/restart-chaos/env-provider-faults.test.ts` (6) pass. - Related suites pass: `environment-run-orchestrator`, `task-interruption-query`, `issue-recovery-actions`, `issue-recovery-deadlines`, `stranded-notice`, `heartbeat-native-resume-lease-failure`. - `server` and `tests/restart-chaos` typecheck pass. - Chaos waves (local, Codex `gpt-6.1-sol`, head `1bd387e98f`; the later head changes only database classification and the notice), all pass: - EP1 `w-20261111T171803-s71-ep`, 2 tasks: each had exactly 2 `environment_provider_unavailable` runs, then succeeded with no user action, no board-owned recovery action, brief oracle pass. - EP1D `w-20261111T172850-s73-ep`, 1 task: 1 failed run on the database error, then succeeded. - EP1N `w-20261111T173346-s74-ep` (and `w-20261111T162752-s72-ep` before the rebase): 3 failed runs, the task rested `blocked` with `canRetry: true` and no board-owned action; after disarm, Retry completed it. - No Daytona wave was run. The fault is injected in the server before the provider call, so a local instance reaches the same retry and recovery code. ## Risks - More failures now retry, all bounded. Only transient SQLSTATEs retry. The staging database error recorded no SQLSTATE. If it was a deterministic SQL error, it still fails `setup_failed` and goes to the board as before; that is intended, because a retry cannot fix it. - Each retry is a new creation attempt with its own creation record. A provisional allocation whose cleanup is pending stays with its record and the creation reconciler, as before. - The retry bound is the shared bootstrap bound (two retries). A provider outage longer than about 15 minutes still rests on Retry, but no longer on a board action. - The fault seam reads a file only when the environment variable is set, and never when `NODE_ENV=production`. - Saved state from the previous release: no persisted shape changes. A task already stranded on a board action keeps it (`preserveExistingOwner`). New failures use the new cause. > 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 (Anthropic) through Claude Code, model ID `claude-opus-5-5`, 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 Fable 5.2 --- doc/execution-semantics.md | 10 + .../heartbeat-process-recovery.test.ts | 93 +++++++- .../environment-lease-fault-injection.test.ts | 63 ++++++ .../environment-lease-fault-injection.ts | 76 +++++++ ...ronment-provider-unavailable-error.test.ts | 78 +++++++ .../environment-provider-unavailable-error.ts | 80 ++++++- .../services/environment-run-orchestrator.ts | 14 +- server/src/services/recovery/service.ts | 22 +- .../services/recovery/stranded-notice.test.ts | 14 ++ .../src/services/recovery/stranded-notice.ts | 4 +- tests/restart-chaos/README.md | 24 ++ .../restart-chaos/env-provider-faults.test.ts | 49 +++++ tests/restart-chaos/env-provider-faults.ts | 106 +++++++++ tests/restart-chaos/env-provider-wave.ts | 205 ++++++++++++++++++ 14 files changed, 825 insertions(+), 13 deletions(-) create mode 100644 server/src/services/environment-lease-fault-injection.test.ts create mode 100644 server/src/services/environment-lease-fault-injection.ts create mode 100644 tests/restart-chaos/env-provider-faults.test.ts create mode 100644 tests/restart-chaos/env-provider-faults.ts create mode 100644 tests/restart-chaos/env-provider-wave.ts diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 61125608984..6f1334faebd 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -1458,6 +1458,16 @@ provider failure as the reason, retries automatically, and on exhaustion becomes `blocked` with a specific recovery notice and a Retry. Because no provider work started, no execution-reconciliation hold is created. +Lease acquisition precedes provider work by construction, so the same budget +covers every lease acquisition failure that carries structured transient evidence, +not only a provider status: the provider's acquisition deadline or an unfinished +provisional creation (the validated acquisition diagnostic the runtime recorded +for that run), the plugin RPC deadline, and a database driver error while the +lease is recorded. A definite non-transient status (for example HTTP 401 or 404) +still fails as `setup_failed`. On exhaustion the task's recovery action is +system-owned (cause `environment_provider_unavailable`), not a board escalation: +nothing needs board repair, and the task's Retry starts a new acquisition. + A saved workspace that cannot be restored into a new allocation before provider dispatch fails with `remote_workspace_restore_failed`. The run error names the server step (`snapshot_lookup`, `snapshot_download`, or `sandbox_restore`) and, diff --git a/server/src/__tests__/heartbeat-process-recovery.test.ts b/server/src/__tests__/heartbeat-process-recovery.test.ts index 559d9890075..d3ae160fe9a 100644 --- a/server/src/__tests__/heartbeat-process-recovery.test.ts +++ b/server/src/__tests__/heartbeat-process-recovery.test.ts @@ -28,6 +28,7 @@ import { recordLegacyWorkspaceRestoreFailure, terminalizeLegacyExecution } from import { issueService } from "../services/issues.js"; import { getExecutionBlocker } from "../services/execution-blocker.js"; import { JsonRpcCallError } from "@paperclipai/plugin-sdk"; +import { leaseFaultError } from "../services/environment-lease-fault-injection.js"; import { taskInterruptionPresentation } from "../services/task-interruption-presentation.js"; import { requestTaskRetry } from "../services/task-retry.js"; import { adapterExecutionControls, createAdapterExecutionControl } from "../services/adapter-execution-control.js"; @@ -5903,7 +5904,20 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => { message: "Daytona sandbox creation failed (HTTP 502); cleanup could not be confirmed for paperclip-create-05f81d77", data: { schema: "paperclip/environment-acquire-error/v1", providerDiagnostic: { httpStatus: 502 } } }); - function failLeaseAcquisition(times: number) { + // EP1: Daytona's own acquisition deadline expired while the provisional + // sandbox was still being created, as staging recorded at 14:00-14:45Z when + // concurrent runs rose from about 8 to about 20. The environment runtime + // records the validated acquisition diagnostic for this run before rethrowing. + // The chaos fault EP1 injects these same shapes (environment-lease-fault-injection.ts). + type LeaseFault = (input: { companyId: string; environment: { id: string }; heartbeatRunId?: string | null }) => Error; + const daytonaAcquisitionDeadline: LeaseFault = input => leaseFaultError("timeout", + { companyId: input.companyId, environmentId: input.environment.id, heartbeatRunId: input.heartbeatRunId! }); + // EP1 database: a control-plane query failed while the lease was being + // recorded (staging: "Database query failed (lease_acquire_failed)"). + const leaseRecordQueryFailure: LeaseFault = input => leaseFaultError("database", + { companyId: input.companyId, environmentId: input.environment.id, heartbeatRunId: input.heartbeatRunId! }); + + function failLeaseAcquisition(times: number, fault: LeaseFault = daytonaCreate502) { let remaining = times; const acquisitions = { refused: 0, delegated: 0 }; const originalFactory = environmentOrchestrator.environmentRunOrchestrator; @@ -5913,7 +5927,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => { if (remaining > 0) { remaining -= 1; acquisitions.refused += 1; - throw daytonaCreate502(); + throw fault(input); } acquisitions.delegated += 1; return runtime.acquireRunLease(input); @@ -6028,6 +6042,81 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => { mockAdapterExecute.mockClear(); } }, 90_000); + it.each([ + ["a provider acquisition deadline", daytonaAcquisitionDeadline, "timeout"], + ["a database error while recording the lease", leaseRecordQueryFailure, "overloaded"], + ] as const)("retries %s before provider work with a bounded, visible backoff", async (_label, fault, category) => { + const { companyId, agentId, runId, issueId } = await seedQueuedIssueRunFixture(); + const lease = failLeaseAcquisition(1, fault); + try { + const heartbeat = heartbeatService(db); + await heartbeat.resumeQueuedRuns(); + await heartbeat.drainActiveRunExecutions(); + + const afterFailure = await runsFor(agentId); + expect(afterFailure.map(run => [run.status, run.errorCode])).toEqual([ + ["failed", "environment_provider_unavailable"], ["scheduled_retry", null]]); + expect(afterFailure[0]!.resultJson).toMatchObject({ providerFailure: { phase: "startup", category, retryability: "transient" }, + executionRecovery: { kind: "bootstrap", providerWorkStarted: false } }); + expect(afterFailure[1]).toMatchObject({ retryOfRunId: runId, scheduledRetryAttempt: 1, scheduledRetryReason: "transient_failure" }); + const [waiting] = await db.select().from(issues).where(eq(issues.id, issueId)); + expect(waiting).toMatchObject({ status: "in_progress", executionRunId: afterFailure[1]!.id }); + expect(await taskInterruptionPresentation(db, waiting!)).toMatchObject({ state: "retry_scheduled", responsibility: "system" }); + expect(await getExecutionBlocker(db, companyId, issueId)).toBeNull(); + + await promoteLatestScheduledRetry(heartbeat, agentId); + const successors = (await runsFor(agentId)).filter(run => run.retryOfRunId === runId); + expect(successors).toHaveLength(1); + expect(successors[0]).toMatchObject({ status: "succeeded" }); + expect(lease.acquisitions.refused).toBe(1); + // The mock adapter's later disposition repair is unrelated; no setup failure reached recovery. + expect((await selectRecoveryActionsForIssue(issueId)).filter(action => action.kind === "stranded_assigned_issue")).toEqual([]); + } finally { + lease.restore(); + mockAdapterExecute.mockClear(); + } + }, 60_000); + + it("rests a provider deadline that never clears on a working Retry, never on a board recovery action", async () => { + const { companyId, agentId, issueId } = await seedQueuedIssueRunFixture(); + const lease = failLeaseAcquisition(BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS + 1, daytonaAcquisitionDeadline); + try { + const heartbeat = heartbeatService(db); + await heartbeat.resumeQueuedRuns(); + await heartbeat.drainActiveRunExecutions(); + for (let attempt = 0; attempt < BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS; attempt += 1) { + await promoteLatestScheduledRetry(heartbeat, agentId); + } + const exhausted = await runsFor(agentId); + expect(exhausted.map(run => run.errorCode)).toEqual( + Array(BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS + 1).fill("environment_provider_unavailable")); + expect(mockAdapterExecute).not.toHaveBeenCalled(); + + const blocked = await waitForValue(async () => { + const [row] = await db.select().from(issues).where(eq(issues.id, issueId)); + return row?.status === "blocked" ? row : null; + }); + const presentation = await taskInterruptionPresentation(db, blocked!); + expect(presentation).toMatchObject({ state: "failed", responsibility: "system", canRetry: true, + observedRunId: exhausted.at(-1)!.id, providerFailure: { category: "timeout", retryability: "transient" } }); + expect(await getExecutionBlocker(db, companyId, issueId)).toBeNull(); + // The task rests on a system-owned action and Retry; nothing waits on the board. + expect((await selectRecoveryActionsForIssue(issueId)).map(action => [action.ownerType, action.cause])) + .toEqual([["system", "environment_provider_unavailable"]]); + + const receipt = await requestTaskRetry({ db, companyId, issueId, actorId: "responsible-user", + idempotencyKey: randomUUID(), observedRunId: presentation!.observedRunId }); + expect(receipt.accepted).toBe(true); + await heartbeat.resumeTaskRetry(companyId, receipt.requestId!); + await heartbeat.drainActiveRunExecutions(); + expect(await waitForValue(async () => (await runsFor(agentId)).find(run => run.status === "succeeded") ?? null, 10_000)) + .not.toBeNull(); + expect(lease.acquisitions.delegated).toBe(1); + } finally { + lease.restore(); + mockAdapterExecute.mockClear(); + } + }, 90_000); }); it("classifies only the installed-but-not-ready sandbox provider plugin message as a configuration gap", () => { diff --git a/server/src/services/environment-lease-fault-injection.test.ts b/server/src/services/environment-lease-fault-injection.test.ts new file mode 100644 index 00000000000..8d163213d58 --- /dev/null +++ b/server/src/services/environment-lease-fault-injection.test.ts @@ -0,0 +1,63 @@ +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { parseLeaseFaultControl } from "./environment-lease-fault-injection.js"; + +describe("lease acquisition fault injection (chaos EP1)", () => { + let directory: string; + let control: string; + let seam: typeof import("./environment-lease-fault-injection.js"); + // Loaded after the reset, so it shares the seam's diagnostic receipts. + let readTransientLeaseAcquisitionFailure: typeof import("./environment-provider-unavailable-error.js").readTransientLeaseAcquisitionFailure; + const input = (issueId: string | null = "issue-1") => ({ companyId: "company-1", environmentId: "env-1", heartbeatRunId: "run-1", issueId }); + + beforeAll(async () => { + directory = await mkdtemp(path.join(os.tmpdir(), "lease-fault-")); + control = path.join(directory, "control.json"); + vi.stubEnv("PAPERCLIP_CHAOS_LEASE_FAULT_CONTROL", control); + vi.resetModules(); + seam = await import("./environment-lease-fault-injection.js"); + ({ readTransientLeaseAcquisitionFailure } = await import("./environment-provider-unavailable-error.js")); + }); + afterAll(async () => { + vi.unstubAllEnvs(); + await rm(directory, { recursive: true, force: true }); + }); + + it("parses only a well-formed control", () => { + expect(parseLeaseFaultControl('{"token":"a","kind":"timeout","failures":2}')).toEqual({ token: "a", kind: "timeout", failures: 2 }); + expect(parseLeaseFaultControl('{"token":"a","kind":"database","failures":null}')).toEqual({ token: "a", kind: "database", failures: null }); + expect(parseLeaseFaultControl('{"token":"a","kind":"other","failures":1}')).toBeNull(); + expect(parseLeaseFaultControl('{"token":"a b","kind":"timeout","failures":1}')).toBeNull(); + expect(parseLeaseFaultControl("")).toBeNull(); + }); + + it("is disarmed without a control file", () => { + expect(() => seam.injectLeaseAcquisitionFault(input())).not.toThrow(); + }); + + it("fails each task's first N acquisitions with a retryable staging shape, then lets them through", async () => { + await writeFile(control, JSON.stringify({ token: "t1", kind: "timeout", failures: 2 })); + for (let attempt = 0; attempt < 2; attempt += 1) { + let thrown: unknown; + try { seam.injectLeaseAcquisitionFault(input()); } catch (error) { thrown = error; } + expect(readTransientLeaseAcquisitionFailure(thrown, { id: "run-1", companyId: "company-1" })).toEqual({ acquisitionTimedOut: true }); + } + expect(() => seam.injectLeaseAcquisitionFault(input())).not.toThrow(); + // Another task keeps its own count; a run with no task is never faulted. + expect(() => seam.injectLeaseAcquisitionFault(input("issue-2"))).toThrow(/lease acquisition timed out/); + expect(() => seam.injectLeaseAcquisitionFault(input(null))).not.toThrow(); + }); + + it("re-arms with a new token, fails forever with null, and disarms on an empty file", async () => { + await writeFile(control, JSON.stringify({ token: "t2", kind: "database", failures: null })); + for (let attempt = 0; attempt < 5; attempt += 1) { + let thrown: unknown; + try { seam.injectLeaseAcquisitionFault(input()); } catch (error) { thrown = error; } + expect(readTransientLeaseAcquisitionFailure(thrown, { id: "run-1", companyId: "company-1" })).toEqual({ reason: "database_error" }); + } + await writeFile(control, ""); + expect(() => seam.injectLeaseAcquisitionFault(input())).not.toThrow(); + }); +}); diff --git a/server/src/services/environment-lease-fault-injection.ts b/server/src/services/environment-lease-fault-injection.ts new file mode 100644 index 00000000000..ac4ce3f59c3 --- /dev/null +++ b/server/src/services/environment-lease-fault-injection.ts @@ -0,0 +1,76 @@ +/** + * Restart-chaos fault EP1 (tests/restart-chaos/env-provider-faults.ts): make a + * run's lease acquisition fail before any provider call, in the exact shapes + * staging recorded, so the bounded retry and Retry paths can be exercised on a + * local instance without a paid sandbox provider. + * + * Arming (test mode only; ignored when NODE_ENV=production): + * + * PAPERCLIP_CHAOS_LEASE_FAULT_CONTROL= + * + * Each acquisition reads the file. Missing, empty or malformed means disarmed. + * Content: {"token":"","kind":"timeout"|"database","failures":|null}. + * The first acquisitions of each task under one token fail (null: every + * one), so writing a new token re-arms with fresh counts and an empty file + * disarms. Counts live in this process, so a restart starts them again. + * + * This is test instrumentation, not Telemetry or Observability + * (rules/data-paths.mdc): nothing is recorded or sent anywhere. + */ +import { readFileSync } from "node:fs"; +import { JsonRpcCallError, PLUGIN_RPC_ERROR_CODES, readEnvironmentAcquisitionDiagnostic } from "@paperclipai/plugin-sdk"; +import { captureEnvironmentAcquisitionDiagnostic } from "./environment-acquisition-diagnostics.js"; + +export const LEASE_FAULT_CONTROL_ENV = "PAPERCLIP_CHAOS_LEASE_FAULT_CONTROL"; + +export type LeaseFaultControl = { token: string; kind: "timeout" | "database"; failures: number | null }; + +export function parseLeaseFaultControl(text: string): LeaseFaultControl | null { + try { + const value = JSON.parse(text) as Record; + if (typeof value.token !== "string" || !/^[A-Za-z0-9_-]{1,80}$/.test(value.token)) return null; + if (value.kind !== "timeout" && value.kind !== "database") return null; + const failures = value.failures; + if (failures !== null && !(Number.isSafeInteger(failures) && (failures as number) >= 0)) return null; + return { token: value.token, kind: value.kind, failures: failures as number | null }; + } catch { return null; } +} + +const controlPath = process.env.NODE_ENV === "production" ? null : process.env[LEASE_FAULT_CONTROL_ENV]?.trim() || null; +const counts = new Map(); + +/** The staging shapes: Daytona's acquisition deadline, and a failed control-plane query. */ +export function leaseFaultError(kind: LeaseFaultControl["kind"], input: { + companyId: string; environmentId: string; heartbeatRunId: string; +}): Error { + if (kind === "database") { + return new Error("Failed query: insert into \"environment_leases\" (\"id\") values ($1)\nparams: ", { + cause: Object.assign(new Error("terminating connection due to administrator command"), { name: "PostgresError", code: "57P01" }), + }); + } + const error = new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR, + message: "Daytona lease acquisition timed out; allocation cleanup is pending", + data: { schema: "paperclip/environment-creation-cleanup/v1", + cleanup: { providerLeaseId: `chaos-ep1-${input.heartbeatRunId.slice(0, 8)}`, companyId: input.companyId, + environmentId: input.environmentId, runId: input.heartbeatRunId, attemptId: input.heartbeatRunId, + accountFingerprint: "0".repeat(64), labels: {} }, + acquisitionDiagnostic: { phase: "create", elapsedMs: 300_000, budgetMs: 300_000, providerState: "creating" } } }); + captureEnvironmentAcquisitionDiagnostic(error, { companyId: input.companyId, environmentId: input.environmentId, + runId: input.heartbeatRunId }, readEnvironmentAcquisitionDiagnostic(error)); + return error; +} + +/** Throws the armed fault for this acquisition; a single null check when disarmed. */ +export function injectLeaseAcquisitionFault(input: { + companyId: string; environmentId: string; heartbeatRunId: string; issueId: string | null; +}): void { + if (controlPath === null || !input.issueId) return; + let control: LeaseFaultControl | null; + try { control = parseLeaseFaultControl(readFileSync(controlPath, "utf8")); } catch { return; } + if (!control) return; + const key = `${control.token}:${input.issueId}`; + const seen = counts.get(key) ?? 0; + if (control.failures !== null && seen >= control.failures) return; + counts.set(key, seen + 1); + throw leaseFaultError(control.kind, input); +} diff --git a/server/src/services/environment-provider-unavailable-error.test.ts b/server/src/services/environment-provider-unavailable-error.test.ts index 319647827a3..7c568c5b18f 100644 --- a/server/src/services/environment-provider-unavailable-error.test.ts +++ b/server/src/services/environment-provider-unavailable-error.test.ts @@ -1,8 +1,11 @@ import { describe, expect, it } from "vitest"; +import { JsonRpcCallError, PLUGIN_RPC_ERROR_CODES, readEnvironmentAcquisitionDiagnostic } from "@paperclipai/plugin-sdk"; +import { captureEnvironmentAcquisitionDiagnostic } from "./environment-acquisition-diagnostics.js"; import { EnvironmentProviderUnavailableError, findEnvironmentProviderUnavailableError, readTransientEnvironmentProviderFailure, + readTransientLeaseAcquisitionFailure, } from "./environment-provider-unavailable-error.js"; function withStatus(status: number, key: "status" | "statusCode" = "status") { @@ -112,3 +115,78 @@ describe("EnvironmentProviderUnavailableError", () => { expect(findEnvironmentProviderUnavailableError(new Error("plain"))).toBeNull(); }); }); + +describe("readTransientLeaseAcquisitionFailure", () => { + const run = { id: "run-1", companyId: "company-1" }; + const creationFailure = (elapsedMs: number, runId = run.id) => { + const error = new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.WORKER_ERROR, + message: "Daytona lease acquisition timed out; allocation cleanup is pending", + data: { schema: "paperclip/environment-creation-cleanup/v1", + cleanup: { providerLeaseId: "paperclip-create-1", companyId: run.companyId, environmentId: "env-1", runId, + attemptId: "attempt-1", accountFingerprint: "a".repeat(64), labels: {} }, + acquisitionDiagnostic: { phase: "create", elapsedMs, budgetMs: 300_000 } } }); + captureEnvironmentAcquisitionDiagnostic(error, { companyId: run.companyId, environmentId: "env-1", runId }, + readEnvironmentAcquisitionDiagnostic(error)); + return error; + }; + + it("keeps the provider's transient status", () => { + expect(readTransientLeaseAcquisitionFailure(withStatus(503), run)).toEqual({ httpStatus: 503 }); + }); + + it("retries a creation that hit the acquisition deadline", () => { + expect(readTransientLeaseAcquisitionFailure(new Error("wrapped", { cause: creationFailure(300_000) }), run)) + .toEqual({ acquisitionTimedOut: true }); + }); + + it("retries a provisional creation that did not finish", () => { + expect(readTransientLeaseAcquisitionFailure(creationFailure(12_000), run)).toEqual({ reason: "acquisition_incomplete" }); + }); + + it("ignores an unfinished-creation diagnostic recorded for another run", () => { + expect(readTransientLeaseAcquisitionFailure(creationFailure(12_000, "run-2"), run)).toBeNull(); + }); + + it("retries a plugin RPC deadline", () => { + const timeout = new JsonRpcCallError({ code: PLUGIN_RPC_ERROR_CODES.TIMEOUT, message: "RPC call timed out" }); + expect(readTransientLeaseAcquisitionFailure(timeout, run)).toEqual({ acquisitionTimedOut: true }); + }); + + const pg = (code: string) => Object.assign(new Error("database error"), { name: "PostgresError", code }); + it.each([ + ["a terminated connection", pg("57P01")], + ["a connection failure", pg("08006")], + ["too many connections", pg("53300")], + ["a lock timeout", pg("55P03")], + ["a closed connection", Object.assign(new Error("closed"), { code: "CONNECTION_CLOSED" })], + ["a Drizzle wrapper around a statement timeout", new Error("Failed query: select 1\nparams: ", { cause: pg("57014") })], + ])("retries %s while recording the lease", (_label, cause) => { + expect(readTransientLeaseAcquisitionFailure(new Error("lease", { cause }), run)).toEqual({ reason: "database_error" }); + }); + + it.each([ + ["a unique violation", pg("23505")], + ["an undefined column", pg("42703")], + ["a Drizzle wrapper around a syntax error", new Error("Failed query: select\nparams: ", { cause: pg("42601") })], + ["a bare Drizzle wrapper", new Error("Failed query: select 1\nparams: ")], + ["an errno that looks like a SQLSTATE", Object.assign(new Error("x"), { code: "EPERM" })], + ])("does not retry %s", (_label, cause) => { + expect(readTransientLeaseAcquisitionFailure(new Error("lease", { cause }), run)).toBeNull(); + }); + + it("does not retry a definite non-transient status, even with other evidence", () => { + const refused = Object.assign(new Error("unauthorized", { cause: creationFailure(300_000) }), { status: 401 }); + expect(readTransientLeaseAcquisitionFailure(refused, run)).toBeNull(); + }); + + it("does not retry an error without structured evidence", () => { + expect(readTransientLeaseAcquisitionFailure(new Error("Daytona lease acquisition timed out"), run)).toBeNull(); + }); + + it("names the reason in the board-facing failure", () => { + const error = new EnvironmentProviderUnavailableError({ environmentName: "Sandbox", driver: "daytona", + evidence: { reason: "database_error" }, cause: null }); + expect(error.providerFailure).toMatchObject({ category: "overloaded", providerCode: "database_error" }); + expect(error.message).toContain("a database query failed while recording the lease"); + }); +}); diff --git a/server/src/services/environment-provider-unavailable-error.ts b/server/src/services/environment-provider-unavailable-error.ts index 488a57bda00..7f4d54adc9f 100644 --- a/server/src/services/environment-provider-unavailable-error.ts +++ b/server/src/services/environment-provider-unavailable-error.ts @@ -1,5 +1,6 @@ -import { readEnvironmentAcquireErrorDiagnostic, readEnvironmentAcquisitionDiagnostic } from "@paperclipai/plugin-sdk"; +import { JsonRpcCallError, PLUGIN_RPC_ERROR_CODES, readEnvironmentAcquireErrorDiagnostic, readEnvironmentAcquisitionDiagnostic } from "@paperclipai/plugin-sdk"; import type { ProviderFailure } from "@paperclipai/shared"; +import { getEnvironmentAcquisitionDiagnostic } from "./environment-acquisition-diagnostics.js"; /** * Setup failure code for a lease acquisition that the environment provider @@ -21,7 +22,13 @@ const TRANSIENT_ERROR_CODES = new Set([ "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET", ]); -type TransientProviderEvidence = { httpStatus?: number; errorCode?: string; acquisitionTimedOut?: true }; +/** + * `reason` names evidence that has neither a provider status nor a deadline: + * the provider reported a provisional creation that did not finish, or a + * control-plane database query failed while the lease was taken. + */ +type TransientLeaseFailureReason = "acquisition_incomplete" | "database_error"; +type TransientProviderEvidence = { httpStatus?: number; errorCode?: string; acquisitionTimedOut?: true; reason?: TransientLeaseFailureReason }; function own(value: unknown, key: string): unknown { try { @@ -54,6 +61,69 @@ export function readTransientEnvironmentProviderFailure(error: unknown): Transie return null; } +/** A definite non-transient HTTP status anywhere on the chain is authoritative: retrying cannot change it. */ +function definiteNonTransientStatus(error: unknown): boolean { + for (let cause = error, depth = 0; cause && depth < 5; cause = own(cause, "cause"), depth++) { + const status = readEnvironmentAcquireErrorDiagnostic(cause)?.httpStatus + ?? [own(cause, "status"), own(cause, "statusCode")].find(value => Number.isInteger(value)); + if (typeof status === "number" && status >= 400 && !TRANSIENT_HTTP_STATUSES.has(status)) return true; + } + return false; +} + +// postgres.js connection-level codes, and SQLSTATEs a repeated statement can +// pass: connection (08), insufficient resources (53), operator intervention +// (57P01-57P03, 57014 query cancelled or timed out), lock not available (55P03), +// serialization failure and deadlock (40001, 40P01). A deterministic SQL error +// (syntax, schema, constraint) is not retried. +const DATABASE_CONNECTION_CODES = new Set(["CONNECTION_CLOSED", "CONNECTION_ENDED", "CONNECTION_DESTROYED", "CONNECT_TIMEOUT"]); +const TRANSIENT_SQLSTATES = new Set(["57P01", "57P02", "57P03", "57014", "55P03", "40001", "40P01"]); + +function transientDatabaseFailure(error: unknown): boolean { + for (let cause = error, depth = 0; cause && depth < 5; cause = own(cause, "cause"), depth++) { + const code = own(cause, "code"); + if (typeof code !== "string") continue; + if (DATABASE_CONNECTION_CODES.has(code)) return true; + if (/^[0-9A-Z]{5}$/.test(code) && (code.startsWith("08") || code.startsWith("53") || TRANSIENT_SQLSTATES.has(code))) { + // A five-character code is a SQLSTATE only on a database driver error. + const name = own(cause, "name"); + if (name === "PostgresError" || name === "DatabaseError" || own(cause, "severity") !== undefined) return true; + } + } + return false; +} + +/** + * Classify a failed lease acquisition for the bounded bootstrap retry. Lease + * acquisition precedes any provider (agent) work by construction, and every + * retry is a new creation attempt with its own idempotent identity, so a + * failure is retried unless it carries a definite non-transient status. Only + * structured evidence is read: the provider's status or errno, the validated + * acquisition diagnostic the runtime recorded for this run, the plugin RPC + * deadline, or a transient database driver code. Message text is never parsed. + */ +export function readTransientLeaseAcquisitionFailure( + error: unknown, + run: { id: string; companyId: string }, +): TransientProviderEvidence | null { + const provider = readTransientEnvironmentProviderFailure(error); + if (provider) return provider; + if (definiteNonTransientStatus(error)) return null; + for (let cause = error, depth = 0; cause && depth < 5; cause = own(cause, "cause"), depth++) { + const acquisition = getEnvironmentAcquisitionDiagnostic(cause, run); + if (acquisition) { + return acquisition.elapsedMs >= acquisition.budgetMs ? { acquisitionTimedOut: true } : { reason: "acquisition_incomplete" }; + } + if (cause instanceof JsonRpcCallError && cause.code === PLUGIN_RPC_ERROR_CODES.TIMEOUT) return { acquisitionTimedOut: true }; + } + return transientDatabaseFailure(error) ? { reason: "database_error" } : null; +} + +const REASON_LABELS: Record = { + acquisition_incomplete: "sandbox creation did not finish", + database_error: "a database query failed while recording the lease", +}; + function category(evidence: TransientProviderEvidence): ProviderFailure["category"] { if (evidence.httpStatus === 429) return "rate_limit"; if (evidence.acquisitionTimedOut || evidence.httpStatus === 408 || evidence.httpStatus === 504 @@ -70,13 +140,15 @@ export class EnvironmentProviderUnavailableError extends Error { readonly providerFailure: ProviderFailure; constructor(input: { environmentName: string; driver: string; evidence: TransientProviderEvidence; cause: unknown }) { - const status = input.evidence.httpStatus !== undefined ? `HTTP ${input.evidence.httpStatus}` : input.evidence.errorCode; + const status = input.evidence.httpStatus !== undefined ? `HTTP ${input.evidence.httpStatus}` + : input.evidence.errorCode ?? (input.evidence.reason ? REASON_LABELS[input.evidence.reason] : undefined); super(status ? `Environment provider for "${input.environmentName}" was temporarily unavailable (${status}).` : `Environment provider for "${input.environmentName}" did not finish starting the sandbox in time.`, { cause: input.cause }); this.name = "EnvironmentProviderUnavailableError"; this.httpStatus = input.evidence.httpStatus ?? null; this.errorCode = input.evidence.errorCode ?? null; + const providerCode = input.evidence.errorCode ?? (input.evidence.httpStatus === undefined ? input.evidence.reason : undefined); this.providerFailure = { schema: "paperclip.provider-failure.v1", provider: /^[a-zA-Z0-9_.:/-]{1,80}$/.test(input.driver) ? input.driver : "environment", @@ -87,7 +159,7 @@ export class EnvironmentProviderUnavailableError extends Error { : `The sandbox for "${input.environmentName}" did not finish starting in time. `) + "No agent work had started. Paperclip retries automatically; if those retries are used up, use Retry once the provider is available.", ...(input.evidence.httpStatus !== undefined ? { httpStatus: input.evidence.httpStatus } : {}), - ...(input.evidence.errorCode !== undefined ? { providerCode: input.evidence.errorCode } : {}), + ...(providerCode !== undefined ? { providerCode } : {}), retryability: "transient", }; } diff --git a/server/src/services/environment-run-orchestrator.ts b/server/src/services/environment-run-orchestrator.ts index 8149b84004f..aa1c0273f62 100644 --- a/server/src/services/environment-run-orchestrator.ts +++ b/server/src/services/environment-run-orchestrator.ts @@ -22,7 +22,8 @@ import { environmentLeases, type Db } from "@paperclipai/db"; import { and, eq } from "drizzle-orm"; import { remoteExecutionHasStopped } from "./remote-execution-termination.js"; import { remoteRecoveryLeaseMismatch, type RemoteRecoveryLeaseMismatchField } from "./native-runtime/remote-recovery-lease-mismatch.js"; -import { EnvironmentProviderUnavailableError, readTransientEnvironmentProviderFailure } from "./environment-provider-unavailable-error.js"; +import { EnvironmentProviderUnavailableError, readTransientLeaseAcquisitionFailure } from "./environment-provider-unavailable-error.js"; +import { injectLeaseAcquisitionFault } from "./environment-lease-fault-injection.js"; import { findReusableSandboxResumeError } from "./reusable-sandbox-resume-error.js"; import { findPluginWorkerUnavailableError } from "./plugin-worker-unavailable-error.js"; import type { @@ -232,13 +233,18 @@ export function environmentRunOrchestrator( runnerReconnectGraceMs?: number; }): Promise { try { + // Restart-chaos EP1 only; disarmed (always in production) this is one null check. + injectLeaseAcquisitionFault({ companyId: input.companyId, environmentId: input.environment.id, + heartbeatRunId: input.heartbeatRunId, issueId: input.issueId }); return await environmentRuntime.acquireRunLease({ ...input, assertCompanyBinding: true }); } catch (err) { - // A transient provider refusal (HTTP 5xx/429/timeout) is retried by the - // setup path with its bounded bootstrap budget. Saved-sandbox resume and + // Lease acquisition precedes any provider work, so a failure without a + // definite non-transient status (HTTP 5xx/429, errno, acquisition + // deadline, unfinished creation, database error) is retried by the setup + // path with its bounded bootstrap budget. Saved-sandbox resume and // stopped-worker refusals keep their own, more specific classifications. const transient = findReusableSandboxResumeError(err) || findPluginWorkerUnavailableError(err) - ? null : readTransientEnvironmentProviderFailure(err); + ? null : readTransientLeaseAcquisitionFailure(err, { id: input.heartbeatRunId, companyId: input.companyId }); throw new EnvironmentRunError( "lease_acquire_failed", `Failed to acquire lease for environment "${input.environment.name}" (${input.environment.driver}): ${err instanceof Error ? err.message : String(err)}`, diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 65292d727b1..b4700a75722 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -299,6 +299,7 @@ export type StrandedRecoveryCause = | "deliberate_wait_without_target" | "process_lost" | "provider_quota" + | typeof ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE | "codex_output_inactivity_monitor" | "workspace_validation_failed" | "configuration_incomplete" @@ -444,12 +445,24 @@ function isProviderQuotaRecovery(latestRun: LatestIssueRun) { ); } +/** + * Lease acquisition failed before any provider work, and its bounded retry + * budget is spent. Nothing needs inspection or repair by the board: the task + * rests on a system-owned action and the normal Retry, never on a board one. + */ +function isPreDispatchEnvironmentProviderFailure(latestRun: LatestIssueRun) { + if (latestRun?.errorCode !== ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE) return false; + const recovery = parseObject(parseObject(latestRun.resultJson).executionRecovery); + return recovery.kind === "bootstrap" && recovery.providerWorkStarted === false; +} + function resolveStrandedRecoveryCause( latestRun: LatestIssueRun, explicitCause?: StrandedRecoveryCause, ): StrandedRecoveryCause { if (explicitCause) return explicitCause; if (isProviderQuotaRecovery(latestRun)) return "provider_quota"; + if (isPreDispatchEnvironmentProviderFailure(latestRun)) return ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE; if (latestRun?.errorCode === "process_lost") return "process_lost"; if (latestRun?.errorCode === "codex_output_inactivity_monitor") { return "codex_output_inactivity_monitor"; @@ -2553,6 +2566,7 @@ export function recoveryService( latestRun: input.latestRun, }); const isProviderQuotaWait = recoveryCause === "provider_quota"; + const isEnvironmentProviderWait = recoveryCause === ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE; const now = new Date(); const actions = database === db ? recoveryActionsSvc : issueRecoveryActionService(database); const action = await actions.upsertSourceScoped({ @@ -2565,7 +2579,7 @@ export function recoveryService( supersedeOnIdentityChange: recoveryCause === "configuration_incomplete", preserveExistingOwner: true, kind: strandedRecoveryActionKind(recoveryCause), - ownerType: isProviderQuotaWait ? "system" : "board", + ownerType: isProviderQuotaWait || isEnvironmentProviderWait ? "system" : "board", ownerAgentId: null, ownerUserId: null, previousOwnerAgentId: input.issue.assigneeAgentId, @@ -2587,7 +2601,7 @@ export function recoveryService( failureSummary: summarizeRunFailureForIssueComment(input.latestRun)?.trim() ?? null, }, - evidenceOnCreate: isProviderQuotaWait + evidenceOnCreate: isProviderQuotaWait || isEnvironmentProviderWait ? {} : { routingPolicy: STRANDED_BOARD_ESCALATION_POLICY }, nextAction: @@ -2597,6 +2611,8 @@ export function recoveryService( ? "Board operator: inspect the retry history, then explicitly retry the original owner, reassign, or intentionally resolve the task." : recoveryCause === "provider_quota" ? "Wait for provider quota recovery, then retry the original assignee; do not wake a takeover owner." + : isEnvironmentProviderWait + ? "No agent work started. Retry the task once the environment provider is available." : recoveryCause === "codex_output_inactivity_monitor" ? "Board operator: inspect the inactivity evidence, then explicitly retry the original owner, reassign, or intentionally resolve the task." : recoveryCause === "workspace_validation_failed" @@ -2632,6 +2648,8 @@ export function recoveryService( type: "monitor_only", reason: recoveryCause, } + : isEnvironmentProviderWait + ? { type: "manual_retry", reason: recoveryCause, preservesSourceAssignee: true } : { type: "board_escalation", reason: recoveryCause, diff --git a/server/src/services/recovery/stranded-notice.test.ts b/server/src/services/recovery/stranded-notice.test.ts index 8f810f0e1bf..551187539f4 100644 --- a/server/src/services/recovery/stranded-notice.test.ts +++ b/server/src/services/recovery/stranded-notice.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; import { noticeMetadataReferencesRecoveryAction } from "./successful-run-handoff.js"; +import { ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE } from "../environment-provider-unavailable-error.js"; import { DEFAULT_STRANDED_RECOVERY_NOTICE_BODY, buildConfigurationIncompleteRecoveryNoticeSeed, @@ -147,6 +148,19 @@ describe("buildStrandedRecoveryEscalationNotice", () => { expect(notice.body).toContain("before the agent started"); expect(JSON.stringify(notice.metadata)).toContain("worker status"); }); + it("asks for Retry, not a board decision, when the environment provider stayed unavailable", () => { + const notice = buildStrandedRecoveryEscalationNotice({ + seed: buildImmediateExecutionPathRecoveryNoticeSeed({ status: "in_progress" }), + recoveryCause: ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE, + recoveryActionId: "provider-recovery", + recoveryOwner: null, + sourceRun: { id: "failed-run", status: "failed", errorCode: ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE }, + }); + const metadata = JSON.stringify(notice.metadata); + expect(notice.presentation.title).toBe("Environment provider was temporarily unavailable"); + expect(metadata).toContain("Retry when ready"); + expect(metadata).not.toContain("Board decision required"); + }); const actionId = "6a2f8e64-6f5e-4b58-b7fd-111111111111"; const owner = { id: "9b1c2d3e-4f50-4a61-8b72-222222222222", name: "CTO" }; const sourceRun = { diff --git a/server/src/services/recovery/stranded-notice.ts b/server/src/services/recovery/stranded-notice.ts index 694a6689aef..1367cd2e7e3 100644 --- a/server/src/services/recovery/stranded-notice.ts +++ b/server/src/services/recovery/stranded-notice.ts @@ -1,4 +1,5 @@ import type { IssueCommentMetadata, IssueCommentPresentation } from "@paperclipai/shared"; +import { ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE } from "../environment-provider-unavailable-error.js"; import { agentLinkRow, keyValueRow, @@ -281,7 +282,8 @@ export function buildStrandedRecoveryEscalationNotice(input: { ? agentLinkRow("Recovery owner", input.recoveryOwner) : keyValueRow( "Recovery owner", - "Board decision required", + // A pre-dispatch provider outage needs no board decision, only Retry. + input.recoveryCause === ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE ? "Retry when ready" : "Board decision required", ), keyValueRow( "Next action", diff --git a/tests/restart-chaos/README.md b/tests/restart-chaos/README.md index 6d08b5bd47f..bd69b2022d5 100644 --- a/tests/restart-chaos/README.md +++ b/tests/restart-chaos/README.md @@ -461,6 +461,30 @@ The observer clicks Retry in the board UI, as for every other cell. In waves `w- and `w-20261111T134316-s9413` the disk-full rest showed "Recover saved files", not a Retry button, while the API reported `canRetry: true`; R3 records this as `ui_retry_button_missing`. +## Environment-provider faults (EP1, `env-provider-wave.ts`) + +```sh +node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/env-provider-wave.ts --fault EP1 --adapters codex --tasks 2 --seed 71 +node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/env-provider-wave.ts --fault EP1N --tasks 1 --seed 72 +node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/env-provider-wave.ts --fault EP1D --tasks 1 --seed 73 +``` + +Lease acquisition fails before any provider call, in the shapes staging recorded +on 2026-11-11: Daytona's acquisition deadline ("lease acquisition timed out; +allocation cleanup is pending") and a failed database query. The server seam +`server/src/services/environment-lease-fault-injection.ts` (test mode only) reads +`PAPERCLIP_CHAOS_LEASE_FAULT_CONTROL` and fails each task's first N acquisitions. +It runs on a local instance; no sandbox provider is needed. One fault per wave. + +| Fault | Shape | Pass | +| --- | --- | --- | +| EP1 | Deadline, 2 times (the automatic bound), then succeeds | Exactly 2 `environment_provider_unavailable` runs, no `setup_failed`, completes with no user action | +| EP1N | Deadline on every attempt | 3 failed runs, the task rests offering Retry; the harness disarms, clicks Retry, and the task completes | +| EP1D | Database error once, then succeeds | 1 failed run, completes with no user action | + +Every fault also fails if a board-owned recovery action is ever active on the +task, and the A1 brief oracle must pass. Results go to `results/-ep/`. + ## Config faults (CF1–CF3, `config-wave.ts`) ```sh diff --git a/tests/restart-chaos/env-provider-faults.test.ts b/tests/restart-chaos/env-provider-faults.test.ts new file mode 100644 index 00000000000..a17301c1398 --- /dev/null +++ b/tests/restart-chaos/env-provider-faults.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from "vitest"; +import { BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS } from "../../server/src/services/heartbeat/retries.js"; +import { parseLeaseFaultControl } from "../../server/src/services/environment-lease-fault-injection.js"; +import { AUTOMATIC_RETRY_BOUND, ENV_PROVIDER_FAULTS, gradeEnvProviderTask, leaseFaultControl, type EpTaskRecord } from "./env-provider-faults.js"; + +const base = (overrides: Partial): EpTaskRecord => ({ + taskId: "t01", nonce: "n", fault: "EP1", issueId: "issue", harnessError: null, runs: [], activeRecoveryActions: [], + recoveryReads: 3, recoveryReadFailures: 0, rested: null, retryClicked: false, finalStatus: "done", briefOk: true, ...overrides, +}); +const failedRun = (id: string, errorCode = "environment_provider_unavailable") => ({ id, status: "failed", errorCode }); + +describe("EP1 environment-provider faults", () => { + it("tracks the server's automatic retry bound", () => { + expect(AUTOMATIC_RETRY_BOUND).toBe(BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS); + }); + + it("writes a control the server seam accepts", () => { + for (const fault of Object.values(ENV_PROVIDER_FAULTS)) { + expect(parseLeaseFaultControl(leaseFaultControl(fault, "wave-1"))).toEqual({ token: "wave-1", kind: fault.shape, failures: fault.failures }); + } + }); + + it("passes a task that retried within the bound and completed by itself", () => { + const grade = gradeEnvProviderTask(base({ runs: [failedRun("a"), failedRun("b"), { id: "c", status: "succeeded", errorCode: null }] })); + expect(grade.pass).toBe(true); + }); + + it("fails the staging shape: a generic setup failure stranded on a board action", () => { + const grade = gradeEnvProviderTask(base({ runs: [failedRun("a", "setup_failed")], finalStatus: "blocked", briefOk: false, + activeRecoveryActions: [{ ownerType: "board", kind: "stranded_assigned_issue", cause: "stranded_assigned_issue" }] })); + expect(grade.checks.filter(check => !check.pass).map(check => check.name)) + .toEqual(["bounded_retry", "no_board_recovery_action", "completes_without_user", "brief_oracle"]); + }); + + it("fails when recovery actions could not be read", () => { + const runs = [failedRun("a"), failedRun("b"), { id: "c", status: "succeeded", errorCode: null }]; + expect(gradeEnvProviderTask(base({ runs, recoveryReadFailures: 1 })).checks.find(check => check.name === "recovery_evidence_read")?.pass).toBe(false); + expect(gradeEnvProviderTask(base({ runs, recoveryReads: 0 })).pass).toBe(false); + }); + + it("requires a never-clearing fault to rest on Retry and finish after it", () => { + const runs = [failedRun("a"), failedRun("b"), failedRun("c"), { id: "d", status: "succeeded", errorCode: null }]; + expect(gradeEnvProviderTask(base({ fault: "EP1N", runs, rested: { issueStatus: "blocked", canRetry: true, observedRunId: "c" }, + retryClicked: true, activeRecoveryActions: [{ ownerType: "system", kind: "stranded_assigned_issue", cause: "environment_provider_unavailable" }] })).pass) + .toBe(true); + expect(gradeEnvProviderTask(base({ fault: "EP1N", runs, rested: { issueStatus: "blocked", canRetry: false, observedRunId: null } })).pass) + .toBe(false); + }); +}); diff --git a/tests/restart-chaos/env-provider-faults.ts b/tests/restart-chaos/env-provider-faults.ts new file mode 100644 index 00000000000..337e33fb0d7 --- /dev/null +++ b/tests/restart-chaos/env-provider-faults.ts @@ -0,0 +1,106 @@ +/** + * Environment-provider fault family (EP1): pure catalog, control format and oracle. + * + * Staging (2026-11-11, 14:00-14:45Z) had five Daytona lease acquisitions time + * out ("Daytona lease acquisition timed out; allocation cleanup is pending") + * and one fail on a database query, all before any provider work. None got a + * bounded retry, and two tasks were left blocked on a board-owned + * `stranded_assigned_issue` recovery action. Every other harness fault hits + * the control plane, storage or the provider stream; nothing failed lease + * acquisition itself. + * + * The server seam is `server/src/services/environment-lease-fault-injection.ts` + * (test mode only): it throws the staging error shapes for each task's first + * N acquisitions, before any provider call, so a local wave exercises the + * same retry and Retry paths a Daytona outage does. + * + * Oracle, per task: + * 1. bounded retry: exactly the expected number of runs fail with + * `environment_provider_unavailable`, never a generic `setup_failed`; + * 2. no board-owned recovery action is ever active on the task; + * 3. EP1/EP1D: the task completes with no user action; + * EP1N (never clears): the task rests offering Retry, and after the + * harness disarms the fault and clicks Retry the task completes; + * 4. the A1 brief oracle passes. + * + * I/O lives in env-provider-wave.ts; this file is credential-free and unit tested. + */ + +export const ENV_PROVIDER_FAULT_KINDS = ["EP1", "EP1N", "EP1D"] as const; +export type EnvProviderFaultKind = (typeof ENV_PROVIDER_FAULT_KINDS)[number]; + +/** BOUNDED_TRANSIENT_HEARTBEAT_RETRY_MAX_ATTEMPTS in server/src/services/heartbeat/retries.ts. */ +export const AUTOMATIC_RETRY_BOUND = 2; + +export interface EnvProviderFault { + kind: EnvProviderFaultKind; + label: string; + /** The server seam's error shape. */ + shape: "timeout" | "database"; + /** Failures per task; null never clears until the harness disarms it. */ + failures: number | null; +} + +export const ENV_PROVIDER_FAULTS: Record = { + EP1: { kind: "EP1", label: "Lease acquisition times out N times, then succeeds", shape: "timeout", failures: AUTOMATIC_RETRY_BOUND }, + EP1N: { kind: "EP1N", label: "Lease acquisition times out on every attempt", shape: "timeout", failures: null }, + EP1D: { kind: "EP1D", label: "A database query fails during lease acquisition once", shape: "database", failures: 1 }, +}; + +/** The control file the seam reads (PAPERCLIP_CHAOS_LEASE_FAULT_CONTROL). An empty file disarms. */ +export function leaseFaultControl(fault: EnvProviderFault, token: string): string { + return JSON.stringify({ token, kind: fault.shape, failures: fault.failures }); +} + +/** Runs of the task in creation order, as `/api/issues/:id/runs` reports them. */ +export interface EpRunSample { id: string; status: string; errorCode: string | null } + +export interface EpTaskRecord { + taskId: string; + nonce: string; + fault: EnvProviderFaultKind; + issueId: string | null; + harnessError: string | null; + runs: EpRunSample[]; + /** Every recovery action seen active on the task at any poll. */ + activeRecoveryActions: Array<{ ownerType: string; kind: string; cause: string | null }>; + /** Polls that read the task's recovery actions, and polls where that read failed. */ + recoveryReads: number; + recoveryReadFailures: number; + /** EP1N: the resting state before Retry. */ + rested: { issueStatus: string; canRetry: boolean; observedRunId: string | null } | null; + retryClicked: boolean; + finalStatus: string | null; + briefOk: boolean | null; +} + +export interface EpCheck { name: string; pass: boolean; detail: string } +export interface EpGrade { pass: boolean; checks: EpCheck[] } + +export function gradeEnvProviderTask(record: EpTaskRecord): EpGrade { + const fault = ENV_PROVIDER_FAULTS[record.fault]; + const failed = record.runs.filter(run => run.errorCode === "environment_provider_unavailable").length; + const generic = record.runs.filter(run => run.errorCode === "setup_failed").length; + const expected = fault.failures ?? AUTOMATIC_RETRY_BOUND + 1; + const board = record.activeRecoveryActions.filter(action => action.ownerType === "board"); + const checks: EpCheck[] = [ + { name: "no_harness_error", pass: record.harnessError === null, detail: record.harnessError ?? "ok" }, + { name: "bounded_retry", pass: failed === expected && generic === 0, + detail: `${failed} environment_provider_unavailable run(s), expected ${expected}; ${generic} setup_failed` }, + { name: "recovery_evidence_read", pass: record.recoveryReads > 0 && record.recoveryReadFailures === 0, + detail: `${record.recoveryReads} read(s), ${record.recoveryReadFailures} failed` }, + { name: "no_board_recovery_action", pass: board.length === 0, + detail: board.length ? board.map(action => `${action.kind}/${action.cause ?? "-"}`).join(", ") : "none" }, + ]; + if (fault.failures === null) { + checks.push({ name: "rests_with_retry", pass: record.rested !== null && record.rested.canRetry, + detail: record.rested ? `${record.rested.issueStatus}, canRetry=${String(record.rested.canRetry)}` : "never rested" }); + checks.push({ name: "retry_completes", pass: record.retryClicked && record.finalStatus === "done", + detail: `retry ${record.retryClicked ? "clicked" : "not clicked"}, final ${record.finalStatus ?? "unknown"}` }); + } else { + checks.push({ name: "completes_without_user", pass: !record.retryClicked && record.finalStatus === "done", + detail: `final ${record.finalStatus ?? "unknown"}` }); + } + checks.push({ name: "brief_oracle", pass: record.briefOk === true, detail: record.briefOk === null ? "not read" : String(record.briefOk) }); + return { pass: checks.every(check => check.pass), checks }; +} diff --git a/tests/restart-chaos/env-provider-wave.ts b/tests/restart-chaos/env-provider-wave.ts new file mode 100644 index 00000000000..f08c27506f1 --- /dev/null +++ b/tests/restart-chaos/env-provider-wave.ts @@ -0,0 +1,205 @@ +/** + * Environment-provider fault waves (EP1). See env-provider-faults.ts for the + * oracle and README.md ("Environment-provider faults") for usage. + * + * node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/env-provider-wave.ts \ + * --fault EP1 --adapters codex --tasks 2 --seed 71 + * + * One fault per wave: the server seam reads one control file, and every task's + * own first acquisitions fail. The harness launches A1 brief tasks, watches + * their runs and recovery actions, and for EP1N disarms the fault once every + * task rests and then uses the task's Retry. + */ +import { spawnSync } from "node:child_process"; +import { randomUUID } from "node:crypto"; +import { existsSync } from "node:fs"; +import { mkdir, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { parseArgs } from "node:util"; +import { setTimeout as delay } from "node:timers/promises"; +import { releaseInstance } from "../runner-e2e/instance-retention.js"; +import { ChaosApi } from "./api.js"; +import { CREDENTIAL_FOR_ADAPTER, waveIdFor } from "./config.js"; +import { + ENV_PROVIDER_FAULT_KINDS, ENV_PROVIDER_FAULTS, gradeEnvProviderTask, leaseFaultControl, + type EnvProviderFaultKind, type EpGrade, type EpTaskRecord, +} from "./env-provider-faults.js"; +import { knownSecretValues, redactKnownSecrets } from "./evidence.js"; +import { seedChaosLab, type ChaosLab } from "./seed.js"; +import { ChaosSupervisor } from "./supervisor.js"; +import { Timeline } from "./timeline.js"; +import { ADAPTER_IDS, type AdapterId } from "./types.js"; +import { workloadDefinitions } from "./workloads.js"; + +const repositoryRoot = path.resolve(import.meta.dirname, "../.."); +const resultsRoot = path.resolve(process.env.RESTART_CHAOS_RESULTS_DIR ?? path.join(import.meta.dirname, "results")); +const POLL_MS = 4_000; +type Json = Record; + +interface WaveOptions { fault: EnvProviderFaultKind; adapters: AdapterId[]; tasks: number; seed: number; restBoundMs: number; doneBoundMs: number } + +export function parseEnvProviderWaveArgs(argv: readonly string[]): { options: WaveOptions; keep: boolean } { + const { values } = parseArgs({ args: argv[0] === "--" ? argv.slice(1) : [...argv], strict: true, options: { + fault: { type: "string" }, adapters: { type: "string" }, tasks: { type: "string" }, seed: { type: "string" }, + "rest-seconds": { type: "string" }, "done-seconds": { type: "string" }, keep: { type: "boolean" }, + } }); + const fault = (values.fault ?? "EP1") as EnvProviderFaultKind; + if (!ENV_PROVIDER_FAULT_KINDS.includes(fault)) throw new Error(`--fault must be one of ${ENV_PROVIDER_FAULT_KINDS.join(", ")}`); + const adapters = (values.adapters ?? "codex").split(",").map(item => item.trim()).filter(Boolean) as AdapterId[]; + for (const adapter of adapters) if (!ADAPTER_IDS.includes(adapter)) throw new Error(`Unknown adapter "${adapter}"`); + const int = (raw: string | undefined, name: string, fallback: number, min: number, max: number) => { + if (raw === undefined) return fallback; + const value = Number(raw); + if (!Number.isSafeInteger(value) || value < min || value > max) throw new Error(`--${name} must be an integer between ${min} and ${max}`); + return value; + }; + return { keep: values.keep === true, options: { fault, adapters, tasks: int(values.tasks, "tasks", 2, 1, 6), + seed: int(values.seed, "seed", Date.now() % 100_000, 0, 2 ** 31 - 1), + // Two automatic retries back off about 30 s and 60 s (with jitter) after each failure. + restBoundMs: int(values["rest-seconds"], "rest-seconds", 420, 120, 1_800) * 1_000, + doneBoundMs: int(values["done-seconds"], "done-seconds", 900, 120, 3_600) * 1_000 } }; +} + +async function sample(api: ChaosApi, record: EpTaskRecord): Promise<{ issue: Json; interruption: Json | null } | null> { + try { + const [issue, runs, recovery] = await Promise.all([ + api.get(`/api/issues/${record.issueId}`, 5_000), + api.get(`/api/issues/${record.issueId}/runs`, 5_000), + // A failed read is recorded, never taken as "no actions": the grade needs this evidence. + api.get(`/api/issues/${record.issueId}/recovery-actions`, 5_000).catch(() => null), + ]); + if (recovery && Array.isArray(recovery.actions)) record.recoveryReads += 1; + else record.recoveryReadFailures += 1; + const known = new Map(record.runs.map(run => [run.id, run])); + for (const run of runs ?? []) { + const id = String(run.runId ?? run.id); + known.set(id, { id, status: String(run.status), errorCode: run.errorCode ?? null }); + } + record.runs = [...known.values()]; + for (const action of (recovery?.actions ?? []) as Json[]) { + if (!["active", "escalated"].includes(String(action.status))) continue; + const seen = { ownerType: String(action.ownerType), kind: String(action.kind), cause: action.cause ?? null }; + if (!record.activeRecoveryActions.some(prior => prior.ownerType === seen.ownerType && prior.kind === seen.kind && prior.cause === seen.cause)) { + record.activeRecoveryActions.push(seen); + } + } + return { issue, interruption: (issue.interruption ?? null) as Json | null }; + } catch { + return null; + } +} + +async function waitFor(api: ChaosApi, record: EpTaskRecord, boundMs: number, done: (state: { issue: Json; interruption: Json | null }) => boolean) { + const deadline = Date.now() + boundMs; + while (Date.now() < deadline) { + const state = await sample(api, record); + if (state) { + record.finalStatus = String(state.issue.status); + if (done(state)) return state; + } + await delay(POLL_MS); + } + return null; +} + +async function runWave(options: WaveOptions, waveDir: string, timeline: Timeline, keep: boolean): Promise> { + const fault = ENV_PROVIDER_FAULTS[options.fault]; + const supervisor = await ChaosSupervisor.create({ repositoryRoot, waveDir, timeline }); + const control = path.join(supervisor.paths.temporaryRoot, "lease-fault-control.json"); + await writeFile(control, leaseFaultControl(fault, `wave${options.seed}`), { mode: 0o600 }); + let stopFailed = false; + const records: EpTaskRecord[] = []; + try { + await supervisor.start({ PAPERCLIP_CHAOS_LEASE_FAULT_CONTROL: control }); + const api = new ChaosApi(supervisor.baseUrl); + const lab: ChaosLab = await seedChaosLab({ api, env: "local", waitForReadyAgents: true, adapters: [...new Set(options.adapters)], + concurrency: options.tasks, budgetCents: 3_000, fixtureRoot: path.join(supervisor.paths.temporaryRoot, "fixtures"), + waveId: path.basename(waveDir), timeline }); + const a1 = workloadDefinitions.A1; + for (let index = 0; index < options.tasks; index += 1) { + const adapter = options.adapters[index % options.adapters.length]!; + const nonce = randomUUID().slice(0, 8); + const record: EpTaskRecord = { taskId: `t${String(index + 1).padStart(2, "0")}`, nonce, fault: options.fault, issueId: null, harnessError: null, + runs: [], activeRecoveryActions: [], recoveryReads: 0, recoveryReadFailures: 0, rested: null, retryClicked: false, finalStatus: null, briefOk: null }; + records.push(record); + try { + const issue = await api.post(`/api/companies/${lab.companyId}/issues`, { title: `Chaos ${options.fault} ${nonce}`, + description: a1.description(nonce), status: "todo", priority: "medium", assigneeAgentId: lab.agents[adapter].id, projectId: lab.projectId }); + record.issueId = String(issue.id); + timeline.add("ep_launched", { taskId: record.taskId, issueId: record.issueId, adapter }); + } catch (error) { + record.harnessError = `launch: ${error instanceof Error ? error.message : String(error)}`.slice(0, 600); + } + } + const live = records.filter(record => record.issueId); + if (fault.failures === null) { + // Never clears: each task must rest offering Retry within the bound. + await Promise.all(live.map(async record => { + const rested = await waitFor(api, record, options.restBoundMs, state => state.interruption?.canRetry === true + && ["blocked", "todo", "in_progress"].includes(String(state.issue.status)) + && !record.runs.some(run => ["queued", "running", "scheduled_retry"].includes(run.status))); + record.rested = rested ? { issueStatus: String(rested.issue.status), canRetry: rested.interruption?.canRetry === true, + observedRunId: rested.interruption?.observedRunId ?? null } : null; + timeline.add("ep_rested", { taskId: record.taskId, rested: record.rested }); + })); + await writeFile(control, "", { mode: 0o600 }); + timeline.add("ep_disarmed", {}); + for (const record of live) { + if (!record.rested?.observedRunId) continue; + const response = await api.post(`/api/issues/${record.issueId}/retry`, { idempotencyKey: randomUUID(), observedRunId: record.rested.observedRunId }); + record.retryClicked = response?.accepted === true; + timeline.add("ep_retry_clicked", { taskId: record.taskId, accepted: response?.accepted ?? null }); + } + } + await Promise.all(live.map(record => waitFor(api, record, options.doneBoundMs, state => state.issue.status === "done"))); + for (const record of live) { + const brief = await api.get(`/api/issues/${record.issueId}/documents/brief`).then(row => typeof row?.body === "string" ? row.body : null).catch(() => null); + record.briefOk = a1.grade(record.nonce, { issueStatus: record.finalStatus, documents: { brief }, agentComments: [], files: {}, commands: {}, workspacePath: null }).verdict === "pass"; + } + } finally { + try { await supervisor.stop(); } catch { stopFailed = true; } + await releaseInstance(supervisor.paths.temporaryRoot, { keep, stopFailed, owner: path.basename(waveDir) }) + .catch(error => timeline.add("instance_cleanup_failed", { error: String(error) })); + } + return records.map(record => ({ record, grade: gradeEnvProviderTask(record) })); +} + +export function envProviderSummaryMarkdown(waveId: string, gitSha: string, fault: EnvProviderFaultKind, rows: Array<{ record: EpTaskRecord; grade: EpGrade }>): string { + const lines = [`# Environment-provider fault wave ${waveId}`, "", `Commit ${gitSha}`, "", `Fault ${fault}: ${ENV_PROVIDER_FAULTS[fault].label}`, "", + "| Task | Runs (errorCode) | Final | Pass |", "| --- | --- | --- | --- |"]; + for (const { record, grade } of rows) { + lines.push(`| ${record.taskId} | ${record.runs.map(run => `${run.status}${run.errorCode ? `/${run.errorCode}` : ""}`).join(", ")} | ${record.finalStatus ?? "?"} | ${grade.pass ? "pass" : "FAIL"} |`); + } + lines.push("", "## Checks", ""); + for (const { record, grade } of rows) { + lines.push(`### ${record.taskId}`, "", ...grade.checks.map(check => `- ${check.pass ? "pass" : "FAIL"} ${check.name}: ${check.detail}`), ""); + } + return lines.join("\n"); +} + +async function main(): Promise { + const { options, keep } = parseEnvProviderWaveArgs(process.argv.slice(2)); + const missing = [...new Set(options.adapters.map(adapter => CREDENTIAL_FOR_ADAPTER[adapter]))].filter(key => !process.env[key]); + if (missing.length) throw new Error(`Missing credentials ${missing.join(", ")}. Run: set -a; source ~/.secrets; set +a`); + const runner = process.env.PAPERCLIP_RUNNER_BINARY ?? path.join(repositoryRoot, "packages/paperclip-runner/runner/target/debug/paperclip-runnerd"); + if (!existsSync(runner)) throw new Error(`Runner binary missing at ${runner}. Run: node scripts/agent-preflight.mjs`); + const waveId = `${waveIdFor(options.seed)}-ep`; + const waveDir = path.join(resultsRoot, waveId); + await mkdir(waveDir, { recursive: true, mode: 0o700 }); + const timeline = new Timeline(path.join(waveDir, "timeline.jsonl")); + const gitSha = spawnSync("git", ["rev-parse", "HEAD"], { cwd: repositoryRoot, encoding: "utf8" }).stdout.trim(); + timeline.add("ep_wave_planned", { waveId, gitSha, options }); + const rows = await runWave(options, waveDir, timeline, keep); + for (const row of rows) { + await writeFile(path.join(waveDir, `${row.record.taskId}.ep-grade.json`), + `${redactKnownSecrets(JSON.stringify(row, null, 2), knownSecretValues())}\n`, { mode: 0o600 }); + } + const summary = envProviderSummaryMarkdown(waveId, gitSha, options.fault, rows); + await writeFile(path.join(waveDir, "SUMMARY.md"), summary, { mode: 0o600 }); + console.info(`\n${summary}\nWave ${waveId}: results ${waveDir}`); + return rows.length === options.tasks && rows.every(row => row.grade.pass) ? 0 : 1; +} + +if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(import.meta.filename)) { + process.exit(await main().catch(error => { console.error(error); return 2; })); +} From 566a97b88228ac43e4307aae3ae3f6691c811299 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:10:24 -0600 Subject: [PATCH 05/12] fix(native): an unretirable predecessor sends the next attempt to a fresh sandbox (#20863) 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 > - Native runs on a reused sandbox keep the previous run's warm Runner, and a new run must retire that owner before it starts > - #20844 retires the owner when Paperclip can prove it stopped. Some owners can never be proven stopped: the controller journal drain outlives the close grace, the Runner never confirms suspension, or a parked question leaves a tool input unanswered > - Then the new run failed before any provider work, and the task stayed blocked with no automatic continuation > - The general answer is to leave the old Runner on its sandbox and start the next attempt on a fresh sandbox restored from the saved workspace > - This pull request adds that fallback for every path that retires a predecessor, and settles a parked question's tool input once its Runner is gone > - The benefit is that an unprovable predecessor no longer fails a task that did no work ## Linked Issues or Issue Description **What happened?** An automatic wake started a new run 30 to 60 seconds after a long successful run on the same task, on the same reused sandbox. The new run had to retire the previous run's warm session first. The retirement failed and the run failed before any provider work, with one of: - `Controller journal drain timed out; preserve the session before replacing its writer.` (during instruction preparation, before runtime selection, or in the executor); - `provider_transport_failed: runner did not durably suspend before checkpoint` (during instruction preparation); - `runner_state_identity_mismatch: prior_owner_terminal_state_indeterminate; retirement_refused=journal_tool_input_unanswered` (the previous run had parked on a question). The tasks rested `blocked` with a reconciliation hold or with nothing scheduled. One bounded retry reused the same sandbox and ended `execution_finalization_deadline_exceeded`, then its recovery refused with `allocation_ownership_ambiguous`. **Expected behavior** A run that did no provider work does not fail the task because its predecessor cannot be retired. The next attempt drops the reused sandbox and starts on a fresh one restored from the saved workspace. Unsaved work is never dropped: when the workspace or the session backup is not durably saved, the sandbox is kept and today's behavior applies. **Steps to reproduce** 1. Complete a warm native run on a Daytona sandbox. 2. Wake the task again so that the next run must retire the warm owner (configuration change, new session, changed agent files). 3. Make the owner's close fail (journal drain timeout, unconfirmed suspension). 4. The new run fails before provider work and the task is not continued. Refs #20844, #18373. ## What Changed - `native-runtime/predecessor-retirement.ts`: a typed pre-provider error `NativePredecessorRetirementUnprovenError` (`native_predecessor_retirement_unproven`) and the `replaceBeforeReuse` lease marker. - Native executor: every path that retires a predecessor for a new run (instruction-copy claim, instruction-directory reservation, session reset, configuration change) throws the typed error when the close fails. The owner stays registered for its own sandbox, so no run on that sandbox launches over it. A run on a different sandbox forgets that owner instead of replaying its cached rejected close. The executor does not settle this error as a provider failure. - A prior-owner fence that refuses a terminal owner on a resumed sandbox (`prior_owner_terminal_state_indeterminate`) also throws the typed error. - Retirement of a finished remote owner accepts an unanswered tool input when the owner's committed result is a governed-wait park (`response_wake` on a task interaction) and its Runner's sandbox lease ended elsewhere. - Heartbeat (`heartbeat/predecessor-retirement-fallback.ts`): on the typed error with no execution-start evidence and no result, mark this run's reusable lease on that sandbox `replaceBeforeReuse` and log `environment.lease_replacement_requested`. After the run ends, `failRun` hands the prepared workspace on only through the shared unchanged-files proof (`proveRemoteWorkspaceUnchanged`; a provisioning command or any runner command refuses it). With the proof it records `predecessorRetirementFallback`, closes the run's coordinator without a result and re-queues the run in the uncharged `interrupted_preparation` lane (native and legacy runtime modes); a run that answered a task interaction keeps its own wake in that uncharged lane, so the retry still carries the answer. Without the proof the workspace stays dirty, heartbeat runs today's failed-workspace preservation and no retry is scheduled. - Environment runtime: a marked lease is replaced instead of resumed, under the same rule as a failed resume (`reusableSandboxReplacementIsSafe`: run ended, clean workspace with a committed save, verified harness backup). The old lease goes to `pending_cleanup` for the sweep. Otherwise the sandbox is resumed as before. - Chaos: session fault SR1U, the SR1 variant where the retained owner cannot be retired. The server gets a test-only fault (`PAPERCLIP_TEST_WARM_RETIREMENT_FAULT=unconfirmed`, armed only when `NODE_ENV=test`). The oracle allows only the fallback failure and requires the succeeding follow-up on a different sandbox. - Docs: `doc/plugins/PLUGIN_RUNNER_EXECUTION.md`, chaos README. ## Verification - RED on master before this change (with #20844), then GREEN: - `native-session-executor.test.ts -t "predecessor cannot be retired"`: base fails with `Error: Controller journal drain timed out…` instead of the typed error. - `native-session-executor.test.ts -t "unretired predecessor"` (instruction preparation): same base failure. - `native-recovered-owner-followup.test.ts -t "unacknowledged"`: base fails with `runner_state_identity_mismatch: prior_owner_terminal_state_indeterminate; retirement_refused=journal_tool_input_unanswered`. - New contract tests: `heartbeat-native-predispatch-retry.test.ts` (claimed native run: lease marked, activity logged, uncharged `interrupted_preparation` retry, no recovery action, task not blocked, retry succeeds) and `environment-runtime-reusable-resume-replacement.test.ts` (a marked lease is replaced without a resume; with unsaved work or no verified backup it resumes as before), `remote-workspace-unchanged-release.test.ts` (an untouched workspace is handed on; a setup-written one stays dirty) and `retries.test.ts` (an answered interaction re-queued in the uncharged lane stays a resolved-interaction continuation with no failure retry spent). - Existing suites pass: the native executor, recovered-owner follow-up, instruction working copy, run completion, run failure cause and resume replacement test files. `pnpm exec vitest run --config tests/restart-chaos/vitest.config.ts question-handoff scheduler config` passes. Server and chaos harness `tsc --noEmit` pass. - Not run: a Daytona SR1U wave. It needs a runner image that matches this checkout. ## Risks - A sandbox marked for replacement is resumed when it cannot be replaced safely. That run can meet the same unretired owner again, fail again in the bounded lane, and then rest with Retry, as today. - The replacement session restores the latest verified harness backup. When the old Runner's final checkpoint was never saved, a same-session continuation resumes from that backup. - An unanswered tool input is accepted only for a committed governed-wait park whose Runner's sandbox lease ended on another sandbox. - Previous-release story: the marker and the run record are additive JSON. An older server ignores the marker and resumes the sandbox as before. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, agentic coding with tool use (shell, file edits, test runs) in Claude Code. ## 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 --- doc/plugins/PLUGIN_RUNNER_EXECUTION.md | 28 ++++ ...untime-reusable-resume-replacement.test.ts | 37 ++++++ ...heartbeat-native-predispatch-retry.test.ts | 61 ++++++++- server/src/services/environment-runtime.ts | 15 ++- server/src/services/heartbeat.ts | 15 ++- .../heartbeat/instruction-working-copy.ts | 2 +- .../predecessor-retirement-fallback.ts | 90 +++++++++++++ server/src/services/heartbeat/retries.test.ts | 24 +++- .../src/services/heartbeat/run-completion.ts | 66 +++++++++- server/src/services/native-runtime/index.ts | 1 + .../native-recovered-owner-followup.test.ts | 18 ++- .../native-session-executor.test.ts | 79 +++++++++++- .../native-runtime/native-session-executor.ts | 121 ++++++++++++++++-- .../native-runtime/predecessor-retirement.ts | 72 +++++++++++ ...remote-workspace-unchanged-release.test.ts | 25 ++++ tests/restart-chaos/README.md | 19 +++ tests/restart-chaos/config.ts | 3 + tests/restart-chaos/main.ts | 2 + tests/restart-chaos/observer.ts | 3 +- tests/restart-chaos/question-handoff.test.ts | 31 ++++- tests/restart-chaos/question-handoff.ts | 35 ++++- tests/restart-chaos/session-faults.ts | 24 +++- 22 files changed, 733 insertions(+), 38 deletions(-) create mode 100644 server/src/services/heartbeat/predecessor-retirement-fallback.ts create mode 100644 server/src/services/native-runtime/predecessor-retirement.ts diff --git a/doc/plugins/PLUGIN_RUNNER_EXECUTION.md b/doc/plugins/PLUGIN_RUNNER_EXECUTION.md index 027da7c0021..3199ca755e3 100644 --- a/doc/plugins/PLUGIN_RUNNER_EXECUTION.md +++ b/doc/plugins/PLUGIN_RUNNER_EXECUTION.md @@ -362,6 +362,34 @@ collection, another close error from an owner without a task, or continuation of the same session still blocks replacement. A controller restart is not required for this stopped-owner reset path. +When retiring the previous owner stays unproven anyway (any close failure, +on any of the paths a new run uses to retire it: instruction preparation, +configuration change, session reset, or a prior-owner fence on a resumed +sandbox), the new run has done no provider work. It fails with the typed +pre-provider error `native_predecessor_retirement_unproven` instead of a +provider failure. The owner stays registered for its own sandbox, so no run +on that sandbox launches over it. The heartbeat then: + +- marks this run's reusable lease on that sandbox `replaceBeforeReuse`, so the + next acquisition creates a fresh sandbox and hands the old one to the + cleanup sweep. That replacement uses the same rule as a failed resume: a + clean, committed workspace save and a verified harness backup. Without them + the next acquisition resumes the sandbox as before; +- after the run ends, hands its prepared workspace on at the saved version + only through the shared unchanged-files proof (no runner command, workspace + operation such as a provisioning command, execution event or result). + Without that proof the workspace stays dirty and is preserved as today, and + the run rests with Retry; +- re-queues the run in the uncharged `interrupted_preparation` lane instead of + a native reconciliation hold. A run that answered a task interaction keeps + its own wake in that lane, so the retry still carries the answer. + +A run on a different sandbox forgets the unretired owner instead of replaying +its rejected close. A previous run parked on a durable governed interaction +leaves its question's tool input unanswered by design. Once its Runner's +sandbox lease has ended elsewhere, that committed park settles the input for +retirement. + Core ends a dispatched task lease with `stop`, `status`, and `complete`. When that sequence confirms the stop and completes the same task, Core does not also call `onEnvironmentReleaseLease`. Core still calls it when the release did not diff --git a/server/src/__tests__/environment-runtime-reusable-resume-replacement.test.ts b/server/src/__tests__/environment-runtime-reusable-resume-replacement.test.ts index d4a802a8b29..08e89747566 100644 --- a/server/src/__tests__/environment-runtime-reusable-resume-replacement.test.ts +++ b/server/src/__tests__/environment-runtime-reusable-resume-replacement.test.ts @@ -250,6 +250,43 @@ describeEmbeddedPostgres("reusable sandbox resume failure replacement", () => { expect(acquired.lease.metadata?.sandboxLeaseAcquisition).toEqual({ outcome: "replacement", reason: "resume_failed" }); }); + // Staging: a run could not retire its predecessor's warm + // Runner on this sandbox, did no provider work, and asked for a fresh one. + async function markReplaceBeforeReuse(seeded: Awaited>) { + await environmentService(db).updateLeaseMetadata(seeded.lease.id, { ...seeded.lease.metadata, + replaceBeforeReuse: { schema: "paperclip.replace-before-reuse.v1", runId: randomUUID(), predecessorRunId: randomUUID(), + recordedAt: new Date().toISOString() } }); + } + + it("replaces a resumable sandbox whose previous Runner could not be retired, without resuming it", async () => { + const seeded = await seed(); + await markReplaceBeforeReuse(seeded); + const { call, runtime } = worker(seeded, async () => ({ providerLeaseId: seeded.providerLeaseId, + metadata: { remoteCwd: "/home/daytona/paperclip-workspace" } })); + const acquired = await acquire(seeded, runtime); + expect(acquired.lease.providerLeaseId).toBe("replacement-sandbox"); + expect(acquired.lease.metadata?.sandboxLeaseAcquisition).toEqual({ outcome: "replacement", reason: "resume_failed", + cause: "native_predecessor_retirement_unproven" }); + // The new sandbox restores the saved session from the verified backup. + expect(acquired.lease.metadata?.nativeHarnessBackup).toMatchObject({ authorizedProviderLeaseId: seeded.providerLeaseId }); + expect(call).not.toHaveBeenCalledWith(seeded.pluginId, "environmentResumeLease", expect.anything(), expect.anything()); + // The old sandbox, with the Runner on it, is kept for the cleanup sweep. + await expect(environmentService(db).getLeaseById(seeded.lease.id)).resolves.toMatchObject({ status: "pending_cleanup" }); + }); + + it.each([ + ["unsaved work on the sandbox", { dirty: true }], + ["no verified harness backup", { backupStamp: false }], + ] as Array<[string, Shape]>)("resumes a sandbox marked for replacement as before when it holds %s", async (_label, shape) => { + const seeded = await seed(shape); + await markReplaceBeforeReuse(seeded); + const { runtime } = worker(seeded, async () => ({ providerLeaseId: seeded.providerLeaseId, + metadata: { remoteCwd: "/home/daytona/paperclip-workspace" } })); + const acquired = await acquire(seeded, runtime); + expect(acquired.lease.providerLeaseId).toBe(seeded.providerLeaseId); + expect(acquired.lease.metadata?.sandboxLeaseAcquisition).toEqual({ outcome: "resumed" }); + }); + it("retries a sandbox state change inside the run and resumes the same sandbox", async () => { const seeded = await seed(); const { call, runtime } = worker(seeded, async (attempt) => { diff --git a/server/src/__tests__/heartbeat-native-predispatch-retry.test.ts b/server/src/__tests__/heartbeat-native-predispatch-retry.test.ts index 275a67ff316..bb42b3bf482 100644 --- a/server/src/__tests__/heartbeat-native-predispatch-retry.test.ts +++ b/server/src/__tests__/heartbeat-native-predispatch-retry.test.ts @@ -1,6 +1,8 @@ import { randomUUID } from "node:crypto"; import { and, eq } from "drizzle-orm"; -import { agents, authUsers, companyMemberships, createDb, heartbeatRuns, issueComments, issueRecoveryActions, issues } from "@paperclipai/db"; +import { activityLog, agents, authUsers, companyMemberships, createDb, environmentLeases, environments, heartbeatRuns, issueComments, + issueRecoveryActions, issues } from "@paperclipai/db"; +import { NativePredecessorRetirementUnprovenError } from "../services/native-runtime/predecessor-retirement.js"; import type { NativeRunIdentity, NativeSession, NativeSessionBackend, PrpEvent } from "@paperclipai/paperclip-runner"; import { describe, expect, it, vi } from "vitest"; import { heartbeatService, type HeartbeatServiceOptions } from "../services/heartbeat.js"; @@ -31,7 +33,8 @@ vi.mock("../services/budget-reservations.js", async importOriginal => { const support = await getRecoveryPostgresSupport({}); -function nativeBackend(db: ReturnType, options: { failDescriptorOnce?: { failed: boolean } } = {}): +function nativeBackend(db: ReturnType, options: { failDescriptorOnce?: { failed: boolean }; + unretiredPredecessorOnce?: { failed: boolean; environmentId: string } } = {}): NonNullable { return execution => { let identity: NativeRunIdentity; @@ -71,6 +74,19 @@ function nativeBackend(db: ReturnType, options: { failDescripto options.failDescriptorOnce.failed = true; throw Object.assign(new Error("could not serialize access due to concurrent update"), { name: "PostgresError", code: "40001" }); } + const unretired = options.unretiredPredecessorOnce; + if (unretired && !unretired.failed) { + // Staging: this run resumed the task's reused sandbox, where + // the previous run's warm Runner could not be retired before any + // provider work. The executor reports that after its coordinator claim. + unretired.failed = true; + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, execution.binding.runId)); + await db.insert(environmentLeases).values({ companyId: run!.companyId, environmentId: unretired.environmentId, + issueId: execution.binding.issueId, heartbeatRunId: run!.id, provider: "daytona", providerLeaseId: "sandbox-reused", + leasePolicy: "reuse_by_environment", status: "active", metadata: { remoteCwd: "/workspace" } }); + throw new NativePredecessorRetirementUnprovenError("previous-run", "sandbox-reused", + new Error("Controller journal drain timed out; preserve the session before replacing its writer.")); + } const [run] = await db.select({ runnerInstanceId: heartbeatRuns.runnerInstanceId }).from(heartbeatRuns) .where(eq(heartbeatRuns.id, execution.binding.runId)); if (!run?.runnerInstanceId) throw new Error("Normal native admission did not persist a runner identity"); @@ -147,6 +163,47 @@ describe.skipIf(!support.supported)("heartbeat native pre-dispatch failure retry } }, 90_000); + it("re-queues a run whose predecessor could not be retired onto a fresh sandbox without a Retry", async () => { + const { companyId } = fixture.current; + const db = createDb(fixture.current.temporary.connectionString, { maxConnections: 4 }); + const [environment] = await db.insert(environments).values({ name: `reused-${randomUUID()}`, driver: "sandbox" }).returning(); + const heartbeat = heartbeatService(db, { nativeSessionBackendFactory: nativeBackend(db, + { unretiredPredecessorOnce: { failed: false, environmentId: environment!.id } }) }); + try { + const { issueId, runId } = await startTask(db, heartbeat); + const [failed] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(failed).toMatchObject({ status: "failed", runtimeMode: "native", errorCode: "adapter_failed", + resultJson: expect.objectContaining({ failureCause: "native_predecessor_retirement_unproven", + executionRecovery: { kind: "bootstrap", providerWorkStarted: false }, + predecessorRetirementFallback: expect.objectContaining({ version: 1, providerWorkStarted: false, + predecessorRunId: "previous-run", replacedProviderLeaseIds: ["sandbox-reused"] }) }) }); + // The reused sandbox is replaced at the next acquisition, not resumed. + const [lease] = await db.select().from(environmentLeases).where(and(eq(environmentLeases.heartbeatRunId, runId), + eq(environmentLeases.providerLeaseId, "sandbox-reused"))); + expect(lease?.metadata).toMatchObject({ replaceBeforeReuse: { schema: "paperclip.replace-before-reuse.v1", runId, + predecessorRunId: "previous-run" } }); + expect(await db.select().from(activityLog).where(and(eq(activityLog.runId, runId), + eq(activityLog.action, "environment.lease_replacement_requested")))).toHaveLength(1); + const successors = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), + eq(heartbeatRuns.retryOfRunId, runId))); + expect(successors).toEqual([expect.objectContaining({ scheduledRetryReason: "interrupted_preparation", scheduledRetryAttempt: 1 })]); + expect(successors[0]!.contextSnapshot?.executionRetryAccounting).toMatchObject({ failureRetries: 0 }); + expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]?.status).not.toBe("blocked"); + expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId))).toHaveLength(0); + + expect(await heartbeat.promoteDueScheduledRetries()).toMatchObject({ promoted: 1 }); + await heartbeat.resumeQueuedRuns(); + await waitForCondition("the retry to succeed", async () => + (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, successors[0]!.id)))[0]?.status === "succeeded"); + await waitForCondition("the retry to settle", () => heartbeat.getTaskDrainStatus().quiescent); + expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId))).toHaveLength(0); + } finally { + await heartbeat.drainActiveRunExecutions(); + await closeIdleWarmNativeSessionsForRestart(); + await db.$client.end(); + } + }, 90_000); + it("keeps the hold when the failure follows entry into the native executor", async () => { const { companyId } = fixture.current; const db = createDb(fixture.current.temporary.connectionString, { maxConnections: 4 }); diff --git a/server/src/services/environment-runtime.ts b/server/src/services/environment-runtime.ts index 49634c140c3..8252eebfb1f 100644 --- a/server/src/services/environment-runtime.ts +++ b/server/src/services/environment-runtime.ts @@ -3,6 +3,7 @@ import { ENVIRONMENT_LEASE_CONTROLLER_KEY } from "./environment-lease-controller import { RetainedSandboxAbsentError, resumeReplyConfirmsAbsence } from "./retained-sandbox-absent-error.js"; import { readNativeWorkspaceMigration } from "./native-runtime/native-workspace-migration.js"; import { ReusableSandboxResumeError } from "./reusable-sandbox-resume-error.js"; +import { NATIVE_PREDECESSOR_RETIREMENT_UNPROVEN_CODE, readReplaceBeforeReuseMarker } from "./native-runtime/predecessor-retirement.js"; import { REUSABLE_SANDBOX_RESUME_BUDGET_MS, retireReplacedReusableSandboxLease, @@ -1806,6 +1807,7 @@ function createSandboxEnvironmentDriver( : null; let providerLease: PluginEnvironmentLease | null = null; + let replacingUnretiredOwner = false; let replacementReason: | "not_found" | "expired" @@ -1831,7 +1833,17 @@ function createSandboxEnvironmentDriver( providerLeaseId: reusableLease.providerLeaseId, }); } - try { + // A run that could not retire its predecessor's Runner on this + // sandbox asked for a fresh one. Replace it under the same safety + // rule as a failed resume; otherwise resume it as before. + replacingUnretiredOwner = readReplaceBeforeReuseMarker(reusableLease.metadata) !== null + && await reusableSandboxReplacementIsSafe({ + db, lease: reusableLease, companyId: input.companyId, heartbeatRunId: input.heartbeatRunId, + executionWorkspaceId: input.executionWorkspaceId, adapterType: input.adapterType, + cause: new Error(NATIVE_PREDECESSOR_RETIREMENT_UNPROVEN_CODE), + }); + if (replacingUnretiredOwner) replacementReason = "resume_failed"; + else try { // One run spends a bounded budget resuming, retries included; the // provider's own start deadline (five minutes on Daytona) is not it. const configuredResumeTimeoutMs = Math.min( @@ -2023,6 +2035,7 @@ function createSandboxEnvironmentDriver( ? { outcome: "replacement", reason: replacementReason ?? "resume_failed", + ...(replacingUnretiredOwner ? { cause: NATIVE_PREDECESSOR_RETIREMENT_UNPROVEN_CODE } : {}), } : { outcome: "created", diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index c36a4eb7871..954104fe5fb 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -43,6 +43,7 @@ import { dotRunnerBroker } from "./dot-runner-broker.js"; import { withRunExecutionTiming, measureRunPhase, measureWorkspaceSyncPhase, isWorkspaceSyncDetailPhase } from "./execution-preparation-timing.js"; import { createHeartbeatPreparationTiming } from "./heartbeat/preparation-timing.js"; import { createHeartbeatInstructionCopyRelease, createHeartbeatInstructionWorkingCopy } from "./heartbeat/instruction-working-copy.js"; +import { preparePredecessorRetirementFallback } from "./heartbeat/predecessor-retirement-fallback.js"; import { prepareHeartbeatRuntimeServiceIntents, startHeartbeatRuntimeServices, recordHeartbeatAdapterRuntimeServices } from "./heartbeat/runtime-services.js"; import { bindHeartbeatRunnerHomeMode, prepareHeartbeatExecutionConfiguration } from "./heartbeat/execution-configuration.js"; import { createRunLogWriterAuthority } from "./heartbeat/run-log-authority.js"; @@ -3846,7 +3847,13 @@ export function heartbeatService( return; } if (await leaveToNextController(err)) return; - if (!(await preserveNativeWorkspaceOnFailure())) { + // An unretired predecessor on a reused sandbox: no provider work ran, + // so the next attempt starts on a fresh sandbox restored from the save. + const predecessorRetirementFallback = await preparePredecessorRetirementFallback(db, run, err).catch(error => { + logger.warn({ err: error, runId: run.id }, "could not prepare a fresh sandbox for the next attempt; keeping the failed workspace"); + return null; + }); + if (!predecessorRetirementFallback && !(await preserveNativeWorkspaceOnFailure())) { const claim = runOptions.nativeRestartRecovery; let releaseFailed = false; restartClaimLapsed = claim !== undefined && await releaseLapsedNativeRestartClaim({ db, companyId: run.companyId, runId: run.id, @@ -3863,15 +3870,17 @@ export function heartbeatService( : "native run failure left to the workspace owner that holds the run"); return; } - await runCompletion.failRun({ + const failed = await runCompletion.failRun({ run, agent, issueId, issueRef, signal: executionControl.controller.signal, output: runOutput, session: { runtimeForAdapter, previousSessionParams, taskKey, configuredModel, sessionConfigMetadata }, readFailureReportSecrets, runId, err, identityRedactor, requiredWorkspaceRestoreEvidence, legacyAdapterEntered, nativeDispatchMayHaveStarted: nativeDispatchMayHaveStarted(), - goalCheckpointSession, previousSessionDisplayId, taskSession, + goalCheckpointSession, previousSessionDisplayId, taskSession, predecessorRetirementFallback, }); + // The failed run's workspace could not be proven unchanged: keep it as today. + if (failed?.preserveFailedWorkspace) await preserveNativeWorkspaceOnFailure(); } } catch (outerErr) { if (nativeStartupCleanupScheduled || nativeStartupCleanupError || outerErr instanceof NativeStartupCleanupPendingError) { diff --git a/server/src/services/heartbeat/instruction-working-copy.ts b/server/src/services/heartbeat/instruction-working-copy.ts index f57dbb449bb..d9a98f6393b 100644 --- a/server/src/services/heartbeat/instruction-working-copy.ts +++ b/server/src/services/heartbeat/instruction-working-copy.ts @@ -156,7 +156,7 @@ export function createHeartbeatInstructionWorkingCopy(input: InstructionWorkingC observabilityCompatibilityKey: input.observabilityCompatibilityKey, priorExecution: parseNativeExecutionInput(priorFileInput), companyId: agent.companyId, agentId: agent.id, executionWorkspaceId: persistedExecutionWorkspace?.id ?? readRun().id, workspace: executionWorkspace, - environmentId: executionTarget?.environmentId ?? null, runId: readRun().id, preparationKey: instructionPreparationKey, forceRetirement: !taskSessionForRun, + environmentId: executionTarget?.environmentId ?? null, target: executionTarget, runId: readRun().id, preparationKey: instructionPreparationKey, forceRetirement: !taskSessionForRun, adopt: async previousRunId => { instructionCopy = await instructionCopies.adopt({ companyId: agent.companyId, agentId: agent.id, runId: readRun().id, previousRunId, target: executionTarget, cwd: executionWorkspace.cwd, allowRetirementHandoff: true }); diff --git a/server/src/services/heartbeat/predecessor-retirement-fallback.ts b/server/src/services/heartbeat/predecessor-retirement-fallback.ts new file mode 100644 index 00000000000..b9b91955888 --- /dev/null +++ b/server/src/services/heartbeat/predecessor-retirement-fallback.ts @@ -0,0 +1,90 @@ +import { and, eq, isNotNull, sql } from "drizzle-orm"; +import { environmentLeases, executionWorkspaces, heartbeatRuns, nativeRunResults, type Db } from "@paperclipai/db"; +import { readRemoteWorkspaceAuthority, remoteWorkspaceRunReferenceSchema } from "@paperclipai/shared"; +import { persistActivity } from "../activity-log.js"; +import { hasNativeExecutionStartEvidence } from "../native-runtime/native-restart-recovery.js"; +import { + findNativePredecessorRetirementUnproven, REPLACE_BEFORE_REUSE_KEY, REPLACE_BEFORE_REUSE_SCHEMA, + type PredecessorRetirementFallback, type ReplaceBeforeReuseMarker, +} from "../native-runtime/predecessor-retirement.js"; +import { releaseUnchangedRemoteWorkspaceWriter } from "../remote-workspaces.js"; + +type Run = Pick; + +/** + * A run failed before provider work because the previous run's warm owner on + * its reused sandbox could not be retired. Mark each reusable lease this run + * holds on that sandbox, so the next acquisition takes the existing + * replacement path instead of resuming it. That path still requires a clean, + * committed workspace save and a verified harness backup; otherwise the next + * acquisition resumes the sandbox as before. Nothing here touches the + * workspace: `releaseUnchangedFallbackWorkspace` settles it once the run ended. + * + * Returns null, changing nothing, when this run may have started provider + * work or holds no reusable lease on that sandbox. The run then keeps today's + * preservation and its Retry. + */ +export async function preparePredecessorRetirementFallback(db: Db, run: Run, error: unknown) + : Promise { + const failure = findNativePredecessorRetirementUnproven(error); + if (!failure) return null; + if (await hasNativeExecutionStartEvidence(db, { companyId: run.companyId, id: run.id })) return null; + const [result] = await db.select({ id: nativeRunResults.id }).from(nativeRunResults) + .where(and(eq(nativeRunResults.companyId, run.companyId), eq(nativeRunResults.runId, run.id))).limit(1); + if (result) return null; + return db.transaction(async tx => { + const [current] = await tx.select().from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, run.companyId), eq(heartbeatRuns.id, run.id))).for("update"); + // The native executor may already have settled the run as a terminal failure. + if (!current || !["running", "failed"].includes(current.status) || current.runnerProfileJson?.nativeWorkspaceSync != null) return null; + const leases = (await tx.select().from(environmentLeases).where(and( + eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id), + eq(environmentLeases.leasePolicy, "reuse_by_environment"), isNotNull(environmentLeases.providerLeaseId), + )).for("update")).filter(lease => !failure.providerLeaseId || lease.providerLeaseId === failure.providerLeaseId); + if (leases.length === 0) return null; + const marker: ReplaceBeforeReuseMarker = { schema: REPLACE_BEFORE_REUSE_SCHEMA, runId: run.id, + predecessorRunId: failure.predecessorRunId, recordedAt: new Date().toISOString() }; + for (const lease of leases) { + await tx.update(environmentLeases).set({ + metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) || ${JSON.stringify({ [REPLACE_BEFORE_REUSE_KEY]: marker })}::jsonb`, + updatedAt: new Date(), + }).where(and(eq(environmentLeases.id, lease.id), eq(environmentLeases.companyId, run.companyId))); + } + const replacedProviderLeaseIds = leases.map(lease => lease.providerLeaseId!); + await persistActivity(tx as unknown as Db, { companyId: run.companyId, actorType: "system", actorId: "native-runtime", + action: "environment.lease_replacement_requested", entityType: "heartbeat_run", entityId: run.id, runId: run.id, + details: { reason: failure.code, predecessorRunId: failure.predecessorRunId, providerLeaseIds: replacedProviderLeaseIds } }); + return { version: 1 as const, providerWorkStarted: false as const, predecessorRunId: failure.predecessorRunId, + replacedProviderLeaseIds }; + }); +} + +/** + * After the failed run ended: hand its prepared remote workspace on at the + * saved version, but only through the shared unchanged-files proof (no runner + * command, workspace operation such as a provisioning command, execution event + * or result recorded). True when nothing of this run's is left to save. False + * keeps the workspace dirty, so the caller preserves it as today and the + * marked sandbox is never replaced. + */ +export async function releaseUnchangedFallbackWorkspace(db: Db, run: Run): Promise { + const [current] = await db.select({ profile: heartbeatRuns.runnerProfileJson }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, run.companyId), eq(heartbeatRuns.id, run.id))); + if (!current || current.profile?.nativeWorkspaceSync != null) return false; + if (current.profile?.remoteWorkspace == null) return true; + const reference = remoteWorkspaceRunReferenceSchema.safeParse(current.profile.remoteWorkspace); + if (!reference.success) return false; + if (reference.data.state !== "prepared") return true; + return db.transaction(async tx => { + const [workspace] = await tx.select().from(executionWorkspaces).where(and( + eq(executionWorkspaces.companyId, run.companyId), eq(executionWorkspaces.id, reference.data.workspaceId))).for("update"); + let authority: ReturnType; + try { authority = readRemoteWorkspaceAuthority(workspace?.metadata); } catch { return false; } + if (!workspace || !authority) return false; + // Another writer took the workspace on, so another run already continues + // the task. Do not queue a second attempt beside it. + if (authority.writerRunId !== run.id) return false; + // The heartbeat that owns this writer is the caller, and it started no runner. + return Boolean(await releaseUnchangedRemoteWorkspaceWriter(tx, { workspace, authority, callerOwnsWriter: true })); + }); +} diff --git a/server/src/services/heartbeat/retries.test.ts b/server/src/services/heartbeat/retries.test.ts index cd94dbfe9d8..b12e2f0374d 100644 --- a/server/src/services/heartbeat/retries.test.ts +++ b/server/src/services/heartbeat/retries.test.ts @@ -238,8 +238,7 @@ describe("heartbeat retry module callbacks", () => { await extracted.createHeartbeatRetries(database.db, spawnDeps) .scheduleInteractionContinuationInfrastructureRetryIfEligible(spawnFailure, { adapterType: "codex_local" } as Agent); expect(spawnDeps.appendRunEvent).toHaveBeenCalledWith(spawnFailure, exhaustion); - expect(database.access).not.toHaveBeenCalled(); - }); + expect(database.access).not.toHaveBeenCalled(); }); }); import { resolveExternalTestDatabaseUrl } from "../../__tests__/helpers/external-test-database.js"; @@ -331,6 +330,27 @@ describePostgres("heartbeat retry module database wiring", () => { } }); + // A run that could not retire its predecessor re-queues in the uncharged lane + // with the answered interaction's own wake, so the retry still carries it. + it("keeps an answered interaction in an uncharged interrupted-preparation retry that keeps its wake", async () => { + const { run, agent, companyId } = await fixture(); + const [wake] = await db.insert(agentWakeupRequests).values({ companyId, agentId: agent.id, + runId: run.id, source: "automation", status: "failed" }).returning(); + const contextSnapshot = { ...run.contextSnapshot, interactionId: randomUUID(), interactionStatus: "answered", + interactionKind: "ask_user_questions", mutation: "interaction", wakeReason: "issue_commented" }; + const [failed] = await db.update(heartbeatRuns).set({ wakeupRequestId: wake!.id, runtimeMode: "native", + errorCode: "adapter_failed", contextSnapshot }).where(eq(heartbeatRuns.id, run.id)).returning(); + const { retries } = boundRetries(); + expect(isResolvedInteractionContinuationWakeContext(failed!.contextSnapshot)).toBe(true); + const scheduled = await retries.scheduleBoundedRetryForRun(failed!, agent, + { now, retryReason: "interrupted_preparation", wakeReason: "issue_commented" }); + expect(scheduled.outcome).toBe("scheduled"); + const [successor] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, run.id)); + expect(isResolvedInteractionContinuationWakeContext(successor!.contextSnapshot)).toBe(true); + expect(successor!.contextSnapshot).toMatchObject({ interactionId: contextSnapshot.interactionId, + retryReason: "interrupted_preparation", executionRetryAccounting: { failureRetries: 0 } }); + }); + it("bounds answered chat attestation retries across restarts and escalates their exhaustion", async () => { const { run, agent, companyId } = await fixture(); const [wake] = await db.insert(agentWakeupRequests).values({ companyId, agentId: agent.id, diff --git a/server/src/services/heartbeat/run-completion.ts b/server/src/services/heartbeat/run-completion.ts index 08a95dc55a5..70729ade8ec 100644 --- a/server/src/services/heartbeat/run-completion.ts +++ b/server/src/services/heartbeat/run-completion.ts @@ -4,6 +4,8 @@ import { providerFailureFromError } from "../../vendor/paperclip-runner/index.js import { GENERIC_RUN_FAILURE_CODES, NATIVE_PRE_DISPATCH_FAILURE_CODE, NATIVE_PRE_DISPATCH_FAILURE_KEY, NATIVE_PRE_DISPATCH_FAILURE_RECORD, failureCauseFromAdapterResult, failureCauseFromError, isNativePreDispatchTransientFailure } from "./run-failure-cause.js"; import { INTERRUPTED_PREPARATION_RETRY_REASON } from "../execution-recovery-attempt.js"; +import { PREDECESSOR_RETIREMENT_FALLBACK_KEY, readPredecessorRetirementFallback, type PredecessorRetirementFallback } from "../native-runtime/predecessor-retirement.js"; +import { releaseUnchangedFallbackWorkspace } from "./predecessor-retirement-fallback.js"; import { hasNativeExecutionStartEvidence } from "../native-runtime/native-restart-recovery.js"; import { withoutSqlStatementText } from "@paperclipai/shared"; import { nativeTaskSessionPublicationHandled } from "../native-runtime/native-task-session-publication.js"; @@ -164,6 +166,8 @@ export interface FailHeartbeatRunInput extends RunCompletionInput { goalCheckpointSession: { current: { params: Record; displayId: string } | null }; previousSessionDisplayId: string | null; taskSession: TaskSession; + /** Set when the run failed on an unretired predecessor and its next attempt was prepared for a fresh sandbox. */ + predecessorRetirementFallback?: PredecessorRetirementFallback | null; } export interface FailHeartbeatRunSetupInput { @@ -1189,15 +1193,61 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC }); } - async function failRun(input: FailHeartbeatRunInput) { + /** + * A run that failed only because its predecessor on the reused sandbox could + * not be retired did no provider work, and its next attempt starts on a fresh + * sandbox. It re-queues itself in the uncharged interrupted-preparation lane, + * like a transient pre-dispatch fault, whatever its runtime mode. An answered + * interaction keeps its response through its own continuation retry. Its own + * coordinator, claimed or not, ends without a result: nothing ran under it. + */ + async function schedulePredecessorRetirementFallbackRetry(run: Run, agent: Agent, fallback: PredecessorRetirementFallback | null | undefined) { + if (!fallback || run.status !== "failed") return null; + // Files this run's setup may have written are never dropped: without the + // shared unchanged-files proof the workspace stays dirty and preserved. + const released = await releaseUnchangedFallbackWorkspace(db, run).catch((error) => { + logger.warn({ err: error, runId: run.id }, "could not prove the failed run left its workspace unchanged"); + return false; + }); + if (!released) return { outcome: "workspace_preservation_required" as const }; + try { + // Recorded only once the workspace is settled: it makes the run eligible for retry. + if (!readPredecessorRetirementFallback(run.resultJson)) { + const record = { [PREDECESSOR_RETIREMENT_FALLBACK_KEY]: fallback, executionRecovery: { kind: "bootstrap", providerWorkStarted: false } }; + await db.update(heartbeatRuns).set({ resultJson: sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) || ${JSON.stringify(record)}::jsonb` }) + .where(and(eq(heartbeatRuns.companyId, run.companyId), eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.status, "failed"))); + run = { ...run, resultJson: { ...parseObject(run.resultJson), ...record } }; + } + await db.update(nativeRunFinalizations).set({ phase: "terminal_failure", failureCode: NATIVE_PRE_DISPATCH_FAILURE_CODE, + leaseOwner: null, leaseExpiresAt: null, nextAttemptAt: null, updatedAt: new Date() }) + .where(and(eq(nativeRunFinalizations.companyId, run.companyId), eq(nativeRunFinalizations.runId, run.id), + isNull(nativeRunFinalizations.resultId), inArray(nativeRunFinalizations.phase, ["observed", "retryable_failure", "terminal_failure"]))); + } catch (error) { + logger.warn({ err: error, runId: run.id }, "could not close the native coordinator of a run that did no provider work"); + return null; + } + // An answered interaction keeps its own wake, so the retry still carries + // the answer as a resolved-interaction continuation, in the uncharged lane. + const wakeReason = isResolvedInteractionContinuationWakeContext(run.contextSnapshot) + ? readNonEmptyString(parseObject(run.contextSnapshot).wakeReason) : null; + return scheduleBoundedRetryForRun(run, agent, { retryReason: INTERRUPTED_PREPARATION_RETRY_REASON, + ...(wakeReason ? { wakeReason } : {}) }).catch((retryError) => { + logger.warn({ err: retryError, runId: run.id }, "failed to re-queue a run whose predecessor could not be retired"); + return null; + }); + } + + async function failRun(input: FailHeartbeatRunInput): Promise<{ preserveFailedWorkspace: true } | undefined> { const { run, agent, issueId, issueRef, signal, output, session, readFailureReportSecrets, runId, err, identityRedactor, requiredWorkspaceRestoreEvidence, - legacyAdapterEntered, nativeDispatchMayHaveStarted, goalCheckpointSession, previousSessionDisplayId, taskSession } = input; + legacyAdapterEntered, nativeDispatchMayHaveStarted, goalCheckpointSession, previousSessionDisplayId, taskSession, + predecessorRetirementFallback } = input; const { runtimeForAdapter, previousSessionParams, taskKey, configuredModel, sessionConfigMetadata } = session; const { handle, outputProgressState, flushOutputProgress } = output; // A process adapter may throw while its owned Stop is joining the // child. Let the cancellation write settle before attempting failure. await processRunCancellationSettlements.get(run.id)?.settled; const providerFailure = providerFailureFromError(err); + let preserveFailedWorkspace = false; const currentUserRedactionOptions = await getCurrentUserRedactionOptions(); const redactFailureText = (text: string) => redactCurrentUserText(identityRedactor.redact(text), currentUserRedactionOptions); @@ -1417,9 +1467,16 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC return null; }) : null; - const nativePreDispatchRetry = storageWait === null ? await scheduleNativePreDispatchRetry(livenessRun, agent) : null; + const nativePreDispatchRetry = storageWait !== null ? null + : !stoppedDuringFailure && predecessorRetirementFallback + ? await schedulePredecessorRetirementFallbackRetry(livenessRun, agent, predecessorRetirementFallback) + : await scheduleNativePreDispatchRetry(livenessRun, agent); + // The workspace may hold this run's setup files: the caller preserves it as today. + preserveFailedWorkspace = nativePreDispatchRetry?.outcome === "workspace_preservation_required"; let fallbackRetry: { outcome: string } | null | undefined = nativePreDispatchRetry; - if (storageWait?.outcome !== "scheduled" && storageWait?.outcome !== "retry_exhausted" && nativePreDispatchRetry === null) { + // The predecessor fallback already asked the interaction continuation retry once. + if (storageWait?.outcome !== "scheduled" && storageWait?.outcome !== "retry_exhausted" && nativePreDispatchRetry === null + && !(predecessorRetirementFallback && !stoppedDuringFailure)) { fallbackRetry = await scheduleInteractionContinuationInfrastructureRetryIfEligible( livenessRun, agent, @@ -1486,6 +1543,7 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC logger.warn({ err: error, runId: run.id }, "interrupted native turn Retry request failed"); }); } + return preserveFailedWorkspace ? { preserveFailedWorkspace: true } : undefined; } /** diff --git a/server/src/services/native-runtime/index.ts b/server/src/services/native-runtime/index.ts index 643e18b9a92..df074628dbe 100644 --- a/server/src/services/native-runtime/index.ts +++ b/server/src/services/native-runtime/index.ts @@ -11,3 +11,4 @@ export * from "./native-finalization-reconciler.js"; export * from "./native-restart-recovery.js"; export * from "./native-workspace-sync.js"; export * from "./status-arbiter.js"; +export * from "./predecessor-retirement.js"; diff --git a/server/src/services/native-runtime/native-recovered-owner-followup.test.ts b/server/src/services/native-runtime/native-recovered-owner-followup.test.ts index 15562311197..e42f3046ef7 100644 --- a/server/src/services/native-runtime/native-recovered-owner-followup.test.ts +++ b/server/src/services/native-runtime/native-recovered-owner-followup.test.ts @@ -94,7 +94,7 @@ describe.skipIf(!recoveryPostgresSupport.supported)("follow-up after a recovered | "failed-turn-start" | "rejected-turn-start" | "indeterminate-turn-start" | "unknown-outcome-turn-start" | "unsuperseded-unknown-outcome-turn-start" | "failed-suspend" | "pending-attach" | "pending-tool-result" = "settled", options: { controller?: { bootId: string; pid: number; processStartedAt: Date }; provider?: "codex" | "acpx" | "opencode"; - lifecycle?: "warm" } = {}) { + lifecycle?: "warm"; governedWait?: boolean } = {}) { const issueId = randomUUID(), workspaceId = randomUUID(), runId = randomUUID(); await db.insert(issues).values({ id: issueId, companyId, title: "Continue after recovery", assigneeAgentId: agentId, status: "in_progress" }); const [row] = await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", runtimeMode: "native", @@ -174,7 +174,10 @@ describe.skipIf(!recoveryPostgresSupport.supported)("follow-up after a recovered const [prepared] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); const [result] = await db.insert(nativeRunResults).values({ companyId, issueId, runId, completionContractId: prepared.completionContractId!, serverFingerprint: "fixture", schemaStatus: "accepted", - resultJson: {}, canonicalSha256: "fixture" }).returning(); + // A turn parked on a request_human_input question commits this governed-wait result. + resultJson: options.governedWait ? { continuation: { kind: "response_wake", idempotencyKey: "interaction-response:question" }, + artifacts: [{ kind: "issue_thread_interaction", ref: `interaction:${randomUUID()}` }] } : {}, + canonicalSha256: "fixture" }).returning(); await db.update(nativeRunFinalizations).set({ phase: "committed", resultId: result.id, leaseOwner: null, leaseExpiresAt: null }) .where(eq(nativeRunFinalizations.runId, runId)); await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date(), runnerProfileJson: { @@ -784,9 +787,16 @@ describe.skipIf(!recoveryPostgresSupport.supported)("follow-up after a recovered outcome: stranded("journal_commands_unsettled(semantic_tool.result.pending)") }, { control: "unanswered-tool", label: "ended on another sandbox", status: "expired", sameSandbox: false, recorded: true, outcome: stranded("journal_tool_input_unanswered") }, + // Staging: the owner parked on a durable question, so that + // question's tool input is unanswered by design. Its Runner is gone. + { control: "unanswered-tool", governedWait: true, label: "ended on another sandbox after a governed-wait park", + status: "expired", sameSandbox: false, recorded: true, outcome: ADMITTED }, + { control: "unanswered-tool", governedWait: true, label: "ended on this sandbox after a governed-wait park", + status: "expired", sameSandbox: true, recorded: true, outcome: stranded("journal_tool_input_unanswered") }, ] as const)("retires a finished remote owner with an unacknowledged $control when its sandbox lease $label", - async ({ control, status, sameSandbox, recorded, outcome }) => { - const prior = await seedRecoveredPriorRun(control, { provider: "opencode" }); + async ({ control, status, sameSandbox, recorded, outcome, ...rest }) => { + const governedWait = "governedWait" in rest && rest.governedWait === true; + const prior = await seedRecoveredPriorRun(control, { provider: "opencode", governedWait }); const followUp = await admitFollowUp(prior); if (recorded) { await db.insert(environments).values({ id: followUp.environmentId, name: `ended-${followUp.environmentId}`, driver: "sandbox" }); diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index c5f40043e9c..f0835396b15 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -10819,6 +10819,47 @@ describe("native warm session supervision", () => { } }); + // Staging: instruction preparation retires the previous + // run's warm owner before runtime selection. Its close failed, and the run + // failed with no provider work and no way back. + it("instruction preparation reports an unretired predecessor and a fresh sandbox skips it", async () => { + const identity = "warm-instruction-unretirable"; + const warmExecution = { ...execution, binding: { ...execution.binding, runId: identity, executionWorkspaceId: `${identity}-workspace` }, + session: { ...execution.session, normalizedSessionId: identity, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 } }, + } as NativeExecutionInputV1; + const drain = new Error("Controller journal drain timed out; preserve the session before replacing its writer."); + let closing: Promise | undefined; + const close = vi.fn(() => closing ??= Promise.reject(drain)); + state.execute.mockReset().mockImplementationOnce(async (options) => { + await options.onSession?.({ close }); + return { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" }, + turnId: identity, normalizedSessionId: identity, providerSessionId: identity, + driverKind: "test", driverVersion: "1", nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null }; + }); + const copy = (runId: string) => ({ runId, root: `/tmp/${identity}`, preparationKey: "before", hasChanges: async () => false, + collectStopped: async () => undefined }); + const target = (providerLeaseId: string, outcome: "created" | "resumed" | "replacement") => ({ kind: "remote" as const, + transport: "sandbox" as const, environmentId: identity, remoteCwd: `/tmp/${identity}`, sandboxLeaseAcquisition: { outcome, providerLeaseId } }); + const claim = (runId: string, claimTarget: ReturnType) => claimWarmNativeInstructionCopy({ priorExecution: warmExecution, + companyId: warmExecution.binding.companyId, agentId: warmExecution.binding.agentId, + executionWorkspaceId: warmExecution.binding.executionWorkspaceId, workspace: warmExecution.workspace, + environmentId: identity, target: claimTarget, runId, preparationKey: "changed", adopt: async () => copy(runId) }); + try { + await executePaperclipNativeSession({ db: leaseDb(warmExecution), execution: warmExecution, runnerInstanceId: identity, + runnerExecutionTarget: target("sandbox-a", "created"), instructionWorkingCopy: copy(identity) }); + await expect(claim(`${identity}-reused`, target("sandbox-a", "resumed"))) + .rejects.toMatchObject({ code: "native_predecessor_retirement_unproven", predecessorRunId: identity, providerLeaseId: "sandbox-a" }); + const closes = close.mock.calls.length; + expect(closes).toBeGreaterThan(0); + // The retry on a fresh sandbox prepares normally; the old owner stays with its sandbox. + expect(await claim(`${identity}-fresh`, target("sandbox-b", "replacement"))).toBeNull(); + expect(close).toHaveBeenCalledTimes(closes); + } finally { + close.mockImplementation(async () => undefined); + await closeWarmNativeSessionsForEnvironment({ environmentId: identity, reason: "test cleanup" }).catch(() => undefined); + } + }); + it.each(["idle", "edit", "add", "remove", "projectless"])("retains the actual agent_files copy across warm turns, then retires for %s", async ending => { const root = await realpath(await mkdtemp(join(tmpdir(), "warm-agent-files-"))); const localRoot = join(root, "run", "live"); @@ -12015,6 +12056,41 @@ describe("native warm session supervision", () => { expect(state.execute).toHaveBeenCalledTimes(2); }); + // Staging: the follow-up on the reused sandbox failed + // before provider work because the previous controller's journal drain + // outlived the close grace. Nothing could ever start the task again. + it("sends the follow-up to a fresh sandbox when its predecessor cannot be retired", async () => { + const { base, next } = fixture("identity-unretirable"); + const drain = new Error("Controller journal drain timed out; preserve the session before replacing its writer."); + let closing: Promise | undefined; + const close = vi.fn(() => closing ??= Promise.reject(drain)); + state.execute.mockReset().mockImplementationOnce(async options => { + options.onSession?.({ close }); return result; + }).mockResolvedValue(result); + const target = (providerLeaseId: string, outcome: "created" | "resumed" | "replacement") => ({ + kind: "remote" as const, transport: "sandbox" as const, environmentId: "identity-unretirable", + remoteCwd: "/tmp/identity-unretirable", sandboxLeaseAcquisition: { outcome, providerLeaseId } }); + const run = (input: NativeExecutionInputV1, runId: string, runnerExecutionTarget: ReturnType) => { + const execution = { ...input, binding: { ...input.binding, runId } }; + return executePaperclipNativeSession({ db: leaseDb(execution), execution, runnerInstanceId: "runner", runnerExecutionTarget }); + }; + await run(base, base.binding.runId, target("sandbox-a", "created")); + const failure = await run(next, `${next.binding.runId}-reused`, target("sandbox-a", "resumed")).catch(error => error); + expect(failure).toMatchObject({ code: "native_predecessor_retirement_unproven", + predecessorRunId: base.binding.runId, providerLeaseId: "sandbox-a" }); + expect(String(failure.message)).toContain(drain.message); + // The same sandbox still holds that Runner: never launch over it. + await expect(run(next, `${next.binding.runId}-same-sandbox`, target("sandbox-a", "resumed"))) + .rejects.toMatchObject({ code: "native_predecessor_retirement_unproven" }); + expect(state.execute).toHaveBeenCalledTimes(1); + const closes = close.mock.calls.length; + // A fresh sandbox cannot meet it. The retry starts without replaying the rejected close. + await run(next, `${next.binding.runId}-fresh`, target("sandbox-b", "replacement")); + expect(state.execute).toHaveBeenCalledTimes(2); + expect(state.execute.mock.calls.at(-1)?.[0].existingSession).toBeUndefined(); + expect(close).toHaveBeenCalledTimes(closes); + }); + it.each(["companyId", "agentId", "issueId", "executionWorkspaceId"] as const)( "does not retire an unrelated %s owner", async field => { const { base, next, run } = fixture(`identity-isolation-${field}`); @@ -12154,8 +12230,9 @@ describe("native warm session supervision", () => { } expect(readNativeSessionIdleWork()).toBe("present"); const next = { ...warmExecution, binding: { ...warmExecution.binding, runId: "run-retirement-retry-next" } }; + // A new run reports the unretired predecessor as its typed pre-provider failure. await expect(executePaperclipNativeSession({ db: leaseDb(next), execution: next, runnerInstanceId: "runner" })) - .rejects.toBe(failure); + .rejects.toMatchObject({ code: "native_predecessor_retirement_unproven", cause: failure }); expect(state.execute).toHaveBeenCalledOnce(); expect(readNativeSessionIdleWork()).toBe("present"); close.mockResolvedValue(undefined); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 077ce813b59..add78046e35 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -58,6 +58,7 @@ import { resolvePluginTaskResume } from "../environment-task-runtime.js"; import { environmentTaskOperationSchema, environmentTaskResultSchema } from "@paperclipai/plugin-sdk"; import { preparePluginRunnerCredentials } from "./plugin-runner-credentials.js"; import { createPluginRunnerTaskOwner, verifyPluginRunnerTaskReattachment } from "./plugin-runner-task.js"; +import { findNativePredecessorRetirementUnproven, NATIVE_PREDECESSOR_RETIREMENT_UNPROVEN_CODE, NativePredecessorRetirementUnprovenError } from "./predecessor-retirement.js"; import { NativeExecutionContext } from "./native-execution-context.js"; import { NativeStartupCleanupPendingError, clearNativeStartupContext } from "./native-startup-cleanup.js"; import { readUnreadSteeredMessages } from "./unread-steered-messages.js"; @@ -695,6 +696,10 @@ type WarmNativeSession = { onReleased: () => void; sessionCheckpointPersisted?: (snapshot: PersistedNativeSession) => void; pluginTaskId?: string; + /** The sandbox that holds this owner's Runner, when it runs in one. */ + providerLeaseId?: string; + /** A successor's retirement of this owner failed; it stays registered for its own sandbox. */ + retirementUnproven?: boolean; observabilityCompatibilityKey?: string; runId: string; issueId: string; @@ -760,6 +765,47 @@ async function closeWarmNativeSession(entry: WarmNativeSession, reason: string, finally { await stopping; } } +function sandboxProviderLeaseId(target?: AdapterExecutionTarget | null): string | null { + return target?.kind === "remote" && target.transport === "sandbox" ? target.sandboxLeaseAcquisition?.providerLeaseId ?? null : null; +} + +/** + * Retire a predecessor before a new run starts. A failed close keeps the owner + * registered, so a successor on the same sandbox never launches over it, and + * reports the typed pre-provider failure that sends the next attempt to a + * fresh sandbox instead of failing the task. + */ +async function retireWarmPredecessor(entry: WarmNativeSession, reason: string, + options?: Parameters[2]) { + // Chaos cell SR1U: a sandbox owner whose stop stays unconfirmed even when + // forced. Test instrumentation only: armed only in a NODE_ENV=test server. + if (process.env.NODE_ENV === "test" && process.env.PAPERCLIP_TEST_WARM_RETIREMENT_FAULT === "unconfirmed" && entry.providerLeaseId) { + entry.retirementUnproven = true; + throw new NativePredecessorRetirementUnprovenError(entry.runId, entry.providerLeaseId, + new Error("warm Runner stop unconfirmed (injected test fault)")); + } + try { await closeWarmNativeSession(entry, reason, options); } + catch (error) { + entry.retirementUnproven = true; + throw new NativePredecessorRetirementUnprovenError(entry.runId, entry.providerLeaseId ?? null, error); + } +} + +/** + * An owner whose retirement stayed unproven lives only in its own sandbox, + * which its successor's attempt left for cleanup. A run on a different sandbox + * cannot meet that Runner, so it forgets the owner instead of replaying its + * rejected close. Any other run keeps retrying retirement. + */ +function forgetUnretiredOwnerOnOtherSandbox(scope: string, entry: WarmNativeSession, + target?: AdapterExecutionTarget | null): boolean { + const next = sandboxProviderLeaseId(target); + if (!entry.retirementUnproven || !entry.providerLeaseId || !next || next === entry.providerLeaseId + || entry.busy || entry.preparingRunId) return false; + forgetWarmNativeSession(scope, entry); + return true; +} + async function detachReleasedWarmNativeSession(entry: WarmNativeSession) { entry.controllerDetachedForRestart = true; if (!entry.session.detachControllerForRestart) throw new Error("native_session_released_detach_unavailable"); @@ -819,6 +865,8 @@ export async function claimWarmNativeInstructionCopy(input: { runId: string; preparationKey: string; forceRetirement?: boolean; + /** This run's execution target; a different sandbox never meets an unretired owner. */ + target?: AdapterExecutionTarget | null; adopt: (previousRunId: string) => Promise; }): Promise<(() => Promise) | null> { const prior = input.priorExecution; @@ -832,6 +880,7 @@ export async function claimWarmNativeInstructionCopy(input: { // Re-read after the wait: the release may have retired or replaced the session. const entry = warmNativeSessions.get(scope); if (!entry || !entry.instructionWorkingCopy?.runId || entry.environmentId !== input.environmentId) return null; + if (forgetUnretiredOwnerOnOtherSandbox(scope, entry, input.target)) return null; if (entry.busy) throw new Error("native_session_supervisor_busy"); entry.busy = true; if (entry.idleTimer !== null) clearTimeout(entry.idleTimer); @@ -840,7 +889,7 @@ export async function claimWarmNativeInstructionCopy(input: { if (warmNativeSessions.get(scope) !== entry) return; entry.closeOnReleaseReason = reason; try { - await closeWarmNativeSession(entry, reason); + await retireWarmPredecessor(entry, reason); forgetWarmNativeSession(scope, entry); } finally { entry.busy = false; } }; @@ -885,6 +934,7 @@ export async function reserveWarmNativeInstructionDirectory(input: { }): Promise<{ reuseRunId: string; adopt: (root: string, collectStopped: () => Promise) => void; release: () => Promise } | null> { for (const [id, entry] of warmNativeSessions) { if (entry.companyId !== input.companyId || entry.agentId !== input.agentId || entry.instructionCopy?.runId !== input.previousRunId) continue; + if (forgetUnretiredOwnerOnOtherSandbox(id, entry, input.target)) return null; if (entry.busy || entry.preparingRunId) throw new Error("native_session_supervisor_busy"); if (entry.idleTimer) clearTimeout(entry.idleTimer); entry.idleTimer = null; @@ -892,7 +942,7 @@ export async function reserveWarmNativeInstructionDirectory(input: { const retire = async (reason: string) => { entry.closeOnReleaseReason = reason; try { - await closeWarmNativeSession(entry, reason); + await retireWarmPredecessor(entry, reason); forgetWarmNativeSession(id, entry); } finally { // Failed containment remains registered and cannot be adopted. The next @@ -2173,10 +2223,12 @@ async function retireSupersededWarmNativeSessions( nextSessionId: string, runId: string, ingress?: { db: Db; claim: NativeWarmIngressClaim }, + target?: AdapterExecutionTarget | null, ): Promise { for (const [scope, entry] of warmNativeSessions) { if (scope === nextSessionScope) continue; const logicalOwner = entry.ownerScope === ownerScope; + if (logicalOwner && forgetUnretiredOwnerOnOtherSandbox(scope, entry, target)) continue; const priorIngress = entry.ingressOwner; const physicalOwner = ingress && priorIngress && nativeWarmIngressAllocation(priorIngress.ingress) === nativeWarmIngressAllocation(ingress.claim.ingress); if (!logicalOwner && !physicalOwner) continue; @@ -2198,7 +2250,7 @@ async function retireSupersededWarmNativeSessions( entry.busy = true; entry.closeOnReleaseReason = logicalOwner ? "warm native session identity changed" : "warm native ingress requires another session"; try { - await closeWarmNativeSession(entry, entry.closeOnReleaseReason, { + await retireWarmPredecessor(entry, entry.closeOnReleaseReason, { discardUnsettledSession: logicalOwner && entry.normalizedSessionId !== nextSessionId, ...(ownReservation ? { preserveInstructionsForRunId: runId } : {}), }); @@ -5697,7 +5749,7 @@ const GONE_REMOTE_RUNNER_DELIVERY_COMMANDS = new Set(["run.attach", "semantic_to "session.goal.get"]); function readSettledRunnerdProjection(root: string, identity: Record, - options: { localRunner?: boolean; controlBytes?: string; remoteRunnerGone?: boolean } = {}): SettledRunnerdProjection { + options: { localRunner?: boolean; controlBytes?: string; remoteRunnerGone?: boolean; parkedGovernedWait?: boolean } = {}): SettledRunnerdProjection { const refuse = (refused: string): SettledRunnerdProjection => ({ refused }); try { if (!isSafeNativeStateDirectory(root)) return refuse("root_unsafe"); @@ -5743,7 +5795,11 @@ function readSettledRunnerdProjection(root: string, identity: Record 0 ? `journal_commands_unsettled(${[...new Set(unsettled)].slice(0, 4).join(",")})` : "journal_terminal_unsettled"); } - if ((control.committedEvents as unknown[]).map(record).some(event => + // A turn parked on a durable governed interaction leaves its question's + // tool input unanswered by design: the answer reaches a new provider turn + // through that interaction, never this Runner. Once that Runner is gone, + // the committed park settles the input. + if (!(options.remoteRunnerGone && options.parkedGovernedWait) && (control.committedEvents as unknown[]).map(record).some(event => (event.eventType === "semantic_tool.input" || event.eventType === "mcp_app.tool_input") && !answered.has(event.sourceEventId))) return refuse("journal_tool_input_unanswered"); return { bytes }; @@ -5843,7 +5899,9 @@ async function inspectFinishedPerTurnRunnerdOwner(input: { currentProviderLeaseId: target?.kind === "remote" && target.transport === "sandbox" ? target.sandboxLeaseAcquisition?.providerLeaseId : undefined, }); - const projectionOptions = { localRunner, controlBytes: input.projectedControlBytes, remoteRunnerGone }; + const parkedGovernedWait = remoteRunnerGone && await priorRunParkedOnGovernedWait(input.db, { + companyId: binding.companyId, issueId: binding.issueId, runId: identity.runId }); + const projectionOptions = { localRunner, controlBytes: input.projectedControlBytes, remoteRunnerGone, parkedGovernedWait }; const projection = readSettledRunnerdProjection(input.root, identity, projectionOptions); if (projection.refused !== undefined) return refuse(projection.refused); const controlBytes = projection.bytes; @@ -5908,7 +5966,7 @@ async function inspectFinishedPerTurnRunnerdOwner(input: { for (const name of readdirSync(quarantine)) { if (!name.startsWith(`${basename(input.root)}.`)) continue; if (quarantinedBootstrapOfOwnerHeldNoProviderWork(resolve(quarantine, name), identity, localRunner)) continue; - const copy = readSettledRunnerdProjection(resolve(quarantine, name), identity, { localRunner, remoteRunnerGone }); + const copy = readSettledRunnerdProjection(resolve(quarantine, name), identity, { localRunner, remoteRunnerGone, parkedGovernedWait }); if (copy.refused !== undefined) return refuse(`quarantine_${copy.refused}`); } } @@ -5932,6 +5990,24 @@ export function quarantinedBootstrapOfOwnerHeldNoProviderWork(root: string, iden || (!localRunner && runnerdStateProvesNoRemoteProviderTurn(root)); } +/** The prior run committed a governed-wait park: its accepted result waits on a durable task interaction. */ +async function priorRunParkedOnGovernedWait(db: Db, input: { companyId: string; issueId: string; runId: string }): Promise { + try { + const [row] = await db.select({ result: nativeRunResults.resultJson }).from(nativeRunFinalizations) + .innerJoin(nativeRunResults, and(eq(nativeRunResults.id, nativeRunFinalizations.resultId), + eq(nativeRunResults.companyId, nativeRunFinalizations.companyId), eq(nativeRunResults.runId, nativeRunFinalizations.runId))) + .where(and(eq(nativeRunFinalizations.companyId, input.companyId), eq(nativeRunFinalizations.issueId, input.issueId), + eq(nativeRunFinalizations.runId, input.runId), eq(nativeRunFinalizations.phase, "committed"))) + .limit(1); + const result = record(row?.result); + return record(result.continuation).kind === "response_wake" && Array.isArray(result.artifacts) + && result.artifacts.some(artifact => record(artifact).kind === "issue_thread_interaction" + && typeof record(artifact).ref === "string" && String(record(artifact).ref).startsWith("interaction:")); + } catch { + return false; + } +} + async function priorRemoteSandboxLeasesEnded(db: Db, input: { companyId: string; runId: string; currentProviderLeaseId?: string; }): Promise { @@ -6235,7 +6311,16 @@ async function migrateRunnerdStateRootForExecution(input: { ); } await recordPriorOwnerFenceRefusal(input, `prior_owner_${verification}`); - throw new Error(`runner_state_identity_mismatch: prior_owner_${verification}${retirementRefusal}`); + const refusal = new Error(`runner_state_identity_mismatch: prior_owner_${verification}${retirementRefusal}`); + // A terminal owner on this reused sandbox can be retired only from a + // different sandbox, where its Runner cannot be. Send the next attempt there. + const target = input.runnerExecutionTarget; + if (verification === "terminal_state_indeterminate" && target?.kind === "remote" && target.transport === "sandbox" + && !target.runnerTask && target.sandboxLeaseAcquisition?.outcome === "resumed") { + throw new NativePredecessorRetirementUnprovenError(identity.runId ?? null, + target.sandboxLeaseAcquisition.providerLeaseId ?? null, refusal); + } + throw refusal; } } return; @@ -8437,6 +8522,9 @@ export function nativeSessionFailureDisposition( sourceFailureCode?: ReturnType, ) { const permanentFailure = + // A same-run retry would meet the same unretired owner on the same sandbox; + // the next run starts on a fresh one instead. + sourceFailureCode === NATIVE_PREDECESSOR_RETIREMENT_UNPROVEN_CODE || sourceFailureCode === "runner_task_admission_rejected" || sourceFailureCode === "runner_ingress_access_rejected" || sourceFailureCode === "native_provider_runtime_missing" || @@ -8629,7 +8717,9 @@ export function nativeSessionFailureSourceCode( | "runner_ingress_access_rejected" | "runner_ingress_acquisition_failed" | "local_runtime_api_listener_unavailable" + | typeof NATIVE_PREDECESSOR_RETIREMENT_UNPROVEN_CODE | "native_session_interrupted" { + if (findNativePredecessorRetirementUnproven(error)) return NATIVE_PREDECESSOR_RETIREMENT_UNPROVEN_CODE; if (error instanceof NativePermissionDeclinedError) return "native_permission_declined"; if (error instanceof NativeGovernedWaitSettlementPendingError) return "native_governed_wait_settlement_pending"; if (error instanceof NativeProviderStateIncompatibleError) return NATIVE_PROVIDER_STATE_INCOMPATIBLE; @@ -10040,6 +10130,7 @@ export async function executePaperclipNativeSession(input: { executingNativeOwnerScopes.set(ownerScope, ownerToken); if (!input.useRunnerd) await retireSupersededWarmNativeSessions( ownerScope, nativeSessionScopeKey(input.execution), nativeSessionKey(input.execution), runId, + undefined, input.runnerExecutionTarget, ); if ((input.execution.schema === "paperclip.native-execution-input.v6" || input.execution.schema === "paperclip.native-execution-input.v8") && isCloudManagedInstance() && (!input.useRunnerd || input.runnerExecutionTarget?.kind !== "remote" @@ -10800,6 +10891,7 @@ async function executePaperclipNativeSessionAttempt( nativeSessionScopeKey(input.execution), nativeSessionKey(input.execution), input.execution.binding.runId, ingress ? { db: input.db, claim: { ...input.execution.binding, ingress, leaseOwner, controllerBootId: controller.bootId, controllerGeneration } } : undefined, + input.runnerExecutionTarget, ); claimedStartupContext?.assertOpen(); if (prepareAfterClaim) input = await prepareAfterClaim(); @@ -11430,7 +11522,9 @@ async function executePaperclipNativeSessionAttempt( startupForAdmission!.executionContext = undefined; }; if (warmSessionId !== null && warmConfigDigest !== null && !input.restartRecovery) { - const entry = warmNativeSessions.get(warmSessionId); + const registered = warmNativeSessions.get(warmSessionId); + const entry = registered && forgetUnretiredOwnerOnOtherSandbox(warmSessionId, registered, input.runnerExecutionTarget) + ? undefined : registered; if (entry?.released) requireReleasedWarmScope(input, releasedWarmRunner(readWarmNativeEnvelope(input.execution)), readRunnerdDurableIdentity(scopedRunnerdStateRoot(input.execution))); if (entry || remoteWarmRecovery?.releasedSource) { @@ -11474,7 +11568,7 @@ async function executePaperclipNativeSessionAttempt( entry.busy = true; entry.closeOnReleaseReason = "warm native session configuration changed"; try { - await closeWarmNativeSession(entry, entry.closeOnReleaseReason, { preserveInstructionsForRunId: input.execution.binding.runId }); + await retireWarmPredecessor(entry, entry.closeOnReleaseReason, { preserveInstructionsForRunId: input.execution.binding.runId }); forgetWarmNativeSession(warmSessionId, entry); } finally { entry.busy = false; } if (preparedCopy) throw new Error("native_instruction_preparation_configuration_changed"); @@ -12007,6 +12101,7 @@ async function executePaperclipNativeSessionAttempt( issueId: input.execution.binding.issueId }), pluginTaskId: usesPluginTask && input.runnerExecutionTarget?.kind === "remote" && input.runnerExecutionTarget.transport === "sandbox" ? input.runnerExecutionTarget.sandboxLeaseAcquisition?.providerLeaseId : undefined, + providerLeaseId: sandboxProviderLeaseId(input.runnerExecutionTarget) ?? undefined, runId: input.execution.binding.runId, issueId: input.execution.binding.issueId, instructionWorkingCopy: input.instructionWorkingCopy?.checkpointWarm ? undefined : input.instructionWorkingCopy, @@ -12358,7 +12453,11 @@ async function executePaperclipNativeSessionAttempt( } if ( error instanceof NativeResultPendingFinalizationError || - error instanceof NativeCancellationPendingRecoveryError + error instanceof NativeCancellationPendingRecoveryError || + // An unretired predecessor failed this run before it launched a Runner. + // It is not a provider failure: the heartbeat boundary sends the next + // attempt to a fresh sandbox, or keeps today's preservation. + findNativePredecessorRetirementUnproven(error) ) { // This is not a provider failure and must not overwrite the durable // result/coordinator state. The heartbeat boundary will either hand an diff --git a/server/src/services/native-runtime/predecessor-retirement.ts b/server/src/services/native-runtime/predecessor-retirement.ts new file mode 100644 index 00000000000..fc76fdc6643 --- /dev/null +++ b/server/src/services/native-runtime/predecessor-retirement.ts @@ -0,0 +1,72 @@ +/** + * A new run on a reused sandbox must first retire the previous run's warm + * Runner there. When that retirement stays unproven (its close failed, or its + * durable journal cannot prove the owner finished), the new run has done no + * provider work. It must not fail the task: the next attempt drops the reused + * sandbox and starts on a fresh one restored from the saved workspace, which + * cannot meet the old Runner. The old sandbox is kept for the cleanup sweep. + */ +export const NATIVE_PREDECESSOR_RETIREMENT_UNPROVEN_CODE = "native_predecessor_retirement_unproven"; + +/** Lease metadata key: the next acquisition replaces this sandbox instead of resuming it. */ +export const REPLACE_BEFORE_REUSE_KEY = "replaceBeforeReuse"; +export const REPLACE_BEFORE_REUSE_SCHEMA = "paperclip.replace-before-reuse.v1"; + +export class NativePredecessorRetirementUnprovenError extends Error { + readonly code = NATIVE_PREDECESSOR_RETIREMENT_UNPROVEN_CODE; + constructor( + readonly predecessorRunId: string | null, + /** The sandbox that still holds the unretired owner, when known. */ + readonly providerLeaseId: string | null, + cause: unknown, + ) { + super(`The previous run's session on this sandbox could not be retired (${ + cause instanceof Error ? cause.message : String(cause)}). The next attempt starts on a fresh sandbox.`, { cause }); + this.name = "NativePredecessorRetirementUnprovenError"; + } +} + +/** The typed error itself or one of its first causes (AggregateError members included). */ +export function findNativePredecessorRetirementUnproven(error: unknown): NativePredecessorRetirementUnprovenError | null { + const pending: unknown[] = [error]; + for (let seen = 0; pending.length > 0 && seen < 16; seen++) { + const current = pending.shift(); + if (current instanceof NativePredecessorRetirementUnprovenError) return current; + if (current instanceof AggregateError) pending.push(...current.errors); + if (current instanceof Error && current.cause !== undefined) pending.push(current.cause); + } + return null; +} + +/** Durable record on a failed run whose next attempt drops its reused sandbox. */ +export const PREDECESSOR_RETIREMENT_FALLBACK_KEY = "predecessorRetirementFallback"; + +export type PredecessorRetirementFallback = { + version: 1; + providerWorkStarted: false; + predecessorRunId: string | null; + replacedProviderLeaseIds: string[]; +}; + +export function readPredecessorRetirementFallback(resultJson: unknown): PredecessorRetirementFallback | null { + if (typeof resultJson !== "object" || resultJson === null) return null; + const value = (resultJson as Record)[PREDECESSOR_RETIREMENT_FALLBACK_KEY]; + if (typeof value !== "object" || value === null) return null; + const record = value as Record; + return record.version === 1 && record.providerWorkStarted === false ? record as PredecessorRetirementFallback : null; +} + +export type ReplaceBeforeReuseMarker = { + schema: typeof REPLACE_BEFORE_REUSE_SCHEMA; + runId: string; + predecessorRunId: string | null; + recordedAt: string; +}; + +export function readReplaceBeforeReuseMarker(metadata: Record | null | undefined): ReplaceBeforeReuseMarker | null { + const value = metadata?.[REPLACE_BEFORE_REUSE_KEY]; + if (typeof value !== "object" || value === null) return null; + const marker = value as Record; + return marker.schema === REPLACE_BEFORE_REUSE_SCHEMA && typeof marker.runId === "string" + ? marker as ReplaceBeforeReuseMarker : null; +} diff --git a/server/src/services/remote-workspace-unchanged-release.test.ts b/server/src/services/remote-workspace-unchanged-release.test.ts index dadd0b2a426..a218aee7266 100644 --- a/server/src/services/remote-workspace-unchanged-release.test.ts +++ b/server/src/services/remote-workspace-unchanged-release.test.ts @@ -19,6 +19,7 @@ import { prepareRemoteWorkspace, readRemoteWorkspaceAuthority, RemoteWorkspaceWriterActiveError, reserveRemoteWorkspace, saveRemoteWorkspace, } from "./remote-workspaces.js"; import { UNCHANGED_BASELINE_KEY } from "./remote-workspace-unchanged-proof.js"; +import { releaseUnchangedFallbackWorkspace } from "./heartbeat/predecessor-retirement-fallback.js"; const exec = promisify(execFile); const support = await getEmbeddedPostgresTestSupport(); @@ -179,6 +180,30 @@ describe.skipIf(!support.supported)("remote workspace writer that ended without await expectFullSave(f, true); }); + // A follow-up that could not retire its predecessor fails before provider + // work; its next attempt moves to a fresh sandbox only with nothing unsaved. + it.each([ + { label: "an untouched workspace", provision: undefined, released: true }, + { label: "setup that wrote into the workspace", provision: "echo provisioned > provisioned.txt", released: false }, + ])("hands on the workspace of a run that could not retire its predecessor only for $label", async ({ provision, released }) => { + const f = await preparedFollowUp(provision ? { runtimeProvisionCommand: provision } : {}); + // The heartbeat still holds the run's controller lease when it settles the failure. + await f.end({ status: "failed", errorCode: "adapter_failed", controllerLeaseExpiresAt: new Date(Date.now() + 60_000) }); + expect(await releaseUnchangedFallbackWorkspace(db, { id: f.runB, companyId: f.companyId })).toBe(released); + expect(readRemoteWorkspaceAuthority((await f.workspace()).metadata)).toMatchObject(released + ? { dirty: false, writerRunId: null, snapshotId: f.savedA.snapshotId } : { dirty: true, writerRunId: f.runB }); + }); + + it.each([1, 0])("queues no fallback attempt beside another writer (epoch change %i)", async epochChange => { + const f = await preparedFollowUp(); + await f.end({ status: "failed", errorCode: "adapter_failed" }); + const current = await f.workspace(); + const authority = readRemoteWorkspaceAuthority(current.metadata)!; + await db.update(executionWorkspaces).set({ metadata: { ...current.metadata, remoteWorkspace: { ...authority, + writerRunId: randomUUID(), epoch: authority.epoch + epochChange } } }).where(eq(executionWorkspaces.id, current.id)); + expect(await releaseUnchangedFallbackWorkspace(db, { id: f.runB, companyId: f.companyId })).toBe(false); + }); + it("keeps the full save while the writer's owner may still act, and while it is still running", async () => { const f = await preparedFollowUp(); await f.end({ controllerLeaseExpiresAt: new Date(Date.now() + 60_000) }); diff --git a/tests/restart-chaos/README.md b/tests/restart-chaos/README.md index bd69b2022d5..e99224fcf98 100644 --- a/tests/restart-chaos/README.md +++ b/tests/restart-chaos/README.md @@ -937,6 +937,25 @@ applies unchanged (`no_failed_attempt` and `issue_done` cover the follow-up), pl session would not exercise the retirement). Because tasks share their adapter's agent, `--tasks 2 --concurrency 2` is the two-concurrent-runs variant. SR1 does not combine with K* or PV* faults. +### SR1U: the retained owner cannot be retired + +```sh +node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/main.ts --env daytona --daytona-warm \ + --daytona-image --adapters codex --workloads Q1 --faults SR1U --concurrency 1 --tasks 1 --seed 311 +``` + +SR1U is SR1 where the parked owner's stop stays unconfirmed even when forced. The harness boots the +server with `PAPERCLIP_TEST_WARM_RETIREMENT_FAULT=unconfirmed` (test instrumentation, armed only when +`NODE_ENV=test`, as in the harness server), so every retirement of a warm sandbox owner fails. This is the staging shape +where a follow-up failed with `Controller journal drain timed out` or `runner did not durably suspend +before checkpoint` before any provider work and nothing ever restarted the task. The follow-up must +fail once with `failureCause: native_predecessor_retirement_unproven`, re-queue itself in the +uncharged `interrupted_preparation` lane, and finish on a fresh sandbox restored from the saved +workspace. The Q1 oracle applies, except that this one pre-provider failure is not a failed attempt, +plus `predecessor_unretirable_fell_back` and `follow_up_fresh_sandbox` (the succeeding follow-up ran +on a different sandbox than the asking run). SR1U needs `--env daytona --daytona-warm`, and it arms +its fault for the whole server, so it does not share a wave with SR1. + ## Database contention (L1, `--db-pressure`) ```sh diff --git a/tests/restart-chaos/config.ts b/tests/restart-chaos/config.ts index c8a5b30596c..1e532c83885 100644 --- a/tests/restart-chaos/config.ts +++ b/tests/restart-chaos/config.ts @@ -282,6 +282,9 @@ export function parseCommand(argv: readonly string[], now = Date.now()): ParsedC if (other.length) throw new Error(`Session faults (SR*) need ${SESSION_FAULT_WORKLOADS.join(", ")}; remove ${other.join(", ")} from --workloads`); // Only a retained warm owner can be superseded; a per-turn Runner exits after each turn. if (options.lifecycle !== "warm" && !options.daytonaWarm) throw new Error("Session faults (SR*) need a retained owner: add --lifecycle warm (or --daytona-warm)"); + // SR1U arms its fault for the whole server and needs a reused sandbox to drop. + if (sessionFaults.includes("SR1U") && (env !== "daytona" || !options.daytonaWarm)) throw new Error("SR1U needs a reused sandbox: run it with --env daytona --daytona-warm"); + if (sessionFaults.includes("SR1U") && sessionFaults.includes("SR1")) throw new Error("SR1U arms its fault for every task; run SR1 in a separate wave"); } validateMultiServerOptions(options); // K15 emulates one deploy identity per generation; a second server beside it would run in the real host's process space. diff --git a/tests/restart-chaos/main.ts b/tests/restart-chaos/main.ts index 0a725569f79..8312373d9f6 100644 --- a/tests/restart-chaos/main.ts +++ b/tests/restart-chaos/main.ts @@ -50,6 +50,7 @@ import type { RestartStep } from "./repeated-restarts.js"; import { isBrokenStdoutError, markTimelineEchoBroken, Timeline } from "./timeline.js"; import { guardedRunnerOutputs, worktreeFingerprint } from "./wave-guard.js"; import { checkCrossServer, readCrossServerEvidence } from "./multi-server.js"; +import { sessionFaultServerEnvironment } from "./session-faults.js"; import type { FaultKind, FaultReceipt, OracleArtifacts, TriggerId, WavePlan } from "./types.js"; const repositoryRoot = path.resolve(import.meta.dirname, "../.."); @@ -354,6 +355,7 @@ async function main(): Promise { } if (plan.options.timeAgeMs) supervisor.timeAgeMs = plan.options.timeAgeMs; if (plan.options.rrStopOn) supervisor.rrStopOn = plan.options.rrStopOn; + Object.assign(serverEnvironment, sessionFaultServerEnvironment(plan.options.sessionFaults)); await supervisor.start(serverEnvironment); // TM2/TM3 age the database; the observer and grader read run times back at their real times. const api: ChaosApi = new TimeShiftedApi(supervisor.baseUrl, supervisor.agingShifts); diff --git a/tests/restart-chaos/observer.ts b/tests/restart-chaos/observer.ts index 7d029633b09..06fba901307 100644 --- a/tests/restart-chaos/observer.ts +++ b/tests/restart-chaos/observer.ts @@ -855,11 +855,12 @@ export class TaskObserver { if (this.plan.workload === "G1") await this.approvalStep(sample, now); if (this.plan.workload === "H1") await this.budgetStep(sample, now); if (this.plan.workload === "Q1" || this.plan.workload === "Q4") { + const sessionFault = isSessionFault(this.plan.fault) ? this.plan.fault : null; await questionStep({ api: this.api, issueId: this.record.issueId, nonce: this.plan.nonce, record: this.record, sample, now, // An `answered` fault waits for the answer, so the board may answer before it fires. boardMayAct: this.boardMayAct(sample, "answered"), sequence: this.plan.workload === "Q4", note: (kind, data) => this.timeline.add(kind, { taskId: this.plan.taskId, ...data }), - ...(isSessionFault(this.plan.fault) ? { beforeAnswer: () => rotateAgentSession(this.api, this.lab.agents[this.plan.adapter].id, this.plan.index, now) } : {}) }); + ...(sessionFault ? { beforeAnswer: () => rotateAgentSession(this.api, this.lab.agents[this.plan.adapter].id, this.plan.index, now, sessionFault) } : {}) }); } } diff --git a/tests/restart-chaos/question-handoff.test.ts b/tests/restart-chaos/question-handoff.test.ts index d1082ad0507..518553ff9bd 100644 --- a/tests/restart-chaos/question-handoff.test.ts +++ b/tests/restart-chaos/question-handoff.test.ts @@ -6,7 +6,7 @@ import { questionStep, type QuestionArtifacts, } from "./question-handoff.js"; import { planTasks, taskFaultSchedule } from "./scheduler.js"; -import { rotateAgentSession } from "./session-faults.js"; +import { rotateAgentSession, sessionFaultServerEnvironment } from "./session-faults.js"; import type { OracleArtifacts, TaskRecord, TaskSample } from "./types.js"; import { workloadDefinitions } from "./workloads.js"; @@ -212,4 +212,33 @@ describe("Q1 saved question", () => { expect(refused.verdict).toBe("fail"); }); }); + + describe("SR1U: the retained owner cannot be retired", () => { + it("is a Daytona warm-only variant that arms its server fault for the wave", () => { + const command = parseCommand(["--env", "daytona", "--daytona-warm", "--daytona-image", "img@sha256:" + "a".repeat(64), + "--adapters", "codex", "--workloads", "Q1", "--faults", "SR1U", "--tasks", "1", "--concurrency", "1"]); + if (command.mode !== "wave") throw new Error("expected a wave"); + expect(command.options).toMatchObject({ faults: [], sessionFaults: ["SR1U"] }); + expect(sessionFaultServerEnvironment(command.options.sessionFaults)).toEqual({ PAPERCLIP_TEST_WARM_RETIREMENT_FAULT: "unconfirmed" }); + expect(sessionFaultServerEnvironment(["SR1"])).toEqual({}); + // Locally there is no reused sandbox to drop. + expect(() => parseCommand(["--workloads", "Q1", "--faults", "SR1U", "--lifecycle", "warm"])).toThrow("--env daytona --daytona-warm"); + }); + + it("passes only when the follow-up finished on a fresh sandbox after the pre-provider fallback", () => { + const rotation = { at: 2_000, idleTimeoutMs: 300_002, httpStatus: 200, error: null, predecessorUnretirable: true }; + const run = (id: string, status: string, createdAt: number, providerLeaseId: string, failureCause: string | null = null) => + ({ id, status, errorCode: status === "failed" ? "adapter_failed" : null, createdAt: new Date(createdAt).toISOString(), + nativeSessionId: id === "run-1" ? "s1" : "s2", providerLeaseId, failureCause }); + const fellBack = run("run-2", "failed", 6_000, "sandbox-a", "native_predecessor_retirement_unproven"); + const passed = gradeQuestionHandoff(NONCE, artifacts({ rotation, runs: [run("run-1", "succeeded", 500, "sandbox-a"), fellBack, + run("run-3", "succeeded", 7_000, "sandbox-b")] })); + expect(passed).toMatchObject({ verdict: "pass" }); + // A follow-up that stayed on the reused sandbox, or any other failure, fails the cell. + expect(gradeQuestionHandoff(NONCE, artifacts({ rotation, runs: [run("run-1", "succeeded", 500, "sandbox-a"), fellBack, + run("run-3", "succeeded", 7_000, "sandbox-a")] })).checks.find(check => check.name === "follow_up_fresh_sandbox")?.ok).toBe(false); + expect(gradeQuestionHandoff(NONCE, artifacts({ rotation, runs: [run("run-1", "succeeded", 500, "sandbox-a"), + run("run-2", "failed", 6_000, "sandbox-a", "native_session_interrupted"), run("run-3", "succeeded", 7_000, "sandbox-b")] })).verdict).toBe("fail"); + }); + }); }); diff --git a/tests/restart-chaos/question-handoff.ts b/tests/restart-chaos/question-handoff.ts index cc9d81efa59..66a3e9aea53 100644 --- a/tests/restart-chaos/question-handoff.ts +++ b/tests/restart-chaos/question-handoff.ts @@ -12,7 +12,7 @@ import type { ChaosApi } from "./api.js"; import type { OracleArtifacts, OracleResult, TaskRecord, TaskSample } from "./types.js"; import type { WorkloadDefinition } from "./workloads.js"; -import type { SessionRotation } from "./session-faults.js"; +import { PREDECESSOR_RETIREMENT_UNPROVEN_CAUSE, type SessionRotation } from "./session-faults.js"; type Json = Record; @@ -44,7 +44,9 @@ export interface QuestionAnswer { export interface QuestionArtifacts extends QuestionRecord { runs: Array<{ id: string; status: string; errorCode: string | null; createdAt: string | null; startedAt?: string | null; /** SR1: the run's normalized provider session, read only when the board replaced the session. */ - nativeSessionId?: string | null }>; + nativeSessionId?: string | null; + /** SR1U: the run's failure cause and the sandbox it ran on. */ + failureCause?: string | null; providerLeaseId?: string | null }>; statuses: Record; } @@ -214,10 +216,14 @@ export async function collectQuestionArtifacts(api: Pick, issue const question = record.question ?? { interactionIds: [], seenAt: null, askedByRunId: null, pendingNow: false }; // SR1 proves its follow-up started a new provider session, so a pass is not a resumed session. const sessions = new Map(); + const sandboxes = new Map(); if (question.rotation) for (const run of runs ?? []) { const id = String(run.runId ?? run.id); const detail = await api.get(`/api/heartbeat-runs/${id}`, 10_000).catch(() => null); sessions.set(id, typeof detail?.nativeSessionId === "string" ? detail.nativeSessionId : null); + const failureCause = detail?.resultJson?.failureCause, providerLeaseId = detail?.runnerProfileJson?.remoteWorkspace?.providerLeaseId; + sandboxes.set(id, { failureCause: typeof failureCause === "string" ? failureCause : null, + providerLeaseId: typeof providerLeaseId === "string" ? providerLeaseId : null }); } return { ...question, @@ -225,7 +231,8 @@ export async function collectQuestionArtifacts(api: Pick, issue statuses: Object.fromEntries(interactions.map(interaction => [String(interaction.id), String(interaction.status)])), runs: (runs ?? []).map(run => ({ id: String(run.runId ?? run.id), status: String(run.status), errorCode: run.errorCode ?? null, createdAt: run.createdAt ?? null, startedAt: run.startedAt ?? null, - ...(sessions.has(String(run.runId ?? run.id)) ? { nativeSessionId: sessions.get(String(run.runId ?? run.id)) } : {}) })), + ...(sessions.has(String(run.runId ?? run.id)) ? { nativeSessionId: sessions.get(String(run.runId ?? run.id)) } : {}), + ...(question.rotation?.predecessorUnretirable ? sandboxes.get(String(run.runId ?? run.id)) ?? {} : {}) })), }; } @@ -238,13 +245,32 @@ function followUpSessionCheck(runs: QuestionArtifacts["runs"], asked: QuestionAr detail: `asked=${before ?? "unknown"} followUps=${followUps.map(run => run.nativeSessionId ?? "unknown").join(",") || "none"}` }; } +/** + * SR1U: the retained owner could not be retired, so the follow-up's first + * attempt failed before provider work and its retry finished on another + * sandbox. Those pre-provider failures are the fallback, not a failed attempt. + */ +function freshSandboxChecks(runs: QuestionArtifacts["runs"], asked: QuestionArtifacts["runs"][number] | undefined, answeredAt: number | null) { + const fellBack = runs.filter(run => run.status === "failed" && run.failureCause === PREDECESSOR_RETIREMENT_UNPROVEN_CAUSE); + const reused = asked?.providerLeaseId ?? null; + const fresh = runs.filter(run => run.id !== asked?.id && run.status === "succeeded" && answeredAt !== null && run.createdAt + && Date.parse(run.createdAt) > answeredAt && typeof run.providerLeaseId === "string" && run.providerLeaseId !== reused); + return [ + { name: "predecessor_unretirable_fell_back", ok: fellBack.length > 0, detail: fellBack.map(run => run.id).join(",") || "none" }, + { name: "follow_up_fresh_sandbox", ok: reused !== null && fresh.length > 0, + detail: `asked=${reused ?? "unknown"} followUps=${fresh.map(run => run.providerLeaseId).join(",") || "none"}` }, + ]; +} + export function gradeQuestionHandoff(nonce: string, artifacts: OracleArtifacts): OracleResult { const question = artifacts.question; const code = q1Code(nonce); const brief = artifacts.documents.brief ?? ""; const bullets = brief.split(/\r?\n/).filter(line => /^\s*[-*] \S/.test(line)).length; const runs = question?.runs ?? []; - const failed = runs.filter(run => run.status === "failed" || run.status === "timed_out"); + const unretirable = question?.rotation?.predecessorUnretirable === true; + const failed = runs.filter(run => (run.status === "failed" || run.status === "timed_out") + && !(unretirable && run.failureCause === PREDECESSOR_RETIREMENT_UNPROVEN_CAUSE)); const asked = question?.askedByRunId ? runs.find(run => run.id === question.askedByRunId) : undefined; const answeredAt = question?.answer?.at ?? null; // Repeated work: another run that started (or was created) after the question was saved and @@ -264,6 +290,7 @@ export function gradeQuestionHandoff(nonce: string, artifacts: OracleArtifacts): ...(question?.rotation ? [followUpSessionCheck(runs, asked, answeredAt), { name: "session_rotated_before_answer", ok: question.rotation.httpStatus === 200 && (answeredAt === null || question.rotation.at < answeredAt), detail: `idleTimeoutMs=${question.rotation.idleTimeoutMs} http=${question.rotation.httpStatus}${question.rotation.error ? ` ${question.rotation.error}` : ""}` }] : []), + ...(unretirable ? freshSandboxChecks(runs, asked, answeredAt) : []), { name: "brief_has_answer", ok: brief.includes(q1AnswerMarker(nonce, code)), detail: q1AnswerMarker(nonce, code) }, { name: "brief_has_three_bullets", ok: bullets >= 3, detail: `bullets=${bullets}` }, ]; diff --git a/tests/restart-chaos/session-faults.ts b/tests/restart-chaos/session-faults.ts index 83822c803b9..4f51f9dca75 100644 --- a/tests/restart-chaos/session-faults.ts +++ b/tests/restart-chaos/session-faults.ts @@ -10,24 +10,40 @@ * The retirement must not fail the follow-up: Q1's `no_failed_attempt` and * `issue_done` checks are the oracle. Two Q1 tasks on the same agent are the * two-concurrent-runs variant: one change rotates both tasks' sessions. + * + * SR1U is the variant where that owner cannot be retired at all: the server + * is booted with a test-only fault that leaves every warm sandbox owner's stop + * unconfirmed, even when forced. The follow-up must then drop the reused + * sandbox and finish on a fresh one restored from the saved workspace. Its + * one allowed failed attempt is the pre-provider fallback itself. */ import type { ChaosApi } from "./api.js"; import type { WorkloadId } from "./types.js"; -export const SESSION_FAULT_KINDS = ["SR1"] as const; +export const SESSION_FAULT_KINDS = ["SR1", "SR1U"] as const; export type SessionFaultKind = (typeof SESSION_FAULT_KINDS)[number]; export const SESSION_FAULT_WORKLOADS: readonly WorkloadId[] = ["Q1"]; +/** The pre-provider failure that sends the next attempt to a fresh sandbox. */ +export const PREDECESSOR_RETIREMENT_UNPROVEN_CAUSE = "native_predecessor_retirement_unproven"; + export function isSessionFault(value: string): value is SessionFaultKind { return (SESSION_FAULT_KINDS as readonly string[]).includes(value); } +/** Server environment a wave of these faults needs. It applies to the whole server. */ +export function sessionFaultServerEnvironment(faults: readonly SessionFaultKind[] | undefined): Record { + return faults?.includes("SR1U") ? { PAPERCLIP_TEST_WARM_RETIREMENT_FAULT: "unconfirmed" } : {}; +} + /** What the board changed, recorded on the task's question. */ export interface SessionRotation { at: number; idleTimeoutMs: number; httpStatus: number | null; error: string | null; + /** SR1U: the retained owner cannot be retired; the follow-up must move to a fresh sandbox. */ + predecessorUnretirable?: boolean; } /** @@ -35,9 +51,11 @@ export interface SessionRotation { * fingerprint and is harmless to the run: the warm idle window, by a few * milliseconds unique to this task. */ -export async function rotateAgentSession(api: Pick, agentId: string, taskIndex: number, now: number): Promise { +export async function rotateAgentSession(api: Pick, agentId: string, taskIndex: number, now: number, + fault: SessionFaultKind = "SR1"): Promise { const idleTimeoutMs = 300_000 + 1 + taskIndex; - const rotation: SessionRotation = { at: now, idleTimeoutMs, httpStatus: null, error: null }; + const rotation: SessionRotation = { at: now, idleTimeoutMs, httpStatus: null, error: null, + ...(fault === "SR1U" ? { predecessorUnretirable: true } : {}) }; try { await api.patch(`/api/agents/${agentId}`, { adapterConfig: { idleTimeoutMs } }); rotation.httpStatus = 200; From f9171ef62187148e61f6e782ed8f14a87ba925ac Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:11:16 -0600 Subject: [PATCH 06/12] fix(native): retry a throttled post-turn checkpoint for real; wait out storage throttling while saving the provider session (#20871) 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 > - After a native turn in a remote sandbox, closing the session saves the provider session (the harness backup) to object storage. The next attempt resumes from it. > - On staging, object storage throttled that save ("Please reduce your request rate", S3 `SlowDown`). The close failed, was retried 3 times 1 s apart, and the session was quarantined. The next attempt of the same run was refused with `native_session_cleanup_quarantined`. > - The retries could never succeed: the Runner transport memoizes `close()`, so every retry returned the first rejected promise and never ran the checkpoint again. Quarantine recovery and admission recovery call the same `close()`. > - Also, the backup upload did not wait out a throttle or outage longer than one request's own retries. > - This pull request makes a close that failed only in its checkpoint run that checkpoint again on the next `close()`, and makes the backup upload wait out storage unavailability inside the existing bounded storage wait. > - The benefit is that a transient storage throttle no longer ends in a quarantine that refuses the next attempt of the same run. ## Linked Issues or Issue Description Refs #20772 (made the backup upload resendable after `SlowDown`). Refs #20165 (per-request throttle backoff). Refs #20833 (earlier steps of the same failure chain). **What happened?** 1. A staging Codex run on Daytona finished its turn. The post-turn close ran the remote checkpoint. 2. The checkpoint failed: `remote checkpoint failed: Please reduce your request rate.` 3. The Runner retried the close 3 times 1 s apart (`native session cleanup recovery after close failure (1..3)`), then 3 quarantine recoveries. All failed within about 5 s. 4. The next attempt of the same run was refused: `native_session_cleanup_quarantined: prior session cleanup remains incomplete`. **Expected behavior** A throttle slows the save down. A retry of the close saves the session again. The next attempt of the same run proceeds once the save succeeds. **Steps to reproduce** 1. Make a transport close whose checkpoint throws once. 2. Call `close()` again. 3. On master the second call returns the first failure without running the checkpoint again. 4. Separately, answer each harness-backup `PUT` with 9 `503 SlowDown` responses. On master `persistNativeHarnessBackup` throws `SlowDown: Please reduce your request rate.` **Paperclip version or commit** master at 381b862135. ## What Changed - `packages/paperclip-runner/src/live/runnerd-codex-transport.ts`: when a close fails because its checkpoint failed (and the control-route release did not fail), the transport keeps the checkpoint and the rest of the close. The next `close()` runs the checkpoint again and then finishes the close. All other close failures (for example a missing suspension proof) stay memoized as before. - `server/src/services/native-runtime/native-harness-backup-storage.ts`: `persistNativeHarnessBackup` runs inside the existing storage outage wait (`waitOutStorageOutages`, purpose "saving the provider session"). A storage-unavailable failure (outage, throttle, rejected credentials) that outlasts one request's retries is retried with the bounded exponential storage wait (2 s doubling to 30 s, 5 minutes in total). Each request still uses the jittered per-request throttle backoff from #20165. - Restart chaos: storage fault `ST8` answers the next 9 to 12 (seeded) harness-backup `PUT`s with `503 SlowDown`. The storage audit reports it when it never changed a request. The README documents it (for `--env daytona --storage s3`). ## Verification - RED on master (fix reverted, new tests kept): - `runnerd-codex-transport-suspension.test.ts` "runs a failed close checkpoint again on the next close": the second `close()` returns the first `SlowDown` error. - `native-harness-backup-throttle.integration.test.ts` "waits out a throttle that outlasts one request's backoff": `SlowDown: Please reduce your request rate.` - GREEN: both pass. `native-harness-backup-throttle.integration.test.ts` 3 passed. `runnerd-codex-transport-suspension.test.ts` 12 passed. `runnerd-codex-transport-release-resume.test.ts` 22 passed (twice). `vitest --config tests/restart-chaos/vitest.config.ts`: 46 files, 554 tests passed, including the new ST8 planning and proxy test. - `tsc --noEmit` clean for `packages/paperclip-runner`, `server` and `tests/restart-chaos`. - `runnerd-codex-transport-settlement.test.ts` has one case that also fails on unchanged master in this worktree. ## Risks - A checkpoint retry runs the same server checkpoint callback again after the runner process was stopped. It reads the settled state from the sandbox. If the sandbox is gone, it fails as before and the quarantine stays. - A close attempt can now take up to the 5-minute storage wait during a long outage. This is on the post-turn path only, not before `turn.start`. - No change to the quarantine admission rules: admission still accelerates one bounded recovery batch and refuses if it fails. Those recoveries now really retry the checkpoint. ## 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 Fable 5.2 --- ...runnerd-codex-transport-suspension.test.ts | 48 ++++++ .../src/live/runnerd-codex-transport.ts | 141 +++++++++++++----- .../native-harness-backup-storage.ts | 11 +- ...arness-backup-throttle.integration.test.ts | 47 ++++++ tests/restart-chaos/README.md | 5 +- tests/restart-chaos/storage-audit.ts | 5 +- tests/restart-chaos/storage-chaos.ts | 4 +- .../storage-multipart-lag.test.ts | 31 ++++ tests/restart-chaos/storage-proxy.ts | 10 +- 9 files changed, 251 insertions(+), 51 deletions(-) diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport-suspension.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport-suspension.test.ts index 004453760bd..94b3a43d97c 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport-suspension.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport-suspension.test.ts @@ -768,3 +768,51 @@ it("persists an active provider as settled before bounded suspension", async () await rm(stateDirectory, { recursive: true, force: true }); } }, 30_000); + +it("runs a failed close checkpoint again on the next close instead of returning the old failure", async () => { + const stateDirectory = await mkdtemp(join(tmpdir(), "runnerd-close-checkpoint-retry-")); + const identity = { + runnerInstanceId: "runner-close-checkpoint-retry", + environmentLeaseId: "lease-close-checkpoint-retry", + runId: "run-close-checkpoint-retry", + normalizedSessionId: "session-close-checkpoint-retry", + turnId: "turn-close-checkpoint-retry", + itemId: "item-close-checkpoint-retry", + }; + const checkpoints: string[] = []; + const bundle = createCapabilityRunnerdCodexTransport({ + runnerBinary: defaultCapabilityRunnerdBinary(), + codexCommand: fakeCodex, + codexArgs: fakeCodexArgs(stateDirectory), + stateDirectory, + closeGraceMs: 400, + lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null }, + prpIdentity: identity, + readRunnerState: async () => ({ schema: "paperclip.runner.durable.state.v1", ...identity, lifecycle: "suspended" }), + controlPlaneRegistration: async (authority) => { + await authority.start(); + return { + connectUrl: authority.connectUrl, + checkpoint: async (settlement: "settled" | "unsettled") => { + checkpoints.push(settlement); + if (checkpoints.length === 1) throw new Error("SlowDown: Please reduce your request rate."); + }, + release: async () => {}, + }; + }, + }); + bundle.transport.setServerRequestHandler(async () => ({ success: true, contentItems: [] })); + try { + await bundle.transport.request("thread/start", { cwd: tmpdir(), dynamicTools: [] }); + await expect(bundle.transport.close("native session execution complete")).rejects.toThrow("Please reduce your request rate"); + const retried = await bundle.transport.close("native session cleanup recovery after close failure (1)").then(() => null, (error: unknown) => error); + if (retried !== null) expect(retried).toMatchObject({ code: "native_session_close_unrecoverable" }); + expect(checkpoints).toHaveLength(2); + expect(checkpoints[1]).toBe(checkpoints[0]); + expect(await bundle.transport.close("after recovery").then(() => null, (error: unknown) => error)).toBe(retried); + expect(checkpoints).toHaveLength(2); + } finally { + await bundle.transport.close().catch(() => undefined); + await rm(stateDirectory, { recursive: true, force: true }); + } +}, 30_000); diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index d0c16c5a7de..791f0afda6c 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -1023,6 +1023,11 @@ function turnStartCommandResultValid(input: { ); } +type CloseCheckpointRetry = { + checkpoint: () => Promise | void; + finish: (deadline: number) => Promise; +}; + async function releaseRunnerProcessOwnership(input: { runnerSettled: boolean; checkpoint: @@ -4044,6 +4049,8 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { readonly #closedSignal: Promise; #resolveClosedSignal!: () => void; #closePromise: Promise | null = null; + #pendingCloseCheckpointRetry: CloseCheckpointRetry | null = null; + #failedCloseCheckpoint: CloseCheckpointRetry | null = null; #shutdownSettled = false; #closeFinished = false; #probeRetirement: Promise | null = null; @@ -5307,10 +5314,25 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { `runner transport close requested: ${reason.replaceAll(/[\r\n]/g, " ").slice(0, 1_000)}`, ); } + const failedCheckpoint = this.#failedCloseCheckpoint; + if (failedCheckpoint && this.#closePromise) { + this.#failedCloseCheckpoint = null; + this.#closePromise = this.#retryFailedCloseCheckpoint(failedCheckpoint); + } this.#closePromise ??= this.#closeOnce(); return this.#closePromise; } + async #retryFailedCloseCheckpoint(failed: CloseCheckpointRetry): Promise { + try { + await failed.checkpoint(); + } catch (error) { + this.#failedCloseCheckpoint = failed; + throw error; + } + await failed.finish(Date.now() + runnerCloseGraceMs(this.options)); + } + async settleCancelledTurn(input: { turnId: string; reason: string }) { const core = this.#core; if (!core || this.#controllerDetachedForRestart || this.#releaseEpisode || this.#turnStartResponsePending @@ -5444,6 +5466,8 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { catch (retirementError) { this.#diagnostic(`controller retirement after failed close is unconfirmed: ${String(retirementError)}`); } + this.#failedCloseCheckpoint = this.#pendingCloseCheckpointRetry; + this.#pendingCloseCheckpointRetry = null; throw error; } } @@ -5654,16 +5678,64 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { (finalProviderState !== "unreadable" && finalProviderState.pendingEventCount === 0 && finalProviderState.providerSettled)); + const finishClose = async (finishDeadline: number) => { + // A lost local runnerd cannot suspend, and its provider and tools were + // re-parented when it died. When runnerd's own lineage journal proves + // every one of them stopped, nothing owns the state root any more: the + // session ends as a crash stop, and recovery decides from the durable + // record how to continue. Anything less keeps the quarantine below. + const runnerLossReaped = suspensionRequired && !runnerSettled && preparationConfirmed + && !runnerSuspended && runnerLost + && await this.#reapLostLocalRunnerLineage(finishDeadline); + if (suspensionRequired && !runnerSettled && !runnerLossReaped) { + const settlement = { + runnerSuspended, + providerDrained, + suspensionState, + semanticTools: this.#core?.semanticToolSettlementDiagnostics(), + finalProviderState, + }; + try { + this.options.onDiagnostic?.(`native_session_settlement_incomplete ${JSON.stringify(settlement)}`); + } catch { + // Keep the settlement failure authoritative if its observer fails. + } + // Sample after ingress retirement and its drain. A result observed before + // that barrier cannot rule out one last admitted tool callback. + throw new NativeSessionCloseUnrecoverableError( + settlement, this.#core?.semanticToolResultsSettled() === true, + ); + } + if (!preparationConfirmed) { + throw new Error(`Native runner ${attachmentPending ? "attachment" : "startup"} cleanup is unconfirmed; recovery state retained.`); + } + this.#shutdownSettled = runnerSettled; + if (this.#ownsRoot && !adoptedRunner) { + rmSync(this.#root, { recursive: true, force: true }); + } + this.#publish(); + }; + const checkpoint = adoptedRunner && !this.#adoptedRunnerAuthenticated + ? null + : this.#controlPlaneCheckpoint; + const release = this.#controlPlaneRelease; + let checkpointFailed = false; + let releaseFailed = false; + let processStopFailed = false; try { await releaseRunnerProcessOwnership({ runnerSettled, // An alive PID does not authorize controlling or replacing a runner // that never authenticated to this controller (for example after an // executable upgrade). Retain its prior checkpoint without rewriting it. - checkpoint: - adoptedRunner && !this.#adoptedRunnerAuthenticated - ? null - : this.#controlPlaneCheckpoint, + checkpoint: checkpoint && (async (settlement) => { + try { + await checkpoint(settlement); + } catch (error) { + checkpointFailed = true; + throw error; + } + }), forceKill: async () => { const handle = this.#handle; if (!handle || this.#evidence.runnerExited) return; @@ -5672,54 +5744,41 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { // Do not release the session for reuse until its process monitor has // settled: the successor would otherwise overwrite that ownership // marker while the previous runner still holds the fixed listener. - const result = await waitForProcess(handle, 15_000); + let result: Awaited>; + try { + result = await waitForProcess(handle, 15_000); + } catch (error) { + processStopFailed = true; + throw error; + } this.#evidence.runnerExited = true; this.#evidence.runnerExitCode = result.code; this.#evidence.runnerSignal = result.signal as NodeJS.Signals | null; }, - release: this.#controlPlaneRelease, + release: release && (async () => { + try { + await release(); + } catch (error) { + releaseFailed = true; + throw error; + } + }), retireController: () => this.#stopAndDrainAuthority(closeDeadline), }); + } catch (error) { + if (checkpoint && checkpointFailed && !releaseFailed && !processStopFailed) { + this.#pendingCloseCheckpointRetry = { + checkpoint: () => checkpoint(runnerSettled ? "settled" : "unsettled"), + finish: finishClose, + }; + } + throw error; } finally { await this.#core?.stop(); this.#controlPlaneCheckpoint = null; this.#controlPlaneRelease = null; } - // A lost local runnerd cannot suspend, and its provider and tools were - // re-parented when it died. When runnerd's own lineage journal proves - // every one of them stopped, nothing owns the state root any more: the - // session ends as a crash stop, and recovery decides from the durable - // record how to continue. Anything less keeps the quarantine below. - const runnerLossReaped = suspensionRequired && !runnerSettled && preparationConfirmed - && !runnerSuspended && runnerLost - && await this.#reapLostLocalRunnerLineage(closeDeadline); - if (suspensionRequired && !runnerSettled && !runnerLossReaped) { - const settlement = { - runnerSuspended, - providerDrained, - suspensionState, - semanticTools: this.#core?.semanticToolSettlementDiagnostics(), - finalProviderState, - }; - try { - this.options.onDiagnostic?.(`native_session_settlement_incomplete ${JSON.stringify(settlement)}`); - } catch { - // Keep the settlement failure authoritative if its observer fails. - } - // Sample after ingress retirement and its drain. A result observed before - // that barrier cannot rule out one last admitted tool callback. - throw new NativeSessionCloseUnrecoverableError( - settlement, this.#core?.semanticToolResultsSettled() === true, - ); - } - if (!preparationConfirmed) { - throw new Error(`Native runner ${attachmentPending ? "attachment" : "startup"} cleanup is unconfirmed; recovery state retained.`); - } - this.#shutdownSettled = runnerSettled; - if (this.#ownsRoot && !adoptedRunner) { - rmSync(this.#root, { recursive: true, force: true }); - } - this.#publish(); + await finishClose(closeDeadline); } async #prepareOwnedProvider( diff --git a/server/src/services/native-runtime/native-harness-backup-storage.ts b/server/src/services/native-runtime/native-harness-backup-storage.ts index 6df1d5f2749..09a050ab3f0 100644 --- a/server/src/services/native-runtime/native-harness-backup-storage.ts +++ b/server/src/services/native-runtime/native-harness-backup-storage.ts @@ -13,6 +13,7 @@ import type { StorageService } from "../../storage/types.js"; import { lockNativeRunnerCheckpointOwner, validateNativeRunnerCheckpointOwner, type NativeRunnerCheckpointFenceOwner } from "./native-runner-checkpoint.js"; import { loadConfig } from "../../config.js"; import { getStorageService } from "../../storage/index.js"; +import { storageOutageWaitFor, waitOutStorageOutages } from "../../storage/storage-unavailable.js"; import { readNativeHarnessBackupStamp, verifyNativeHarnessBackupStamp } from "./native-harness-backup-stamp.js"; import { captureNativeHarnessArchive, restoreNativeHarnessArchive, MAX_NATIVE_HARNESS_OBJECT_BYTES } from "./native-harness-backup-archive.js"; import { removeNativeHarnessBackup } from "./native-harness-backup-cleanup.js"; @@ -193,12 +194,18 @@ export async function assertNativeHarnessBackupOwner(db: Db, owner: NativeRunner await db.transaction(tx => fence(tx, owner)); } -export async function persistNativeHarnessBackup(input: { +type PersistNativeHarnessBackupInput = { db: Db; storage: StorageService; owner: NativeRunnerCheckpointFenceOwner | OfflineOwner | SettledControllerArchiveOwner | SettledNativeHarnessBackupOwner; scopeDigest: string; root: string; signal?: AbortSignal; maxArchiveBytes?: number; inactiveSource?: { normalizedSessionId: string; runnerInstanceId: string; providerLeaseId: string }; providerArtifacts?: NativeProviderArtifactSource; -}): Promise { +}; + +export function persistNativeHarnessBackup(input: PersistNativeHarnessBackupInput): Promise { + return waitOutStorageOutages(() => storageOutageWaitFor("saving the provider session", () => persistNativeHarnessBackupOnce(input))); +} + +async function persistNativeHarnessBackupOnce(input: PersistNativeHarnessBackupInput): Promise { if (!/^[a-f0-9]{64}$/.test(input.scopeDigest)) fail("scope_invalid"); if ("kind" in input.owner && input.owner.kind === "settled_native_harness_backup" && (input.scopeDigest !== input.owner.scopeDigest || input.root !== input.owner.root)) fail("preservation_source_changed"); diff --git a/server/src/services/native-runtime/native-harness-backup-throttle.integration.test.ts b/server/src/services/native-runtime/native-harness-backup-throttle.integration.test.ts index f5b148d5484..b6466a86108 100644 --- a/server/src/services/native-runtime/native-harness-backup-throttle.integration.test.ts +++ b/server/src/services/native-runtime/native-harness-backup-throttle.integration.test.ts @@ -142,4 +142,51 @@ describeEmbeddedPostgres("durable native provider backups under an object-storag await new Promise(resolve => server.close(() => resolve())); } }); + + it("waits out a throttle that outlasts one request's backoff instead of losing the backup", async () => { + const f = await fixture(); + const objects = new Map(), refusals = new Map(); + const server = createServer((request, response) => { + const key = new URL(request.url!, "http://localhost").pathname; + const chunks: Buffer[] = []; + request.on("data", chunk => chunks.push(chunk)); + request.on("end", () => { + if (request.method === "PUT") { + const refused = refusals.get(key) ?? 0; + if (refused < 9) { + refusals.set(key, refused + 1); + response.writeHead(503, { "Content-Type": "application/xml" }).end( + "SlowDownPlease reduce your request rate.throttled"); + return; + } + objects.set(key, Buffer.concat(chunks)); + response.writeHead(200, { ETag: `"${createHash("md5").update(objects.get(key)!).digest("hex")}"` }).end(); + } else if (request.method === "GET" || request.method === "HEAD") { + const body = objects.get(key); + if (!body) { response.writeHead(404, { "Content-Type": "application/xml" }).end("NoSuchKey"); return; } + response.writeHead(200, { "Content-Length": body.length, ETag: `"${createHash("md5").update(body).digest("hex")}"`, + "Content-Type": "application/octet-stream" }).end(request.method === "GET" ? body : undefined); + } else if (request.method === "DELETE") { + objects.delete(key); response.writeHead(204).end(); + } else response.writeHead(500).end(); + }); + }); + await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); }); + vi.stubEnv("AWS_ACCESS_KEY_ID", "fixture"); vi.stubEnv("AWS_SECRET_ACCESS_KEY", "fixture"); + const random = vi.spyOn(Math, "random").mockReturnValue(0); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const storage = createStorageService(createS3StorageProvider({ bucket: "bucket", region: "us-east-1", forcePathStyle: true, + endpoint: `http://127.0.0.1:${(server.address() as AddressInfo).port}` })); + try { + await persistNativeHarnessBackup({ ...f, storage }); + expect([...refusals.values()]).toEqual([9]); + const [current] = await f.db.select().from(nativeHarnessBackups).where(and(eq(nativeHarnessBackups.scopeDigest, f.scopeDigest), + eq(nativeHarnessBackups.status, "current"))); + expect(current).toBeDefined(); + } finally { + random.mockRestore(); warn.mockRestore(); + server.closeAllConnections(); + await new Promise(resolve => server.close(() => resolve())); + } + }, 60_000); }); diff --git a/tests/restart-chaos/README.md b/tests/restart-chaos/README.md index e99224fcf98..e96feb427fd 100644 --- a/tests/restart-chaos/README.md +++ b/tests/restart-chaos/README.md @@ -559,11 +559,12 @@ method and status are written to `storage-proxy.json`. | ST5 | credentials rejected: every request answers 403 `ExpiredToken`, `InvalidAccessKeyId` or `SignatureDoesNotMatch` (seeded per window) | | ST5R | real key rotation: MinIO restarts with a new root key (old key revoked), and the server's credential source keeps serving the old key until the window ends | | ST7 | read-after-write lag: a `GET` or `HEAD` of an object answers 404 `NoSuchKey` for 5–30 s (seeded) after its `PUT` or multipart completion succeeded | +| ST8 | provider-session backup throttle: the next 9–12 (seeded) `PUT`s of a native harness backup answer 503 `SlowDown`, more than one request's own throttled retries. This is the post-turn close checkpoint of a remote (Daytona) run, so use it with `--env daytona --storage s3` | -With ST4 or ST7 in the wave, the harness audits the store when the wave ends (`storage-audit.json` and a +With ST4, ST7 or ST8 in the wave, the harness audits the store when the wave ends (`storage-audit.json` and a `Storage audit` section in `SUMMARY.md`). It reads every committed workspace snapshot back from MinIO and checks its size and SHA-256 against the snapshot row, and after the server stops it lists incomplete multipart uploads -under the wave's prefix. An orphaned upload, a committed snapshot that does not read back, a planned ST4 or ST7 fault +under the wave's prefix. An orphaned upload, a committed snapshot that does not read back, a planned ST4, ST7 or ST8 fault that never changed a request, or a skipped snapshot check fails the wave. ST4 truncation forwards the first bytes of the part to MinIO before it cuts both connections. diff --git a/tests/restart-chaos/storage-audit.ts b/tests/restart-chaos/storage-audit.ts index 452d77eb9ff..44baf9c8683 100644 --- a/tests/restart-chaos/storage-audit.ts +++ b/tests/restart-chaos/storage-audit.ts @@ -24,10 +24,11 @@ export function unexercisedFaults(kinds: readonly string[], injectedBy: Record Object.entries(injectedBy).some(([cause, count]) => count > 0 && prefixes.some(prefix => cause.startsWith(prefix))); return [...new Set(kinds)].filter(kind => (kind === "ST4" && !hit(["UploadPart:", "CompleteMultipartUpload:"])) - || (kind === "ST7" && !hit(["GetObject:read_after_write_lag", "HeadObject:read_after_write_lag"]))); + || (kind === "ST7" && !hit(["GetObject:read_after_write_lag", "HeadObject:read_after_write_lag"])) + || (kind === "ST8" && !hit(["PutObject:throttle", "UploadPart:throttle"]))); } -export const AUDITED_STORAGE_FAULTS = ["ST4", "ST7"] as const; +export const AUDITED_STORAGE_FAULTS = ["ST4", "ST7", "ST8"] as const; export function auditsStorage(options: { storage?: string; storageFaults?: readonly string[]; storageWindows?: ReadonlyArray<{ kind: string }> }): boolean { diff --git a/tests/restart-chaos/storage-chaos.ts b/tests/restart-chaos/storage-chaos.ts index a3e731783f1..c4dc2cc1f8e 100644 --- a/tests/restart-chaos/storage-chaos.ts +++ b/tests/restart-chaos/storage-chaos.ts @@ -4,7 +4,7 @@ import { bandwidthDraw } from "./storage-bandwidth.js"; import { lagFaultRules } from "./storage-lag.js"; import { multipartFaultRules } from "./storage-multipart.js"; -export const STORAGE_FAULT_KINDS = ["ST1", "ST2", "ST3", "ST4", "ST5", "ST5R", "ST7"] as const; +export const STORAGE_FAULT_KINDS = ["ST1", "ST2", "ST3", "ST4", "ST5", "ST5R", "ST7", "ST8"] as const; export type StorageFaultKind = typeof STORAGE_FAULT_KINDS[number]; export interface StorageFaultWindow { kind: StorageFaultKind; startMs: number; durationMs: number; rules: StorageFaultRule[] } @@ -30,6 +30,8 @@ export function storageFaultRules(kind: StorageFaultKind, random: () => number): case "ST4": return multipartFaultRules(random); case "ST5": case "ST5R": return credentialFaultRules(kind, random); case "ST7": return lagFaultRules(random); + case "ST8": return [{ fault: { kind: "throttle" }, methods: ["PUT"], pathIncludes: "native-harness-backups", + firstObjectOnly: true, remaining: 9 + Math.floor(random() * 4) }]; } } diff --git a/tests/restart-chaos/storage-multipart-lag.test.ts b/tests/restart-chaos/storage-multipart-lag.test.ts index 7518eb78b29..a4e136c19f7 100644 --- a/tests/restart-chaos/storage-multipart-lag.test.ts +++ b/tests/restart-chaos/storage-multipart-lag.test.ts @@ -62,6 +62,37 @@ describe("ST4 and ST7 planning", () => { expect(rule!.fault).toEqual({ kind: "read_after_write_lag", lagMs: LAG_MS_RANGE[1] }); }); + it("plans ST8 as a seeded SlowDown run on provider-session backup uploads, longer than one request's retries", async () => { + expect(storageFaultRules("ST8", () => 0)).toEqual([{ fault: { kind: "throttle" }, methods: ["PUT"], + pathIncludes: "native-harness-backups", firstObjectOnly: true, remaining: 9 }]); + expect(storageFaultRules("ST8", () => 0.99)[0]!.remaining).toBe(12); + expect(unexercisedFaults(["ST8"], { "PutObject:outage": 1 })).toEqual(["ST8"]); + expect(unexercisedFaults(["ST8"], { "PutObject:errors": 9, "UploadPart:errors": 2 })).toEqual(["ST8"]); + expect(unexercisedFaults(["ST8"], { "PutObject:throttle": 9 })).toEqual([]); + expect(auditsStorage({ storage: "s3", storageFaults: ["ST8"] })).toBe(true); + let received = 0; + const server = createServer((incoming, outgoing) => { received += 1; incoming.resume(); outgoing.writeHead(200).end(); }); + server.listen(0, "127.0.0.1"); await once(server, "listening"); + const proxy = await startStorageFaultProxy(`http://127.0.0.1:${(server.address() as { port: number }).port}`); + try { + proxy.setRules(storageFaultRules("ST8", () => 0)); + const statuses: number[] = []; + for (let attempt = 0; attempt < 10; attempt += 1) { + statuses.push((await fetch(`${proxy.endpoint}/b/c/native-harness-backups/s/id.pchn`, { method: "PUT", body: "x" })).status); + if (attempt === 0) { + expect((await fetch(`${proxy.endpoint}/b/c/native-harness-backups/s/other.pchn`, { method: "PUT", body: "x" })).status).toBe(200); + } + } + expect((await fetch(`${proxy.endpoint}/b/c/workspace-snapshots/k`, { method: "PUT", body: "x" })).status).toBe(200); + expect(statuses).toEqual([...Array(9).fill(503), 200]); + expect(received).toBe(3); + expect(proxy.counts().injectedBy).toEqual({ "PutObject:throttle": 9 }); + } finally { + await proxy.close(); + server.closeAllConnections(); server.close(); + } + }); + it("audits storage only on s3 waves that plan or replay ST4 or ST7", () => { expect(auditsStorage({ storage: "s3", storageFaults: ["ST4"] })).toBe(true); expect(auditsStorage({ storage: "s3", storageWindows: [{ kind: "ST7" }] })).toBe(true); diff --git a/tests/restart-chaos/storage-proxy.ts b/tests/restart-chaos/storage-proxy.ts index fdaa529e218..3ea8e4aac0c 100644 --- a/tests/restart-chaos/storage-proxy.ts +++ b/tests/restart-chaos/storage-proxy.ts @@ -14,7 +14,8 @@ export type StorageFault = | { kind: "expired_credentials"; code?: CredentialErrorCode } | { kind: "credential_rotation" } | { kind: "truncate"; afterBytes: number } - | { kind: "read_after_write_lag"; lagMs: number }; + | { kind: "read_after_write_lag"; lagMs: number } + | { kind: "throttle" }; export const CREDENTIAL_ERROR_CODES = ["ExpiredToken", "InvalidAccessKeyId", "SignatureDoesNotMatch"] as const; export type CredentialErrorCode = typeof CREDENTIAL_ERROR_CODES[number]; @@ -25,7 +26,7 @@ const CREDENTIAL_ERROR_MESSAGES: Record = { }; export interface StorageFaultRule { fault: StorageFault; methods?: readonly string[]; pathIncludes?: string; remaining?: number; - operations?: readonly S3Operation[]; partNumbers?: readonly number[] } + operations?: readonly S3Operation[]; partNumbers?: readonly number[]; firstObjectOnly?: boolean; pinnedObject?: string } export type StorageRequestListener = (incoming: IncomingMessage, outgoing: ServerResponse) => number | void; @@ -54,6 +55,7 @@ export function matches(rule: StorageFaultRule, method: string, url: string): bo if (rule.methods && !rule.methods.includes(method)) return false; if (rule.operations && !rule.operations.includes(s3Operation(method, url))) return false; if (rule.partNumbers && !rule.partNumbers.includes(partNumberOf(url) ?? 0)) return false; + if (rule.pinnedObject !== undefined && url.split("?")[0] !== rule.pinnedObject) return false; return !rule.pathIncludes || url.includes(rule.pathIncludes); } @@ -101,6 +103,7 @@ export async function startStorageFaultProxy(endpoint: string, random: () => num const heldMs = listener?.(incoming, outgoing) || 0; const rule = heldMs ? undefined : rules.find(candidate => matches(candidate, method, incoming.url ?? "/")); if (rule?.remaining !== undefined) rule.remaining -= 1; + if (rule?.firstObjectOnly && rule.pinnedObject === undefined) rule.pinnedObject = (incoming.url ?? "/").split("?")[0]; const fault: StorageFault = heldMs ? { kind: "latency", ms: heldMs } : rule?.fault ?? { kind: "pass" }; if (fault.kind === "latency") { const delay = fault.ms + Math.round((fault.jitterMs ?? 0) * random()); @@ -126,7 +129,8 @@ export async function startStorageFaultProxy(endpoint: string, random: () => num forward(incoming, outgoing); return; } - const injected = fault.kind === "errors" + const injected = fault.kind === "throttle" ? { status: 503, body: s3Error("SlowDown", "Please reduce your request rate.") } + : fault.kind === "errors" ? { status: fault.status ?? 503, body: fault.slowDown ? s3Error("SlowDown", "Please reduce your request rate.") : s3Error("InternalError", "Injected storage error") } : fault.kind === "read_after_write_lag" ? { status: 404, body: s3Error("NoSuchKey", "The specified key does not exist.") } : faultResponse(fault); From 8eabb13ebdb6868afd5e159350fe0660b92d6e4a Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:22:51 -0600 Subject: [PATCH 07/12] fix(recovery): retry a system-woken run once when it lost its runner before any turn (#20873) 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 native run on a remote sandbox can lose its Runner process before its same-run retry reattaches. The run then fails with `runner_remote_process_identity_unavailable` > - After saved-work recovery, the server requests one Retry by itself, but only for user wakes. System wakes (monitors, automatic assignments) rest on the visible Retry > - On staging, a monitor wake's run lost its Runner before it started any provider turn. Nothing it did could be repeated, but the task stayed blocked until a person clicked Retry > - This pull request lets that one case continue automatically, once, under the run's responsible user > - The benefit is that a system-woken task whose run never reached a provider turn continues without a person ## Linked Issues or Issue Description **What happened?** On staging, a monitor wake (`issue_monitor_due`) started a remote native run. Its `session.snapshot` command timed out before any turn. The same-run retry found the Runner process gone (`process_not_running`, lifecycle `ready`) and the run failed with `runner_remote_process_identity_unavailable`. The run had no turn event and no tool event. Saved-work recovery recovered the files, but `requestInterruptedNativeTurnRetry` refused with `not_user_request`, so the task stayed blocked on a manual Retry. **What did you expect to happen?** When the run proves that it did no provider turn, the server requests the Retry once by itself, as it does for user wakes. **Steps to reproduce** 1. A system wake starts a remote native run. 2. The run fails before any turn event, and the same-run retry finds the Runner gone. 3. Saved-work recovery completes. No Retry is requested; the task waits for a person. Refs #20872, #20853 ## What Changed The rule that changed, exactly: in `requestInterruptedNativeTurnRetry` (`server/src/services/heartbeat/restart-interrupted-turn.ts`), a run whose wake was not requested by a user used to stop with `not_user_request` in all cases. Now it requests the task Retry only when all of these are true: - the run failed with one of the existing reattachment-loss codes (unchanged gate); - a positive durable record proves that no turn was ever issued: the run's last `native.remote_runner_recovery_failed` event carries `remoteRunnerRecovery` with `stage: process_verification`, `reason: process_not_running` and `providerTurnIssued: false`; - the run also recorded no turn event and no tool event; - the run has a `responsibleUserId`; the Retry runs under that user; - the run is not itself a `task_retry` run; - the task is still open and assigned to the same agent (unchanged gate). An absence of run events is never enough: a turn can reach the provider before its events are stored (Greptile, first review). - New `withRemoteRunnerTurnProof` (`native-session-executor.ts`): when a same-run reattachment is refused because the sandbox proved the Runner process gone (exit 45, not an unreachable sandbox), the executor reads the run's controller journal. The controller records each turn command there before it sends it. Only when `runnerdStateProvesNoRemoteProviderTurn` holds (just `run.prepare`/`session.open` and maintenance commands such as `session.snapshot`, and only session-open events) does it add `providerTurnIssued: false` to the diagnostic. This is the same proof that restart recovery already uses for `bootstrap_incomplete`. `RemoteRunnerRecoveryDiagnostic` keeps the field only as `false`. - Which staging shapes this covers: a run whose journal holds no turn command. Whether c14bab19 (the `session.snapshot` timeout) qualifies depends on its controller journal, which staging does not expose; if its journal held a `turn.start`, it stays on the manual Retry floor. 32376b3a (`turn.submitted`, then a `turn.start` timeout) always stays on the floor. - Everything else about system wakes is unchanged: without the journal proof, with any turn or tool event, or without a responsible user, a system wake still rests on the visible Retry. - Bounded: the Retry uses the existing idempotency key `restart-interrupted-turn:`, so it is requested at most once per run. Its successor is a user-attributed `task_retry` run, so if that run also loses its Runner, the existing `automatic_retry_used` rule leaves it on the visible Retry. No loop is possible. - Attribution: `requestTaskRetry` records `issue.retry_requested` with actor `restart-recovery` on behalf of the run's responsible user. Admission keeps every gate (saved-work recovery, stop proof, approvals, pause, budget, ownership). - Tests in `server/src/services/workspace-recovery-retry-copyback.test.ts`: a positive case (monitor wake, Runner proven gone, journal proof), including the second-loss `automatic_retry_used` check. Negative cases: no run events but no journal proof (the Greptile shape), a settled turn, a tool event, no responsible user. - New `server/src/services/native-runtime/remote-runner-turn-proof.test.ts`: the proof is recorded only for a journal of session commands; not for a `turn.start` command, a committed turn event, an unreadable journal, or an unreachable sandbox (`probe_transport_failed`). - `doc/execution-semantics.md`: describes the rule. ## Verification - `cd server && pnpm exec vitest run src/services/workspace-recovery-retry-copyback.test.ts`: 83 passed. - Red on master (product hunk removed): the positive case fails with `expected { requested: false, … } to match object { requested: true }`. - Red on the first head (a244ad3b): the "no run events but no journal proof" case is requested automatically; CI's `run-completion.test.ts` ("replays saved user intent … system_wake") failed for the same reason. Both pass now. - `pnpm exec vitest run src/services/native-runtime/remote-runner-turn-proof.test.ts`: 4 passed. `native-session-executor.test.ts`, `run-completion.test.ts`, `runtime-execution.test.ts`: 1571 tests passed (one local `afterAll` hook timeout under load). - `cd server && pnpm exec tsc --noEmit -p tsconfig.json`: passes. ## Risks - Low to medium. A system-woken task can now start one new run without a person. This happens only when the controller journal proves that no turn command was ever issued, so no provider work or tool side effect from that run can be repeated. The Retry starts a fresh provider session, like a manual Retry. - The Retry runs with the run's responsible user's authority. That user already authorized the failed run. If the user lost access, `requestTaskRetry` refuses and the visible Retry remains. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution in an agent harness. ## 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 --- doc/execution-semantics.md | 10 +++- .../heartbeat/restart-interrupted-turn.ts | 46 +++++++++++++--- .../native-runtime/native-session-executor.ts | 28 ++++++++-- .../remote-runner-recovery-diagnostics.ts | 5 +- .../remote-runner-turn-proof.test.ts | 52 +++++++++++++++++++ .../workspace-recovery-retry-copyback.test.ts | 37 ++++++++++--- 6 files changed, 158 insertions(+), 20 deletions(-) create mode 100644 server/src/services/native-runtime/remote-runner-turn-proof.test.ts diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 6f1334faebd..f86cdf04cf0 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -1725,7 +1725,15 @@ assigned the task, or clicked Retry. It does this only when the run recorded no provider turn or its last provider turn is settled. Activity records the request as `restart-recovery` on behalf of that user. Admission keeps every gate: saved-work recovery, stop proof, approvals, pauses, budget and ownership. A Retry that the -server requested gets no second automatic attempt. System wakes and runs with an +server requested gets no second automatic attempt. A system wake (for example a +monitor or an automatic assignment) continues this way only with a positive +record that no turn was ever issued: the refused reattachment proved the Runner +process gone, and the run's controller journal, which records each turn command +before it is sent, holds no turn command and no turn event +(`providerTurnIssued: false` on `native.remote_runner_recovery_failed`). The run +must also have no turn or tool event, and the Retry runs under the run's +responsible user. Missing events alone never qualify, because a turn can reach +the provider before its events are stored. Other system wakes and runs with an in-flight provider turn do not continue automatically. For these failed runs, a recovered workspace hold offers Retry (`canRetry`) and says "Retry or send a message to continue." An intentional Stop keeps "send a message" as its only diff --git a/server/src/services/heartbeat/restart-interrupted-turn.ts b/server/src/services/heartbeat/restart-interrupted-turn.ts index a1458a27826..16564be7238 100644 --- a/server/src/services/heartbeat/restart-interrupted-turn.ts +++ b/server/src/services/heartbeat/restart-interrupted-turn.ts @@ -36,6 +36,29 @@ export function isProvenTurnSettlement(event: { eventType: string; payload: unkn asRecord(asRecord(payload.prpEvent).payload).providerTerminalObserved !== false; } +/** Any turn or tool event: the run may have done provider work that a new turn could repeat. */ +const PROVIDER_TURN_ACTIVITY_EVENTS = [...TURN_STARTED_EVENTS, ...TURN_SETTLED_EVENTS, + "tool.execution.started", "tool.execution.completed"]; + +/** + * The run's last refused reattachment proved its Runner process gone and its + * controller journal proved that no turn command was ever issued + * (`providerTurnIssued: false`, recorded by the executor). No turn or tool + * event may exist either. + */ +async function hasProvenNoProviderTurn(db: Db, run: { companyId: string; id: string }) { + const [activity] = await db.select({ id: heartbeatRunEvents.id }).from(heartbeatRunEvents).where(and( + eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id), + inArray(heartbeatRunEvents.eventType, PROVIDER_TURN_ACTIVITY_EVENTS))).limit(1); + if (activity) return false; + const [refusal] = await db.select({ payload: heartbeatRunEvents.payload }).from(heartbeatRunEvents).where(and( + eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id), + eq(heartbeatRunEvents.eventType, "native.remote_runner_recovery_failed"), + )).orderBy(desc(heartbeatRunEvents.seq)).limit(1); + const proof = asRecord(asRecord(refusal?.payload).remoteRunnerRecovery); + return proof.stage === "process_verification" && proof.reason === "process_not_running" && proof.providerTurnIssued === false; +} + /** Automatic continuation is requested at most once per chain of runs. */ export const RESTART_RETRY_KEY_PREFIX = "restart-interrupted-turn:"; @@ -47,7 +70,9 @@ type Outcome = { requested: true; requestId: string } | { requested: false; reas * request the same Retry a user would click, once and idempotently per run, * under the requesting user's authority. Only when the run's user input was not * yet acted on, or its last provider turn is settled; an in-flight turn's - * outcome is unknown, so it keeps the visible Retry. Admission keeps every gate, + * outcome is unknown, so it keeps the visible Retry. A system wake continues + * this way only when the controller journal proved that no turn was ever + * issued, under the run's responsible user. Admission keeps every gate, * including stop proof and saved-work recovery before the next turn. */ export async function requestRestartInterruptedTurnRetry(db: Db, claim: NativeRestartRecoveryClaim): Promise { @@ -71,11 +96,19 @@ export async function requestInterruptedNativeTurnRetry(db: Db, runId: string): const [wake] = await db.select().from(agentWakeupRequests).where(and( eq(agentWakeupRequests.companyId, run.companyId), eq(agentWakeupRequests.agentId, run.agentId), eq(agentWakeupRequests.id, run.wakeupRequestId), eq(agentWakeupRequests.runId, run.id))); - const actorId = wake?.requestedByActorType === "user" ? wake.requestedByActorId : null; + const userActorId = wake?.requestedByActorType === "user" ? wake.requestedByActorId : null; const reason = typeof context.wakeReason === "string" ? context.wakeReason : wake?.reason; - // System wakes keep their policy: only a new user turn continues them. - if (!actorId) return { requested: false, reason: "not_user_request" }; - if (reason === "task_retry") { + let actorId = userActorId; + if (!userActorId) { + // System wakes keep their policy (only a new user turn continues them), + // except when the controller journal positively proves that no turn was + // ever issued: nothing the run did can be repeated, so the Retry runs once + // under the run's responsible user. Missing events alone prove nothing, + // because a turn can reach the provider before its events are stored. + if (!wake || reason === "task_retry" || !run.responsibleUserId || !await hasProvenNoProviderTurn(db, run)) + return { requested: false, reason: "not_user_request" }; + actorId = run.responsibleUserId; + } else if (reason === "task_retry") { // A Retry this hook already requested gets no second automatic attempt. const retryId = typeof context.taskRetryRequestId === "string" ? context.taskRetryRequestId : null; const [receipt] = retryId ? await db.select({ key: agentWakeupRequests.idempotencyKey }).from(agentWakeupRequests).where(and( @@ -88,10 +121,11 @@ export async function requestInterruptedNativeTurnRetry(db: Db, runId: string): const [comment] = commentId ? await db.select({ id: issueComments.id }).from(issueComments).where(and( eq(issueComments.companyId, run.companyId), eq(issueComments.issueId, issueId), sql`${issueComments.id}::text = ${commentId}`, eq(issueComments.authorType, "user"), - eq(issueComments.authorUserId, actorId), isNull(issueComments.deletedAt), isNull(issueComments.createdByRunId), + eq(issueComments.authorUserId, userActorId), isNull(issueComments.deletedAt), isNull(issueComments.createdByRunId), )) : []; if (!comment && reason !== "issue_assigned") return { requested: false, reason: "message_unavailable" }; } else return { requested: false, reason: "not_user_request" }; + if (!actorId) return { requested: false, reason: "not_user_request" }; const [issue] = await db.select({ status: issues.status, assigneeAgentId: issues.assigneeAgentId }).from(issues) .where(and(eq(issues.companyId, run.companyId), eq(issues.id, issueId))); if (!issue || issue.assigneeAgentId !== run.agentId || ["done", "cancelled"].includes(issue.status)) diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index add78046e35..c46e7976c96 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -6252,11 +6252,15 @@ async function migrateRunnerdStateRootForExecution(input: { await verifyPluginRunnerTaskReattachment(target.runnerTask, identity); return; } - await verifyRemoteRunnerOrSettledExit({ - claim: input.restartRecovery, target: input.runnerExecutionTarget, identity, - runId: input.execution.binding.runId, normalizedSessionId: nativeSessionKey(input.execution), - providerAttempt: input.restartRecovery.providerAttempt, - }); + try { + await verifyRemoteRunnerOrSettledExit({ + claim: input.restartRecovery, target: input.runnerExecutionTarget, identity, + runId: input.execution.binding.runId, normalizedSessionId: nativeSessionKey(input.execution), + providerAttempt: input.restartRecovery.providerAttempt, + }); + } catch (error) { + throw withRemoteRunnerTurnProof(error, scoped); + } return; } if (durableIdentityMatchesExecution(identity, input.execution)) { @@ -6858,6 +6862,20 @@ export async function stopStaleRemoteRunnerBeforeBootstrap(input: { } } +/** + * A refused reattachment whose Runner process is proven gone records whether + * this run's controller journal proves that no turn command was ever issued. + * The controller writes each turn command there before sending it, so only + * that positive record (never an absence of run events) allows an automatic + * relaunch that cannot repeat provider work. + */ +export function withRemoteRunnerTurnProof(error: unknown, root: string): unknown { + const diagnostic = readRemoteRunnerRecoveryError(error); + if (diagnostic?.stage !== "process_verification" || diagnostic.reason !== "process_not_running" || + !runnerdStateProvesNoRemoteProviderTurn(root)) return error; + return attachRemoteRunnerRecoveryDiagnostic(error, { ...diagnostic, providerTurnIssued: false }); +} + /** The remote controller record proves its runner was never sent a turn. */ export function runnerdStateProvesNoRemoteProviderTurn(root: string): boolean { try { diff --git a/server/src/services/native-runtime/remote-runner-recovery-diagnostics.ts b/server/src/services/native-runtime/remote-runner-recovery-diagnostics.ts index 78d660b5bfc..cd6b7710842 100644 --- a/server/src/services/native-runtime/remote-runner-recovery-diagnostics.ts +++ b/server/src/services/native-runtime/remote-runner-recovery-diagnostics.ts @@ -21,6 +21,8 @@ export interface RemoteRunnerRecoveryDiagnostic { reason: typeof reasons[number]; runnerLifecycle?: typeof runnerLifecycles[number]; runnerSettled?: boolean; + /** Present only as `false`: the controller journal proves no turn command was ever issued. */ + providerTurnIssued?: false; } export function describeExitedRemoteRunner(state: Record): Pick; + const { stage, reason, runnerLifecycle, runnerSettled, providerTurnIssued } = value as Record; if (!stages.some(candidate => candidate === stage) || !reasons.some(candidate => candidate === reason)) return null; return { stage, reason, ...(runnerLifecycles.some(candidate => candidate === runnerLifecycle) ? { runnerLifecycle } : {}), ...(typeof runnerSettled === "boolean" ? { runnerSettled } : {}), + ...(providerTurnIssued === false ? { providerTurnIssued } : {}), } as RemoteRunnerRecoveryDiagnostic; } catch { return null; diff --git a/server/src/services/native-runtime/remote-runner-turn-proof.test.ts b/server/src/services/native-runtime/remote-runner-turn-proof.test.ts new file mode 100644 index 00000000000..ff585e5058d --- /dev/null +++ b/server/src/services/native-runtime/remote-runner-turn-proof.test.ts @@ -0,0 +1,52 @@ +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { withRemoteRunnerTurnProof } from "./native-session-executor.js"; +import { RemoteRunnerRecoveryError, readRemoteRunnerRecoveryError } from "./remote-runner-recovery-diagnostics.js"; + +const roots: string[] = []; +afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); }); + +async function journal(commands: Array<{ type: string; status: string }>, eventTypes = ["session.started"]) { + const root = await mkdtemp(path.join(os.tmpdir(), "turn-proof-")); + roots.push(root); + await mkdir(path.join(root, "control-plane"), { recursive: true }); + await writeFile(path.join(root, "control-plane", "control-plane-state.json"), JSON.stringify({ + schema: "paperclip.runner.durable.control-plane-state.v2", connectionCount: 1, + commands, committedEvents: eventTypes.map((eventType, index) => ({ sourceSeq: index + 1, eventType })), + ackedSourceSeq: eventTypes.length, + })); + return root; +} +const exited = () => new RemoteRunnerRecoveryError({ stage: "process_verification", reason: "process_not_running", + runnerLifecycle: "ready", runnerSettled: false }); + +// Staging class T: the Runner process was proven gone. Only the controller +// journal, which records each turn command before sending it, can prove no +// turn was issued; an absence of run events cannot. +describe("withRemoteRunnerTurnProof", () => { + it("records the proof when the journal holds only session commands", async () => { + const root = await journal([{ type: "run.prepare", status: "completed" }, { type: "session.open", status: "completed" }, + { type: "session.snapshot", status: "pending" }]); + expect(readRemoteRunnerRecoveryError(withRemoteRunnerTurnProof(exited(), root))).toMatchObject({ + reason: "process_not_running", providerTurnIssued: false }); + }); + + it.each([ + ["a turn command was issued", [{ type: "session.open", status: "completed" }, { type: "turn.start", status: "pending" }], ["session.started"]], + ["a turn event was committed", [{ type: "session.open", status: "completed" }], ["session.started", "turn.started"]], + ])("records nothing when %s", async (_label, commands, events) => { + const root = await journal(commands, events); + expect(readRemoteRunnerRecoveryError(withRemoteRunnerTurnProof(exited(), root))).not.toHaveProperty("providerTurnIssued"); + }); + + it("records nothing without a readable journal or without a proven exit", async () => { + const empty = await mkdtemp(path.join(os.tmpdir(), "turn-proof-")); + roots.push(empty); + expect(readRemoteRunnerRecoveryError(withRemoteRunnerTurnProof(exited(), empty))).not.toHaveProperty("providerTurnIssued"); + const root = await journal([{ type: "session.open", status: "completed" }]); + const unreachable = new RemoteRunnerRecoveryError({ stage: "process_verification", reason: "probe_transport_failed" }); + expect(readRemoteRunnerRecoveryError(withRemoteRunnerTurnProof(unreachable, root))).not.toHaveProperty("providerTurnIssued"); + }); +}); diff --git a/server/src/services/workspace-recovery-retry-copyback.test.ts b/server/src/services/workspace-recovery-retry-copyback.test.ts index 39bbad5f77b..def29ff74d5 100644 --- a/server/src/services/workspace-recovery-retry-copyback.test.ts +++ b/server/src/services/workspace-recovery-retry-copyback.test.ts @@ -114,6 +114,17 @@ describe("automatic retained workspace recovery", () => { } const queuedSuccessors = async (companyId: string) => db.select().from(heartbeatRuns) .where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.status, "queued"))); + async function systemWake(f: Awaited>, proof?: { providerTurnIssued?: false }) { + await db.update(agentWakeupRequests).set({ requestedByActorType: "system", requestedByActorId: null, + reason: "issue_monitor_due" }).where(eq(agentWakeupRequests.id, f.wake.id)); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, wakeReason: "issue_monitor_due" } }) + .where(eq(heartbeatRuns.id, f.runId)); + // The executor's refused reattachment (see withRemoteRunnerTurnProof). + if (proof) await appendHeartbeatRunEvent(db, { companyId: f.companyId, runId: f.runId, agentId: f.agentId, + eventType: "native.remote_runner_recovery_failed", stream: "system", level: "error", message: "Could not verify the existing remote runner.", + payload: { remoteRunnerRecovery: { stage: "process_verification", reason: "process_not_running", + runnerLifecycle: "ready", runnerSettled: false, ...proof } } }); + } it.each([ { title: "the first attachment found the previous runner gone", turn: "none" as const, error: "runner_remote_process_identity_unavailable", initial: true }, @@ -122,8 +133,14 @@ describe("automatic retained workspace recovery", () => { { title: "a same-run retry found the settled turn's remote runner gone", turn: "settled" as const, error: "runner_remote_process_identity_unavailable", initial: false }, { title: "a same-run retry found the settled turn's sandbox lease gone", turn: "settled" as const, error: "native_remote_recovery_lease_mismatch", initial: false }, { title: "a same-run retry named the lease check that failed", turn: "settled" as const, error: "native_remote_recovery_lease_mismatch: stage=environment_acquire field=lease_status", initial: false }, - ])("continues a user turn once, without a second message, after $title and recovery saved the work", async ({ turn, error, initial }) => { + // Staging class T (c14bab19): a monitor wake's session snapshot timed out + // before any turn, then the same-run retry found the Runner gone. Its + // controller journal proved no turn command was ever issued, so nothing can + // be repeated and the run's responsible user's Retry continues it once. + { title: "a system wake's run found its runner gone and its journal proved no turn", turn: "none" as const, error: "runner_remote_process_identity_unavailable", initial: false, system: true }, + ])("continues a user turn once, without a second message, after $title and recovery saved the work", async ({ turn, error, initial, system }) => { const f = await restartAllocationLostSource(turn, error); + if (system) await systemWake(f, { providerTurnIssued: false }); const service = heartbeatService(db, { environmentRuntime: f.environmentRuntime }); // Keep the agent's only slot busy so the successor stays observable as queued. await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running" }); @@ -164,18 +181,24 @@ describe("automatic retained workspace recovery", () => { it.each([ { title: "its provider turn was still in flight", change: "turn" }, { title: "its provider turn ended without an observed provider terminal", change: "unproven" }, - { title: "the source was a system wake", change: "system" }, + { title: "the source was a system wake whose provider turn settled", change: "system" }, + // No run events is not proof: a turn can reach the provider before its + // events are stored. Only the controller journal can prove it. + { title: "the source was a system wake with no run events but no journal proof", change: "system_unproven" }, + { title: "the source was a system wake whose run used a tool before its turn event", change: "system_tool" }, + { title: "the source was a system wake whose run had no responsible user", change: "system_unowned" }, { title: "the failure was not a lost runner or allocation", change: "error" }, // Staging class P: the new sandbox had no Runner state to resume the saved // provider session. The Runner now names it, so the run ends with the // permanent code and Retry continues in a fresh provider session. { title: "the Runner had no saved state to resume the provider session", change: "unrestorable" }, ])("does not continue automatically when $title, and offers a Retry that works on first use", async ({ change }) => { - const f = await restartAllocationLostSource(change === "turn" ? "in_flight" : change === "unproven" ? "unproven" : "none"); - if (change === "system") await db.update(agentWakeupRequests).set({ requestedByActorType: "system", requestedByActorId: null, - reason: "issue_children_completed" }).where(eq(agentWakeupRequests.id, f.wake.id)); - if (change === "system") await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, wakeReason: "issue_children_completed" } }) - .where(eq(heartbeatRuns.id, f.runId)); + const f = await restartAllocationLostSource(change === "turn" ? "in_flight" : change === "unproven" ? "unproven" + : change === "system" ? "settled" : "none"); + if (change.startsWith("system")) await systemWake(f, change === "system_unproven" ? undefined : { providerTurnIssued: false }); + if (change === "system_tool") await appendHeartbeatRunEvent(db, { companyId: f.companyId, runId: f.runId, + agentId: f.agentId, eventType: "tool.execution.started", stream: "system", level: "info", message: "tool" }); + if (change === "system_unowned") await db.update(heartbeatRuns).set({ responsibleUserId: null }).where(eq(heartbeatRuns.id, f.runId)); if (change === "error") await db.update(heartbeatRuns).set({ error: "native_provider_terminal_failed" }).where(eq(heartbeatRuns.id, f.runId)); if (change === "unrestorable") await db.update(heartbeatRuns).set({ errorCode: "native_provider_state_incompatible", error: "native_session_recovery_failed: NativeRunnerResumeStateUnavailableError: PRP provider resume state is unavailable" }) From e601f9d2fcf349025391bab3783fb34b9b929b10 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:29:59 -0600 Subject: [PATCH 08/12] fix(runner): answer each OpenCode MCP tool call on its own connection (#20886) 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 Paperclip runner runs native OpenCode agents. OpenCode calls Paperclip tools through a local MCP bridge in the OpenCode proxy. OpenCode runs on Bun and uses Bun `fetch` for each MCP request. > - In one chat eval, the model made two parallel tool calls. The bridge produced and wrote both results in about 0.55 s. OpenCode received only one of them. > - The other call waited until Bun's default fetch timeout fired, about five minutes later. The chat turn lost five minutes, and the eval missed its deadline. > - The most likely trigger is the reuse of an idle keep-alive socket. We could not reproduce the loss locally, so this pull request is hardening that is based on a hypothesis. > - This pull request makes the bridge answer every request on its own connection. It also records how each tool result left the bridge, so a recurrence can be attributed from the run log. > - The benefit is that a pooled socket can no longer strand a tool result. If a call is stranded again, the run log shows whether the bridge wrote the answer. ## Linked Issues or Issue Description No public issue exists. Related: Refs #18751 (draft native client acceptance diagnostic), Refs #19546 (abandoned queued calls), Refs #20862 (transport event delivery; it does not touch this path). **What happened** In CI run `gha-42925998380` (chat-features, runner-opencode, `cases.create-case`), the CEO chat run used OpenCode 1.18.34 with an OpenRouter DeepSeek model. At 00:01:12.16 the model issued `list_workflows` (MCP id 3) and `list_projects` (MCP id 4) in parallel. The runner emitted the dynamic tool results for id 4 at 00:01:12.468 and for id 3 at 00:01:12.714 (ok, HTTP 200). The bridge writes the HTTP response directly after that event. There is no queue between them. OpenCode completed `list_projects` at 00:01:13.113. It failed `list_workflows` only at 00:06:01.761 with `The operation timed out.` We read the bundled OpenCode source. Its MCP tool call has no timeout that produces that message: the MCP request timeout gives `-32001 Request timed out`, and the configured value is 1 h for durable calls. With the same binary in Bun mode (Bun 1.3.14), a fetch on a reused keep-alive socket that never gets an answer fails after 298 s with `TimeoutError: The operation timed out.` So Bun's default fetch timeout ended the call, and the client never consumed the written answer. The previous call (`list_agents`) answered at about 00:01:06.89, so its socket was idle for about 5.27 s when the parallel pair started. Our thesis is that call 3 reused that pooled socket, and call 4 opened a new one. **Expected behavior** When the bridge has the result of a tool call, the MCP client gets it. The client must not wait for a five-minute transport timeout. **Steps to reproduce** We did not reproduce it locally. This is the only occurrence in the retained evidence. A macOS stress test (Bun 1.3.14 client, Node 26 server with the bridge's default keep-alive, one call, then an idle time of 4.8–7.2 s, then two parallel calls, 8 pairs in parallel) completed 343 trials and about 1,029 requests with 0 lost results. The failing run was on Linux CI with Node 24. ## What Changed - `mcp-bridge.ts`: every bridge response sends `Connection: close`. The MCP client cannot reuse a pooled keep-alive socket for a later request. A loopback connect per request costs much less than the failure mode. - `mcp-bridge.ts`: each `tools/call` records one closed delivery diagnostic. This includes rejected calls (unsupported tool, invalid input, duplicate identity), which record the outcome `error` (`paperclip.opencode.tool-delivery-diagnostic/v1`) when its response closes. The fields are the call id SHA-256, the socket request index, the socket idle ms, the handler ms, the outcome (`result`, `error` or `unanswered`) and `written` (`writableFinished`). It holds no tool names, inputs or results. The limit is 256 records per bridge. - `opencode-proxy-finish-diagnostics.ts`: the proxy forwards these records to the run log as `warning` frames after session binding. It validates the exact key set and value types and drops anything else. - Tests: a new `mcp-bridge-delivery.test.ts` uses a pooling keep-alive client with the incident's call shape (one call, then two parallel calls). New forwarder cases cover the record validation. The existing finish diagnostic assertion now filters by its own schema. ## Verification - Red: with the `Connection: close` line removed, `mcp-bridge-delivery.test.ts` fails with `expected 'keep-alive' to be 'close'`. The pooling client then reuses the socket. - Green: `cd packages/paperclip-runner && pnpm exec vitest run src/drivers/opencode/mcp-bridge-delivery.test.ts src/drivers/opencode/mcp-bridge-diagnostics.test.ts src/drivers/opencode/mcp-bridge.test.ts src/cli/opencode-proxy-finish-diagnostics.test.ts src/cli/opencode-app-server-proxy.test.ts src/cli/opencode-proxy-abandoned-tool-call.test.ts` gives 6 files and 45 tests passed. - The new test asserts that all three results arrive with the correct JSON-RPC ids, that no socket is reused, and that each call records `socketRequestIndex: 1`, `outcome: "result"`, `written: true` without tool names or raw ids. A second test asserts that a client that leaves before its answer records `outcome: "unanswered"`, `written: false`. A third test asserts that a rejected call records `outcome: "error"`, `written: true`. - `tsc -p tsconfig.json --noEmit` for `packages/paperclip-runner` reports no errors in the changed files. Seven existing errors in `codex-runtime-adapter.ts` and `eval/workflow-harness.ts` come from this worktree's linked dependencies. Required CI typecheck is the source of truth. - This does not prove the production fix. A recurrence on CI will show socket reuse, idle time and `written` for the stranded call in the run log. ## Risks - Low risk. Each MCP request now opens a new loopback TCP connection. That adds well under 1 ms per call, and there is no TLS. - The `notifications/cancelled` handling and the abandoned-call abort do not change. The abort still reads `writableFinished` on response close. - One extra run-log warning for each tool call (at most 256 for each bridge). The record holds only a hash, counters and timings. - Previous-release story (upgrade-safe run state): no persisted run, session, launch or pack state changes. A bridge from the previous release keeps its behavior until the proxy restarts. - If the thesis is wrong, the five-minute stall can recur. The new records will then show `written: true` on a fresh socket and point the next investigation at OpenCode or Bun. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution in Claude Code. ## 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 --- .../opencode-proxy-finish-diagnostics.test.ts | 20 ++- .../cli/opencode-proxy-finish-diagnostics.ts | 18 +++ .../opencode/mcp-bridge-delivery.test.ts | 139 ++++++++++++++++++ .../opencode/mcp-bridge-diagnostics.test.ts | 4 +- .../src/drivers/opencode/mcp-bridge.ts | 66 ++++++++- 5 files changed, 241 insertions(+), 6 deletions(-) create mode 100644 packages/paperclip-runner/src/drivers/opencode/mcp-bridge-delivery.test.ts diff --git a/packages/paperclip-runner/src/cli/opencode-proxy-finish-diagnostics.test.ts b/packages/paperclip-runner/src/cli/opencode-proxy-finish-diagnostics.test.ts index 1ebd37fc4fb..f5631d9521c 100644 --- a/packages/paperclip-runner/src/cli/opencode-proxy-finish-diagnostics.test.ts +++ b/packages/paperclip-runner/src/cli/opencode-proxy-finish-diagnostics.test.ts @@ -91,10 +91,26 @@ it("retains the actual MCP producer's offered schema and rejected shape records" const report={reportedWorkDisposition:"done",summary:"Synthetic complete response",completionClaim:{contractRevision:"1",objectiveSatisfied:true,criteria:[],remainingWork:[]},evidence:[],verification:[]}; const result=await rpc(2,"tools/call",{name:"paperclip_finish",arguments:{...report,continuation:"SYNTHETIC_PRIVATE_INPUT"}}); expect(result.result.isError).toBe(true); - expect(frames).toHaveLength(2); - const [actualOffered,actualRejected]=frames.map(frame=>JSON.parse(frame.params.message)); + const finishFrames=frames.filter(frame=>frame.params.message.includes("finish-input-diagnostic")); + expect(finishFrames).toHaveLength(2); + const [actualOffered,actualRejected]=finishFrames.map(frame=>JSON.parse(frame.params.message)); expect(actualOffered).toEqual({...offered,schemaSha256:createHash("sha256").update(JSON.stringify(schema)).digest("hex")}); expect(actualRejected).toEqual({...actualOffered,stage:"input_rejected",callIdSha256:createHash("sha256").update("2").digest("hex"),validationCategory:"continuation",rootShape:"object",continuationShape:"string"}); expect(JSON.stringify(frames)).not.toContain("SYNTHETIC_PRIVATE_INPUT"); } finally {await bridge.close();} }); + +it("forwards closed tool delivery records after binding and drops any record that could carry tool data", () => { + const frames: unknown[] = [], forward = createOpenCodeFinishDiagnosticForwarder(frame => frames.push(frame)); + const delivery = { schema: "paperclip.opencode.tool-delivery-diagnostic/v1", callIdSha256: "d".repeat(64), + socketRequestIndex: 1, socketIdleMs: null, handlerMs: 512, outcome: "result", written: true }; + forward.diagnostic(JSON.stringify(delivery)); + expect(frames).toEqual([]); + expect(forward.bind("actual-session")).toBe(true); + for (const invalid of [{ ...delivery, result: "private" }, { ...delivery, callIdSha256: "3" }, { ...delivery, outcome: "private" }, { ...delivery, outcome: ["result"] }, + { ...delivery, socketIdleMs: -1 }, { ...delivery, handlerMs: "512" }, { ...delivery, written: "yes" }]) forward.diagnostic(JSON.stringify(invalid)); + expect(frames).toEqual([]); + forward.diagnostic(JSON.stringify({ ...delivery, socketRequestIndex: 2, socketIdleMs: 5270 })); + expect(frames).toEqual([{ method: "warning", params: { threadId: "actual-session", + message: JSON.stringify({ ...delivery, socketRequestIndex: 2, socketIdleMs: 5270 }) } }]); +}); diff --git a/packages/paperclip-runner/src/cli/opencode-proxy-finish-diagnostics.ts b/packages/paperclip-runner/src/cli/opencode-proxy-finish-diagnostics.ts index c9790efbc8b..f7d9baa926a 100644 --- a/packages/paperclip-runner/src/cli/opencode-proxy-finish-diagnostics.ts +++ b/packages/paperclip-runner/src/cli/opencode-proxy-finish-diagnostics.ts @@ -17,6 +17,11 @@ export function createOpenCodeFinishDiagnosticForwarder(send: (frame: Warning) = if (message.length > 2048) return; let value: Record; try { value = JSON.parse(message); } catch { return; } + if (value && typeof value === "object" && !Array.isArray(value) + && value.schema === "paperclip.opencode.tool-delivery-diagnostic/v1") { + if (validToolDelivery(value)) emit(value); + return; + } if (!value || typeof value !== "object" || Array.isArray(value) || value.schema !== "paperclip.opencode.finish-input-diagnostic/v1" || typeof value.schemaSha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.schemaSha256)) return; @@ -39,3 +44,16 @@ export function createOpenCodeFinishDiagnosticForwarder(send: (frame: Warning) = }, }; } + +const TOOL_DELIVERY_KEYS = "callIdSha256,handlerMs,outcome,schema,socketIdleMs,socketRequestIndex,written"; +// Delivery records carry only hashes, counters and timings. Reject anything +// else so this channel cannot forward tool inputs or results. +function validToolDelivery(value: Record): boolean { + const count = (entry: unknown) => typeof entry === "number" && Number.isSafeInteger(entry) && entry >= 0; + return Object.keys(value).sort().join(",") === TOOL_DELIVERY_KEYS + && typeof value.callIdSha256 === "string" && /^[a-f0-9]{64}$/.test(value.callIdSha256) + && count(value.socketRequestIndex) && count(value.handlerMs) + && (value.socketIdleMs === null || count(value.socketIdleMs)) + && typeof value.outcome === "string" && ["result", "error", "unanswered"].includes(value.outcome) + && typeof value.written === "boolean"; +} diff --git a/packages/paperclip-runner/src/drivers/opencode/mcp-bridge-delivery.test.ts b/packages/paperclip-runner/src/drivers/opencode/mcp-bridge-delivery.test.ts new file mode 100644 index 00000000000..74a7742792c --- /dev/null +++ b/packages/paperclip-runner/src/drivers/opencode/mcp-bridge-delivery.test.ts @@ -0,0 +1,139 @@ +import { createHash } from "node:crypto"; +import { Agent, request } from "node:http"; +import { afterEach, expect, it } from "vitest"; +import { startOpenCodeMcpBridge, type OpenCodeMcpBridge } from "./mcp-bridge.js"; + +const bridges: OpenCodeMcpBridge[] = []; +const agents: Agent[] = []; +afterEach(async () => { + for (const agent of agents.splice(0)) agent.destroy(); + await Promise.all(bridges.splice(0).map(bridge => bridge.close())); +}); + +type Answer = { status: number; connection: string | undefined; reusedSocket: boolean; body: { id: unknown; result?: { content?: Array<{ text: string }> } } }; + +// A pooling client like Bun's fetch: it reuses an idle keep-alive socket +// whenever the server leaves one open. +function call(bridge: OpenCodeMcpBridge, agent: Agent, id: number, name: string): Promise { + const body = JSON.stringify({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: {} } }); + return new Promise((resolve, reject) => { + const outgoing = request(bridge.url, { + method: "POST", agent, + headers: { Authorization: `Bearer ${bridge.secret}`, "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) }, + }, response => { + const chunks: Buffer[] = []; + response.on("data", chunk => chunks.push(chunk)); + response.on("end", () => resolve({ + status: response.statusCode ?? 0, + connection: response.headers.connection, + reusedSocket: outgoing.reusedSocket, + body: JSON.parse(Buffer.concat(chunks).toString("utf8")), + })); + response.on("error", reject); + }); + outgoing.on("error", reject); + outgoing.end(body); + }); +} + +const tools = [ + { name: "list_agents", inputSchema: { type: "object" } }, + { name: "list_workflows", inputSchema: { type: "object" } }, + { name: "list_projects", inputSchema: { type: "object" } }, +]; + +it("answers every tool call on its own connection so a pooled socket can never strand a parallel result", async () => { + const messages: string[] = []; + const bridge = await startOpenCodeMcpBridge({ + tools, + handler: async ({ tool }) => { + await new Promise(resolve => setTimeout(resolve, tool === "list_workflows" ? 40 : 10)); + return { tool }; + }, + onDiagnostic: message => { if (message.includes("tool-delivery-diagnostic")) messages.push(message); }, + }); + bridges.push(bridge); + const agent = new Agent({ keepAlive: true, maxSockets: 8 }); + agents.push(agent); + + const first = await call(bridge, agent, 2, "list_agents"); + // Let the client finish handling the first response before the parallel + // pair, as OpenCode does while the model writes its next step. + await new Promise(resolve => setTimeout(resolve, 20)); + const [workflows, projects] = await Promise.all([ + call(bridge, agent, 3, "list_workflows"), + call(bridge, agent, 4, "list_projects"), + ]); + + for (const [answer, id, tool] of [[first, 2, "list_agents"], [workflows, 3, "list_workflows"], [projects, 4, "list_projects"]] as const) { + expect(answer.status).toBe(200); + expect(answer.body.id).toBe(id); + expect(JSON.parse(answer.body.result!.content![0]!.text)).toEqual({ tool }); + expect(answer.connection).toBe("close"); + expect(answer.reusedSocket).toBe(false); + } + + await expect.poll(() => messages.length).toBe(3); + const deliveries = messages.map(message => JSON.parse(message)); + expect(deliveries.map(delivery => delivery.callIdSha256).sort()).toEqual( + ["2", "3", "4"].map(id => createHash("sha256").update(id).digest("hex")).sort(), + ); + for (const delivery of deliveries) { + expect(delivery).toEqual({ + schema: "paperclip.opencode.tool-delivery-diagnostic/v1", + callIdSha256: expect.stringMatching(/^[a-f0-9]{64}$/), + socketRequestIndex: 1, + socketIdleMs: null, + handlerMs: expect.any(Number), + outcome: "result", + written: true, + }); + } + expect(JSON.stringify(messages)).not.toMatch(/list_|"tool"/); +}); + +it("records a call whose client left before its result was written", async () => { + const messages: string[] = []; + let release!: () => void; + const held = new Promise(resolve => { release = resolve; }); + let started!: () => void; + const handlerStarted = new Promise(resolve => { started = resolve; }); + const bridge = await startOpenCodeMcpBridge({ + tools, + handler: async () => { started(); await held; return { ok: true }; }, + onDiagnostic: message => { if (message.includes("tool-delivery-diagnostic")) messages.push(message); }, + }); + bridges.push(bridge); + const controller = new AbortController(); + const abandoned = fetch(bridge.url, { + method: "POST", signal: controller.signal, + headers: { Authorization: `Bearer ${bridge.secret}`, "Content-Type": "application/json" }, + body: JSON.stringify({ jsonrpc: "2.0", id: 9, method: "tools/call", params: { name: "list_agents", arguments: {} } }), + }).catch(() => undefined); + await handlerStarted; + controller.abort(); + await abandoned; + await expect.poll(() => messages.length).toBe(1); + release(); + expect(JSON.parse(messages[0]!)).toMatchObject({ outcome: "unanswered", written: false, socketRequestIndex: 1 }); +}); + +it("records a rejected call as an answered error", async () => { + const messages: string[] = []; + const bridge = await startOpenCodeMcpBridge({ + tools, + handler: async () => ({ ok: true }), + onDiagnostic: message => { if (message.includes("tool-delivery-diagnostic")) messages.push(message); }, + }); + bridges.push(bridge); + const answer = await (await fetch(bridge.url, { + method: "POST", + headers: { Authorization: `Bearer ${bridge.secret}`, "Content-Type": "application/json" }, + body: JSON.stringify({ jsonrpc: "2.0", id: 11, method: "tools/call", params: { name: "not_declared", arguments: {} } }), + })).json() as { result: { isError: boolean } }; + expect(answer.result.isError).toBe(true); + await expect.poll(() => messages.length).toBe(1); + expect(JSON.parse(messages[0]!)).toMatchObject({ + callIdSha256: createHash("sha256").update("11").digest("hex"), outcome: "error", written: true, + }); +}); diff --git a/packages/paperclip-runner/src/drivers/opencode/mcp-bridge-diagnostics.test.ts b/packages/paperclip-runner/src/drivers/opencode/mcp-bridge-diagnostics.test.ts index 59844a49dc7..b08fca1a0ef 100644 --- a/packages/paperclip-runner/src/drivers/opencode/mcp-bridge-diagnostics.test.ts +++ b/packages/paperclip-runner/src/drivers/opencode/mcp-bridge-diagnostics.test.ts @@ -44,7 +44,7 @@ it("binds closed rejection shapes to the actual offered finish schema without re }); expect(unrelated.result.isError).toBe(true); expect(handler).toHaveBeenCalledTimes(2); - expect(messages.map(message => JSON.parse(message))).toEqual([ + expect(messages.map(message => JSON.parse(message)).filter(message => message.schema === "paperclip.opencode.finish-input-diagnostic/v1")).toEqual([ { schema: "paperclip.opencode.finish-input-diagnostic/v1", stage: "offered", schemaSha256: digest }, ...["string", "array", "number", "boolean"].map((continuationShape, index) => ({ schema: "paperclip.opencode.finish-input-diagnostic/v1", stage: "input_rejected", @@ -63,7 +63,7 @@ it("reports the effective supplied schema and bounds diagnostics without admitti const inputSchema = { type: "object", required: ["continuation"], properties: { continuation: { type: "object" } } }; const bridge = await startOpenCodeMcpBridge({ tools: [{ name: "paperclip_finish", inputSchema }], handler, - onDiagnostic: message => messages.push(message), + onDiagnostic: message => { if (message.includes("finish-input-diagnostic")) messages.push(message); }, }); bridges.push(bridge); for (let index = 0; index < 12; index++) { diff --git a/packages/paperclip-runner/src/drivers/opencode/mcp-bridge.ts b/packages/paperclip-runner/src/drivers/opencode/mcp-bridge.ts index f2428112f2b..2dc6c73cf05 100644 --- a/packages/paperclip-runner/src/drivers/opencode/mcp-bridge.ts +++ b/packages/paperclip-runner/src/drivers/opencode/mcp-bridge.ts @@ -1,5 +1,6 @@ import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; +import type { Socket } from "node:net"; import { Ajv2020, type ValidateFunction } from "ajv/dist/2020.js"; import { toolInputError } from "../tool-input-error.js"; @@ -57,6 +58,16 @@ const DEFAULT_MAX_BODY_BYTES = 1_048_576; // Native app results/pages are capped at 500 KB before reaching this bridge. // Leave room for their delivery envelope, but never cut a completed JSON value. const MAX_RESULT_BYTES = 1_048_576; +const TOOL_DELIVERY_DIAGNOSTIC_SCHEMA = "paperclip.opencode.tool-delivery-diagnostic/v1"; +const MAX_TOOL_DELIVERY_DIAGNOSTICS = 256; + +type SocketUse = { requests: number; lastResponseAt: number | null }; +type ToolDelivery = { + socketRequestIndex: number; + socketIdleMs: number | null; + receivedAt: number; +}; +type ToolDeliveryOutcome = "result" | "error" | "unanswered"; export function canonicalOpenCodeMcpToolName(name: string): string { const trimmed = name.trim(); @@ -94,10 +105,41 @@ export async function startOpenCodeMcpBridge( }; try { options.onDiagnostic(JSON.stringify(diagnostic)); } catch { /* Optional diagnostics never change admission. */ } }; + let deliveryDiagnostics = 0; + const diagnoseToolDelivery = ( + callId: string, + delivery: ToolDelivery, + outcome: ToolDeliveryOutcome, + written: boolean, + ) => { + if (!options.onDiagnostic || deliveryDiagnostics++ >= MAX_TOOL_DELIVERY_DIAGNOSTICS) return; + const diagnostic = { + schema: TOOL_DELIVERY_DIAGNOSTIC_SCHEMA, + callIdSha256: createHash("sha256").update(callId).digest("hex"), + socketRequestIndex: delivery.socketRequestIndex, + socketIdleMs: delivery.socketIdleMs, + handlerMs: Date.now() - delivery.receivedAt, + outcome, + written, + }; + try { options.onDiagnostic(JSON.stringify(diagnostic)); } catch { /* Optional diagnostics never change delivery. */ } + }; const calls = new Map; waiting: Set }>(); const controllers = new Map(); + const socketUses = new WeakMap(); const server = createServer((request, response) => { + const use = socketUses.get(request.socket) ?? { requests: 0, lastResponseAt: null }; + socketUses.set(request.socket, use); + const receivedAt = Date.now(); + const delivery: ToolDelivery = { + socketRequestIndex: ++use.requests, + socketIdleMs: use.lastResponseAt === null ? null : receivedAt - use.lastResponseAt, + receivedAt, + }; + response.once("finish", () => { use.lastResponseAt = Date.now(); }); void handleRequest(request, response, { + delivery, + diagnoseToolDelivery, secret, tools, admittedTools, @@ -182,6 +224,8 @@ async function handleRequest( request: IncomingMessage, response: ServerResponse, context: { + delivery: ToolDelivery; + diagnoseToolDelivery: (callId: string, delivery: ToolDelivery, outcome: ToolDeliveryOutcome, written: boolean) => void; secret: string; tools: OpenCodeMcpToolDefinition[]; admittedTools: OpenCodeMcpToolDefinition[]; @@ -198,6 +242,11 @@ async function handleRequest( }, ): Promise { setSecurityHeaders(response); + // Never let the MCP client reuse a pooled socket for a later request. A + // native OpenCode run (Bun fetch) once lost a written tools/call result on + // a parallel call and waited about five minutes for Bun's fetch timeout. + // A loopback connect per request costs far less than that failure mode. + response.setHeader("Connection", "close"); if (!authorized(request.headers.authorization, context.secret)) { response.statusCode = 401; response.end(); @@ -265,6 +314,14 @@ async function handleRequest( return; } const params = isRecord(message.params) ? message.params : {}; + const callId = typeof id === "string" || typeof id === "number" ? String(id) : randomBytes(12).toString("hex"); + // Record how each call's answer left the bridge, rejections included, so a + // client that never consumes a written answer can be told apart from a + // bridge that never answered it. + let outcome: ToolDeliveryOutcome = "unanswered"; + response.once("close", () => { + context.diagnoseToolDelivery(callId, context.delivery, outcome, response.writableFinished); + }); const rawName = typeof params.name === "string" ? params.name : ""; // A declared operation may itself start with paperclip_. Preserve that // authority identity before accepting an OpenCode transport prefix alias. @@ -273,10 +330,10 @@ async function handleRequest( ? exactName : canonicalOpenCodeMcpToolName(exactName); if (!context.admittedTools.some((entry) => entry.name === tool)) { + outcome = "error"; writeRpc(response, id, { isError: true, content: [{ type: "text", text: "Unsupported tool." }] }); return; } - const callId = typeof id === "string" || typeof id === "number" ? String(id) : randomBytes(12).toString("hex"); const args = params.arguments ?? {}; const validator = context.validators.get(tool); if (validator === undefined || !validator(args)) { @@ -288,6 +345,7 @@ async function handleRequest( } const error = toolInputError(validator); try { context.onRejectedCall?.({ tool, callId, arguments: args }, error); } catch {} + outcome = "error"; writeRpc(response, id, { isError: true, content: [{ type: "text", text: error }], @@ -298,6 +356,7 @@ async function handleRequest( const existing = context.calls.get(callId); if (existing && existing.fingerprint !== fingerprint) { try { context.onRejectedCall?.({ tool, callId, arguments: args }, "Duplicate call identity conflict."); } catch {} + outcome = "error"; writeRpc(response, id, { isError: true, content: [{ type: "text", text: "Duplicate call identity conflict." }] }); return; } @@ -328,8 +387,11 @@ async function handleRequest( } try { const result = await execution; - writeRpc(response, id, { content: [{ type: "text", text: safeJson(result) }] }); + const text = safeJson(result); + outcome = "result"; + writeRpc(response, id, { content: [{ type: "text", text }] }); } catch (error) { + outcome = "error"; writeRpc(response, id, { isError: true, content: [{ type: "text", text: safeError(error) }] }); } } From 5dfbb04b856543386900d08329c17e06d73a43ca Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Wed, 11 Nov 2026 10:33:02 -0800 Subject: [PATCH 09/12] Poll asynchronous workspace provider preparation (#20865) ## Thinking Path > - Paperclip starts agent runs through a workspace provider when a project uses remote storage. > - The provider must prepare the workspace before the agent starts. > - One long worker call ties the checkout to its transport. > - Some checkouts take longer than the transport allows. > - This change lets an opted-in provider accept work and report its deadline. > - Core waits for completion through short status calls and stops at the provider deadline. ## Linked Issues or Issue Description **What happened?** A workspace provider can lose its reply when preparation takes longer than a single transport request. This stops run bootstrap before agent execution. **Expected behavior** Core should wait for a provider-confirmed workspace through short requests. The provider's deadline must bound the wait. **Steps to reproduce** Use a workspace provider that takes longer to prepare a checkout than its transport can remain open. Start a run that requires a new checkout. ## What Changed - Add an optional workspace preparation method to the plugin SDK. - Validate pending receipts and keep the original binding checks on completed replies. - Poll only during active preparation. Retry a lost status reply within the advertised deadline. - Preserve the original operation for providers that do not offer asynchronous preparation. - Reject deadline offers that exceed the existing lifecycle lock budget. Honor accepted offers without shortening them. - Checkout verification uses the existing synchronous RPC with a 10-second deadline and a 12-second transport timeout. [Core verification PR #20876](https://github.com/paperclipai/paperclip/pull/20876) ## Verification - All 63 workspace SDK and Core integration tests passed with temporary local PostgreSQL. The tests cover lost status replies, deadline expiry, oversized offers, and synchronous verification with an async-capable worker. - All 58 runner SDK input, evidence, and public type tests passed with the regenerated source pins. The local server typecheck passed. ## Risks - This change activates only when the provider advertises the method. Existing providers keep their current behavior. - Polling uses one-second intervals during active preparation. It stops at completion, failure, or the provider deadline. - No database migration is required. ## Model Used - OpenAI GPT-6 Codex with local code execution and tests. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/plugins/PLUGIN_RUNNER_EXECUTION.md | 30 ++++++- packages/plugins/sdk/src/define-plugin.ts | 3 +- packages/plugins/sdk/src/protocol.ts | 4 +- packages/plugins/sdk/src/worker-rpc-host.ts | 10 ++- .../plugins/sdk/src/workspace-provider.ts | 28 +++++++ .../sdk/tests/workspace-provider.test.ts | 13 +++ .../plugin-workspaces.integration.test.ts | 80 +++++++++++++++++-- server/src/services/plugin-worker-manager.ts | 2 +- .../services/plugin-workspace-preparation.ts | 63 +++++++++++++++ server/src/services/plugin-workspaces.ts | 19 ++--- .../runner-e2e/source-sdk-public-inputs.json | 8 +- 11 files changed, 233 insertions(+), 27 deletions(-) create mode 100644 server/src/services/plugin-workspace-preparation.ts diff --git a/doc/plugins/PLUGIN_RUNNER_EXECUTION.md b/doc/plugins/PLUGIN_RUNNER_EXECUTION.md index 3199ca755e3..afc0704453b 100644 --- a/doc/plugins/PLUGIN_RUNNER_EXECUTION.md +++ b/doc/plugins/PLUGIN_RUNNER_EXECUTION.md @@ -175,6 +175,8 @@ It does not qualify a deployed plugin, live account, or production WSS proxy. A storage provider can declare `workspaceProvider.workspaceVerificationVersion: 1`. Before creating a fresh workspace for an admitted Retry, Core may send the original task-owned workspace's `prepare` request with `verifyExisting: true`. +Core sends verification through `workspaceOperation` with a 10-second +deadline and a 12-second RPC timeout. The provider must verify a completed checkout without creating or fetching one and return `prepared` with `created: false`. Core checks prior writer settlement and continues normal preparation on the retained workspace after @@ -261,6 +263,32 @@ Provider upgrades, activation, company re-enablement, and finalization settlemen wake cleanup transactionally. No table, independent timer, or background scan of all remote PR refs is required. +### Asynchronous workspace preparation + +A provider can implement `onWorkspacePrepare` alongside `onWorkspaceOperation`. +Core calls the optional method with `phase: "submit"` and a short submission +deadline. A provider that cannot prepare asynchronously returns +`{ kind: "unsupported" }` before starting work, so Core can use the original +operation. Otherwise the provider returns the completed result or a +`{ kind: "pending", deadline }` receipt. The provider sets and enforces that +operation deadline. Core holds the workspace lifecycle lock during preparation +and rejects offers beyond the previous synchronous RPC budget before polling. +It honors accepted deadlines as supplied. Replayed submission must not duplicate +an active prepare. + +Core sends `phase: "poll"` with the same operation identity and the deadline +from the receipt. The provider returns the same receipt while work is pending +and the usual scoped `prepared` result after success. Core rejects late results +and stops polling when the deadline expires. Each submission and poll has a +short transport bound independent of the operation deadline. A provider can +keep reporting pending while it restores recovery snapshots, under the same +deadline. + +Each invocation has its own scoped host access. Complete scoped host calls +inside the submit or poll that owns them. Detached work can use a remote +operation already authorized by that invocation. It cannot reuse the +invocation to call host services after the reply. + ### Workspace operation failures Core separates a failed `workspaceOperation` call by what it knows about the @@ -274,7 +302,7 @@ outcome: | The provider threw any other error | `Workspace storage provider reported a failure; retry the same workspace` | Unchanged setup failure. | To report a reason, throw `PluginWorkspaceOperationError` from -`onWorkspaceOperation`, or any error with an own `workspaceFailureReason` +`onWorkspaceOperation` or `onWorkspacePrepare`, or any error with an own `workspaceFailureReason` property. The reason must come from `WORKSPACE_OPERATION_FAILURE_REASONS`: | Reason | Retrying the same workspace can help | diff --git a/packages/plugins/sdk/src/define-plugin.ts b/packages/plugins/sdk/src/define-plugin.ts index eb6530c0067..a99e07ce77e 100644 --- a/packages/plugins/sdk/src/define-plugin.ts +++ b/packages/plugins/sdk/src/define-plugin.ts @@ -1,4 +1,4 @@ -import type { PluginWorkspaceParams, PluginWorkspaceResult } from "./workspace-provider.js"; +import type { PluginWorkspaceParams, PluginWorkspacePrepareParams, PluginWorkspacePrepareResult, PluginWorkspaceResult } from "./workspace-provider.js"; import type { PluginEnvironmentTaskParams, PluginEnvironmentTaskResult } from "./environment-tasks.js"; import type { AgentLifecycleRequest, AgentLifecycleResult } from "@paperclipai/shared"; import type { AiConnectionRouterRequest, AiConnectionRouterResult } from "@paperclipai/shared"; @@ -408,6 +408,7 @@ export interface PluginDefinition { ): Promise; /** Required with manifest.workspaceProvider, together with project resource lifecycle. */ + onWorkspacePrepare?(params: PluginWorkspacePrepareParams): Promise; onWorkspaceOperation?(params: PluginWorkspaceParams): Promise; /** Provide Runner execution: prepare resources, start Runner, connect via PRP, and manage task lifecycle. */ diff --git a/packages/plugins/sdk/src/protocol.ts b/packages/plugins/sdk/src/protocol.ts index 95e8af999da..97ee5337227 100644 --- a/packages/plugins/sdk/src/protocol.ts +++ b/packages/plugins/sdk/src/protocol.ts @@ -1,4 +1,4 @@ -import type { PluginWorkspaceParams, PluginWorkspaceResult } from "./workspace-provider.js"; +import type { PluginWorkspaceParams, PluginWorkspacePrepareParams, PluginWorkspacePrepareResult, PluginWorkspaceResult } from "./workspace-provider.js"; import type { PluginEnvironmentTaskParams, PluginEnvironmentTaskResult } from "./environment-tasks.js"; import type { PluginAgentRuntimeState, PluginAgentRuntimeIdentity } from "./types.js"; import type { AgentLifecycleRequest, AgentLifecycleResult } from "@paperclipai/shared"; @@ -1462,6 +1462,7 @@ export interface HostToWorkerMethods { params: PluginEnvironmentValidateConfigParams, result: PluginEnvironmentValidationResult, ]; + workspacePrepare: [params: PluginWorkspacePrepareParams, result: PluginWorkspacePrepareResult]; workspaceOperation: [params: PluginWorkspaceParams, result: PluginWorkspaceResult]; environmentTask: [params: PluginEnvironmentTaskParams, result: PluginEnvironmentTaskResult]; environmentProbe: [ @@ -1586,6 +1587,7 @@ export const HOST_TO_WORKER_OPTIONAL_METHODS: readonly HostToWorkerMethodName[] "handleApiRequest", "agentLifecycle", "resourceLifecycle", + "workspacePrepare", "workspaceOperation", "getData", "performAction", diff --git a/packages/plugins/sdk/src/worker-rpc-host.ts b/packages/plugins/sdk/src/worker-rpc-host.ts index 72f844508f6..3de7748e983 100644 --- a/packages/plugins/sdk/src/worker-rpc-host.ts +++ b/packages/plugins/sdk/src/worker-rpc-host.ts @@ -1,6 +1,6 @@ import { freshWorkspaceSchema } from "./workspace-provider.js"; import { workspaceProviderBindingSchema } from "@paperclipai/shared"; -import { pluginWorkspaceParamsSchema, parseWorkspaceProviderResult } from "./workspace-provider.js"; +import { pluginWorkspaceParamsSchema, pluginWorkspacePrepareParamsSchema, parseWorkspacePrepareResult, parseWorkspaceProviderResult } from "./workspace-provider.js"; import { environmentTaskOperationSchema, parseEnvironmentTaskResult, type PluginEnvironmentTaskParams } from "./environment-tasks.js"; import type { AgentLifecycleRequest, AgentLifecycleResult } from "@paperclipai/shared"; import type { AiConnectionRouterRequest, AiConnectionRouterResult } from "@paperclipai/shared"; @@ -1667,7 +1667,7 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost : method === "environmentStopLease" ? environmentStopErrorData(err) : method === "environmentResumeLease" ? environmentResumeErrorData(err) : method === "environmentTask" ? taskError ?? environmentTaskErrorCodeData(err) - : method === "workspaceOperation" ? workspaceOperationErrorData(err) : undefined)); + : method === "workspaceOperation" || method === "workspacePrepare" ? workspaceOperationErrorData(err) : undefined)); } finally { done?.(); } @@ -1725,6 +1725,11 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost return handleExecuteTool(params as ExecuteToolParams); case "detectExternalObjects": return handleDetectExternalObjects(params as DetectExternalObjectsParams); + case "workspacePrepare": { + if (!plugin.definition.onWorkspacePrepare) throw methodNotImplemented("workspacePrepare"); + const input = pluginWorkspacePrepareParamsSchema.parse(params); + return parseWorkspacePrepareResult(input, await plugin.definition.onWorkspacePrepare(input)); + } case "workspaceOperation": { if (!plugin.definition.onWorkspaceOperation) throw methodNotImplemented("workspaceOperation"); const input = pluginWorkspaceParamsSchema.parse(params); @@ -1875,6 +1880,7 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost if (plugin.definition.onIdleDrain) supportedMethods.push("prepareIdleSleep", "releaseIdleSleep"); if (plugin.definition.onApiRequest) supportedMethods.push("handleApiRequest"); if (plugin.definition.onDetectExternalObjects) supportedMethods.push("detectExternalObjects"); + if (plugin.definition.onWorkspacePrepare) supportedMethods.push("workspacePrepare"); if (plugin.definition.onWorkspaceOperation) supportedMethods.push("workspaceOperation"); if (plugin.definition.onResourceLifecycle) supportedMethods.push("resourceLifecycle"); if (plugin.definition.onAgentLifecycle) supportedMethods.push("agentLifecycle"); diff --git a/packages/plugins/sdk/src/workspace-provider.ts b/packages/plugins/sdk/src/workspace-provider.ts index 5db136efa4b..dea90b92e5b 100644 --- a/packages/plugins/sdk/src/workspace-provider.ts +++ b/packages/plugins/sdk/src/workspace-provider.ts @@ -125,6 +125,34 @@ export const pluginWorkspaceParamsSchema = z /** Finalization receives the originating run/agent context; maintenance remains agent-independent. */ export type PluginWorkspaceParams = z.infer; +export const pluginWorkspacePrepareParamsSchema = pluginWorkspaceParamsSchema.extend({ + phase: z.enum(["submit", "poll"]), +}).refine((input) => input.operation.kind === "prepare"); +export type PluginWorkspacePrepareParams = z.infer; + +export type PluginWorkspacePrepareResult = + | { kind: "unsupported" } + | { kind: "pending"; deadline: string } + | Extract; + +export function parseWorkspacePrepareResult( + params: PluginWorkspacePrepareParams, + value: unknown, +): PluginWorkspacePrepareResult { + const result = z.discriminatedUnion("kind", [ + z.object({ kind: z.literal("unsupported") }).strict(), + z.object({ kind: z.literal("pending"), deadline: z.string().datetime() }).strict(), + ]).safeParse(value); + if (result.success) { + if (result.data.kind === "unsupported" && params.phase !== "submit") + throw new Error("Workspace provider withdrew asynchronous preparation"); + return result.data; + } + const prepared = parseWorkspaceProviderResult(params, value); + if (prepared.kind !== "prepared") throw new Error("Workspace provider returned the wrong preparation result"); + return prepared; +} + export function parseWorkspaceProviderResult( params: PluginWorkspaceParams, value: unknown, diff --git a/packages/plugins/sdk/tests/workspace-provider.test.ts b/packages/plugins/sdk/tests/workspace-provider.test.ts index 9385be933cd..fe8a9501193 100644 --- a/packages/plugins/sdk/tests/workspace-provider.test.ts +++ b/packages/plugins/sdk/tests/workspace-provider.test.ts @@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest"; import { workspaceProviderOperationSchema, parseWorkspaceProviderResult, + parseWorkspacePrepareResult, + pluginWorkspacePrepareParamsSchema, type PluginWorkspaceParams, } from "../src/workspace-provider.js"; import { createWorkspaceProviderHarness } from "../src/testing.js"; @@ -50,6 +52,17 @@ const result = { branchCreatedByRuntime: true, }; describe("workspace provider SDK", () => { + it("validates asynchronous preparation receipts and preserves result scope", () => { + const submit = pluginWorkspacePrepareParamsSchema.parse({ ...params, phase: "submit" }); + const poll = { ...submit, phase: "poll" as const }; + const pending = { kind: "pending", deadline: "2099-01-01T00:01:00Z" }; + expect(parseWorkspacePrepareResult(submit, pending)).toEqual(pending); + expect(parseWorkspacePrepareResult(poll, result)).toEqual(result); + expect(() => parseWorkspacePrepareResult(poll, { kind: "unsupported" })).toThrow(); + expect(() => parseWorkspacePrepareResult(poll, { ...pending, deadline: "whenever" })).toThrow(); + expect(() => parseWorkspacePrepareResult(poll, { ...result, binding: { ...result.binding, projectId: id(20) } })).toThrow(); + }); + it("bounds recovery hints to an exact PR number and commit", () => { for (const kind of ["inspect", "remove"] as const) { const operation = { kind, binding: result.binding, ...(kind === "remove" ? { expectedHeadSha: "a".repeat(40) } : {}) }; diff --git a/server/src/__tests__/plugin-workspaces.integration.test.ts b/server/src/__tests__/plugin-workspaces.integration.test.ts index ae1a45b3fcd..dd05afef90a 100644 --- a/server/src/__tests__/plugin-workspaces.integration.test.ts +++ b/server/src/__tests__/plugin-workspaces.integration.test.ts @@ -1,6 +1,6 @@ import { createPluginWorkspaceFixture } from "./helpers/plugin-workspaces.js"; import { randomUUID } from "node:crypto"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { and, eq, sql } from "drizzle-orm"; import { createDb, @@ -76,11 +76,19 @@ const support = await getEmbeddedPostgresTestSupport(); issueId: f.issueId, status: "running", contextSnapshot: { taskRetryRequestId: retryIntentId }, }).returning(); const fresh = { mode: "fresh_isolated_workspace", retryIntentId, sourceRunId: f.runId, retainedSourceIds: [] } as const; - const workers: WorkspaceWorkers = { ...f.workers, call: async (...args) => { + const call = vi.fn(async (...args) => { const result = await f.workers.call(...args) as { kind: string }; if (state === "unconfirmed") throw new Error("checkout incomplete"); return { ...result, created: false }; - } }; + }); + const workers: WorkspaceWorkers = { + getWorker: (pluginId) => { + const worker = f.workers.getWorker(pluginId); + return worker && { ...worker, supportedMethods: ["workspaceOperation", "workspacePrepare"] }; + }, + call, + }; + const verificationStarted = Date.now(); const result = await verifyRetryWorkspace(db, workers, retry, f.issueId, null, { ...fresh, retainedSourceIds: [] }); const verified = state === "ready" || state === "lost_reply"; @@ -88,11 +96,73 @@ const support = await getEmbeddedPostgresTestSupport(); ? { mode: "reuse_issue_workspace", retryIntentId, sourceRunId: f.runId, workspaceId, cwd: null } : fresh); expect(f.calls.slice(1)).toHaveLength(state === "live_writer" || state === "unsupported" ? 0 : 1); - if (f.calls.length > 1) expect(f.calls[1]).toMatchObject({ executionWorkspaceId: workspaceId, - runId: retry.id, operation: { kind: "prepare", verifyExisting: true } }); + if (f.calls.length > 1) { + expect(call).toHaveBeenCalledExactlyOnceWith(f.pluginId, "workspaceOperation", expect.objectContaining({ + executionWorkspaceId: workspaceId, runId: retry.id, operation: expect.objectContaining({ verifyExisting: true }), + }), 12_000); + const deadline = Date.parse(f.calls[1].deadline); + expect(deadline).toBeGreaterThanOrEqual(verificationStarted + 10_000); + expect(deadline).toBeLessThanOrEqual(Date.now() + 10_000); + } const [retained] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, workspaceId)); expect(retained.providerRef).toBe(`checkout:${workspaceId}`); }); + + it("polls bounded requests using the provider's advertised preparation deadline", async () => { + const f = await fixture(); + const deadline = new Date(Date.now() + 30_000).toISOString(); + const phases: string[] = []; + const workers = { + getWorker: () => ({ supportedMethods: ["workspaceOperation", "workspacePrepare"] }), + call: async (pluginId: string, method: string, params: any, timeout: number) => { + expect(method).toBe("workspacePrepare"); + expect(timeout).toBeLessThanOrEqual(15_000); + phases.push(params.phase); + if (params.phase === "submit") return { kind: "pending", deadline }; + expect(params.deadline).toBe(deadline); + if (phases.length === 2) throw new Error("lost status reply"); + const { phase: _phase, ...original } = params; + return f.workers.call(pluginId, "workspaceOperation", original); + }, + } as unknown as WorkspaceWorkers; + expect(await preparePluginWorkspace(db, workers, f.input)).toBeTruthy(); + expect(phases).toEqual(["submit", "poll", "poll"]); + expect(f.calls).toHaveLength(1); + }); + + it("stops preparation at the provider deadline before issuing a poll", async () => { + const f = await fixture(); + const workers = { + getWorker: () => ({ supportedMethods: ["workspaceOperation", "workspacePrepare"] }), + call: async (_pluginId: string, method: string, params: { phase: string }) => { + expect(method).toBe("workspacePrepare"); + expect(params.phase).toBe("submit"); + return { kind: "pending", deadline: new Date(Date.now() - 1).toISOString() }; + }, + } as unknown as WorkspaceWorkers; + await expect(preparePluginWorkspace(db, workers, f.input)).rejects.toMatchObject({ + kind: "provider", reason: "deadline_exceeded", retryable: true, + }); + }); + + it("rejects an oversized provider deadline before it can retain the workspace lifecycle lock", async () => { + const f = await fixture(); + const workers = { + getWorker: () => ({ supportedMethods: ["workspaceOperation", "workspacePrepare"] }), + call: async (_pluginId: string, method: string, params: { phase: string }) => { + expect(method).toBe("workspacePrepare"); + expect(params.phase).toBe("submit"); + return { kind: "pending", deadline: "2099-01-01T00:00:00Z" }; + }, + } as unknown as WorkspaceWorkers; + await expect(preparePluginWorkspace(db, workers, f.input)).rejects.toMatchObject({ + kind: "provider", reason: "unsupported_operation", retryable: false, + }); + const [task] = await db.select().from(issues).where(eq(issues.id, f.issueId)); + expect(task?.executionWorkspaceId).toBeTruthy(); + expect(await preparePluginWorkspace(db, f.workers, { ...f.input, existingWorkspaceId: task!.executionWorkspaceId })).toBeTruthy(); + }); + it.each([ ["missing", undefined], ["stopped", { status: "stopped", supportedMethods: [] }], diff --git a/server/src/services/plugin-worker-manager.ts b/server/src/services/plugin-worker-manager.ts index fb2ac061a0b..ceb257fec44 100644 --- a/server/src/services/plugin-worker-manager.ts +++ b/server/src/services/plugin-worker-manager.ts @@ -1285,7 +1285,7 @@ export function createPluginWorkerHandle( if (method === "resourceLifecycle" && params.resourceType === "project" && readNonEmptyString(params.resourceId)) { return { companyId: directCompanyId, projectGit: { projectId: params.resourceId as string } }; } - if (method === "workspaceOperation" && isRecord(params.operation)) { + if ((method === "workspaceOperation" || method === "workspacePrepare") && isRecord(params.operation)) { const operation = params.operation; const source = operation.kind === "prepare" ? operation.source : operation.binding; const workspaceId = isRecord(source) ? readNonEmptyString(operation.kind === "prepare" ? source.id : source.projectWorkspaceId) : null; diff --git a/server/src/services/plugin-workspace-preparation.ts b/server/src/services/plugin-workspace-preparation.ts new file mode 100644 index 00000000000..895fc6c0e4f --- /dev/null +++ b/server/src/services/plugin-workspace-preparation.ts @@ -0,0 +1,63 @@ +import { setTimeout as delay } from "node:timers/promises"; +import { parseWorkspacePrepareResult, parseWorkspaceProviderResult, type PluginWorkspaceParams } from "@paperclipai/plugin-sdk"; +import type { PluginWorkerManager } from "./plugin-worker-manager.js"; +import { WorkspaceProviderFailureError, workspaceProviderCallFailure } from "./workspace-provider-failure.js"; + +type ProviderRequest = Omit; +type WorkspaceWorker = Pick; +const legacyWorkspaceOperationMs = 300_000; +const legacyRpcGraceMs = 10_000; + +export async function invokeWorkspaceProvider(workers: WorkspaceWorker, params: ProviderRequest) { + const verifyExisting = params.operation.kind === "prepare" && params.operation.verifyExisting; + if (!verifyExisting && params.operation.kind === "prepare" && workers.getWorker(params.pluginId)?.supportedMethods?.includes("workspacePrepare")) { + const result = await prepareWorkspaceWithPolling(workers, params); + if (result) return result; + } + const timeout = verifyExisting ? 10_000 : params.operation.kind === "finalize" ? 30_000 : legacyWorkspaceOperationMs; + const request = { ...params, deadline: new Date(Date.now() + timeout).toISOString() }; + return parseWorkspaceProviderResult(request, await workers.call( + params.pluginId, "workspaceOperation", request, timeout + (verifyExisting ? 2_000 : legacyRpcGraceMs), + )); +} + +async function prepareWorkspaceWithPolling(workers: Pick, params: ProviderRequest) { + const rpcTimeout = 15_000; + const submit = { ...params, phase: "submit" as const, deadline: new Date(Date.now() + rpcTimeout).toISOString() }; + const receipt = parseWorkspacePrepareResult(submit, await workers.call(params.pluginId, "workspacePrepare", submit, rpcTimeout)); + if (receipt.kind === "unsupported") return null; + if (receipt.kind === "prepared") return receipt; + const offeredMs = Date.parse(receipt.deadline) - Date.now(); + if (offeredMs > legacyWorkspaceOperationMs + legacyRpcGraceMs) + throw new WorkspaceProviderFailureError({ + kind: "provider", reason: "unsupported_operation", retryable: false, + message: "Workspace provider offered a deadline outside the supported lifecycle budget", + }); + const expiresAt = performance.now() + offeredMs; + const remaining = () => { + const ms = Math.ceil(expiresAt - performance.now()); + if (ms <= 0) throw new WorkspaceProviderFailureError({ + kind: "provider", reason: "deadline_exceeded", retryable: true, + message: "Workspace storage operation expired; retry the same workspace", + }); + return ms; + }; + const poll = { ...params, phase: "poll" as const, deadline: receipt.deadline }; + for (;;) { + await delay(Math.min(1000, remaining())); + const timeout = Math.min(rpcTimeout, remaining()); + let response: unknown; + try { + response = await workers.call(params.pluginId, "workspacePrepare", poll, timeout); + } catch (error) { + const failure = workspaceProviderCallFailure(error); + if (failure.kind === "transport" || failure.kind === "timeout") continue; + throw failure; + } + remaining(); + const status = parseWorkspacePrepareResult(poll, response); + if (status.kind === "prepared") return status; + if (status.kind === "unsupported" || status.deadline !== receipt.deadline) + throw new Error("Workspace provider changed the preparation deadline"); + } +} diff --git a/server/src/services/plugin-workspaces.ts b/server/src/services/plugin-workspaces.ts index 6faed0e455b..cab1346ed1d 100644 --- a/server/src/services/plugin-workspaces.ts +++ b/server/src/services/plugin-workspaces.ts @@ -17,16 +17,17 @@ import { type WorkspaceProviderBinding, } from "@paperclipai/shared"; import { - parseWorkspaceProviderResult, workspaceProviderOperationSchema, type PluginWorkspaceOperation, type PluginWorkspaceRecoveryPullRequest, type PluginWorkspaceParams, + type PluginWorkspaceResult, type PluginFreshWorkspace, } from "@paperclipai/plugin-sdk"; +import { invokeWorkspaceProvider } from "./plugin-workspace-preparation.js"; import { notifyTerminalWorkspaceWork } from "./terminal-workspace-work.js"; import { withExecutionWorkspaceLifecycleLock } from "./execution-workspace-lifecycle-lock.js"; -import { workspaceProviderCallFailure } from "./workspace-provider-failure.js"; +import { WorkspaceProviderFailureError, workspaceProviderCallFailure } from "./workspace-provider-failure.js"; import { assertTaskWorkspaceExecutionAccess, assertTaskWorkspaceSourceProjectAccess, @@ -87,7 +88,7 @@ export async function callWorkspaceProvider( operation.fresh = await stageProviderFreshWorkspace({ db, companyId: workspace.companyId, issueId: workspace.sourceIssueId, ...operation.fresh, existing: operation.fresh }); } - const params: PluginWorkspaceParams = { + const params: Omit = { pluginId, companyId: workspace.companyId, projectId: workspace.projectId, @@ -102,22 +103,17 @@ export async function callWorkspaceProvider( ) .digest("hex")), generation: operationGeneration, - deadline: new Date(Date.now() + (verifyExisting ? 10_000 : operation.kind === "finalize" ? 30_000 : 300_000)).toISOString(), runId: input.runId ?? null, agentId: input.agentId ?? null, operation, }; - let value: unknown; + let result: PluginWorkspaceResult; try { - value = await workers!.call( - pluginId, - "workspaceOperation", - params, - verifyExisting ? 12_000 : operation.kind === "finalize" ? 40_000 : 310_000, - ); + result = await invokeWorkspaceProvider(workers!, params); } catch (error) { // A worker that never received the call, a lost reply and a provider-reported // failure need different recovery; only a closed provider reason crosses over. + if (error instanceof WorkspaceProviderFailureError) throw error; throw workspaceProviderCallFailure(error); } // Recheck enablement and ownership after an external effect, including an ambiguous retry. @@ -139,7 +135,6 @@ export async function callWorkspaceProvider( ) { throw conflict("Workspace changed during storage preparation"); } - const result = parseWorkspaceProviderResult(params, value); if (result.kind === "prepared" && result.binding.pluginId !== pluginId) throw conflict("Workspace provider ownership changed"); return result; diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 2cb39222091..3ef601ea748 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -3,7 +3,7 @@ "package.json": "e704ca28508fa7c887f704fc26603cf8fd623867", "packages/plugins/sdk/package.json": "b7a4936e2803fd0d3b32dd7f17fc1ea86609ead0", "packages/plugins/sdk/src/bundlers.ts": "883bf3d9f2bd42877cfc0c3707cd882a6f6248d0", - "packages/plugins/sdk/src/define-plugin.ts": "eb6530c006722d22f55355ec810745f1524b874a", + "packages/plugins/sdk/src/define-plugin.ts": "a99e07ce77ef72fcf1df1347346aacb8ba12e284", "packages/plugins/sdk/src/dev-cli.ts": "7c1b0e2b6e4b7fd82027cca5321066e473a03d20", "packages/plugins/sdk/src/dev-server.ts": "2eadff81b74ca0706aec53aaf8637797fe4b4093", "packages/plugins/sdk/src/environment-acquire-error.ts": "50a74c3d1f83150f4215d44a763aa8ce4d9469c2", @@ -20,7 +20,7 @@ "packages/plugins/sdk/src/index.ts": "4e573c181198ea98442321cc136341741e856ff7", "packages/plugins/sdk/src/invocation-tracer.ts": "b28ac4aa4bc3e82658abac4a8081ed4508008696", "packages/plugins/sdk/src/protocol.duplex-channel.test.ts": "18255eb3d63038dc459240c111cbcb29fcba25cc", - "packages/plugins/sdk/src/protocol.ts": "95e8af999dabf93b1b0e531edfec4c80daf52b61", + "packages/plugins/sdk/src/protocol.ts": "97ee5337227e3a1ede6801fe5b7586cc6785edad", "packages/plugins/sdk/src/testing.ts": "fa99065efa867d8f8a9372cb4a448b8f9d687883", "packages/plugins/sdk/src/types.ts": "80375e46504f96c7c0c1f156319dfb81275d16cc", "packages/plugins/sdk/src/ui/clipboard.ts": "1f42069c97d731e636a6ad5481dad22d20c0ed63", @@ -29,9 +29,9 @@ "packages/plugins/sdk/src/ui/index.ts": "f7d1cee64a8f0c924bd10a1bd20745a52fe2060e", "packages/plugins/sdk/src/ui/runtime.ts": "998428e9701eba3b762d3417236d32c2d0d5763d", "packages/plugins/sdk/src/ui/types.ts": "5a5644acf6554d2e5e1d000bfd03b97d57001eb2", - "packages/plugins/sdk/src/worker-rpc-host.ts": "72f844508f695737a44d34b01b3949ec3be10aec", + "packages/plugins/sdk/src/worker-rpc-host.ts": "3de7748e983ad1a749a7a7f62f685dab4399cdd1", "packages/plugins/sdk/src/workspace-operation-error.ts": "2cd247d002d83b163239229e631bca4e519e5075", - "packages/plugins/sdk/src/workspace-provider.ts": "5db136efa4bd904044113e341f443e523e336d0d", + "packages/plugins/sdk/src/workspace-provider.ts": "dea90b92e5bf0c05062eb57598c70f370e207cea", "packages/plugins/sdk/tsconfig.json": "d62ebdff94bc4b75dabf1fcad187e1e7a90fc794", "packages/shared/package.json": "6417ef8baef0cb9b836b14f453dc8bc5025709e0", "packages/shared/src/__snapshots__/slack-app-manifest.test.ts.snap": "79020ba3aa6662923f70aa44e2c483844e9901d9", From 854b4bcac4ca146e8ef0bca4c2eb5c2445425b61 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:44:09 -0600 Subject: [PATCH 10/12] fix(opencode): report a provider 401 from the hello probe as missing authentication (#20878) 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 > - Each agent has a runtime readiness test ("test environment") that runs a short hello probe through its harness > - The OpenCode probe sorts failures into model, timeout, authentication and generic errors > - OpenRouter rejects an empty or unknown key with HTTP 401 and the messages "Missing Authentication header" or "User not found." > - The probe matched authentication only by wording, so these 401 replies became a generic `opencode_hello_probe_failed` error > - The server maps `*_hello_probe_auth_required` to the missing-account state, so the user saw a generic failure instead of "connect an account" > - This pull request classifies the structured APIError status 401 as `opencode_hello_probe_auth_required` > - The benefit is that a member without a working account shows the missing-account state and its fix ## Linked Issues or Issue Description **What happened** An OpenCode (native runner) agent with an empty OpenRouter key failed its readiness test with the generic error `opencode_hello_probe_failed`. The chat eval `teams.configure-team` could not form its "one member is missing an account, one is ready" fixture because of this. **Expected behavior** The readiness test reports `opencode_hello_probe_auth_required` (warn) when the provider rejects authentication with HTTP 401, whatever the provider's wording. **Steps to reproduce** 1. Configure a native runner OpenCode agent with model `openrouter/deepseek/deepseek-v4.1-flash-1017` and `OPENROUTER_API_KEY` set to an empty string. 2. Run the agent's environment test. 3. OpenCode 1.18.34 prints `{"type":"error","error":{"name":"APIError","data":{"message":"Missing Authentication header","statusCode":401}}}`. 4. The result is `opencode_hello_probe_failed` (error), not the missing-authentication check. ## What Changed - `parse.ts`: add `openCodeErrorStatusCodes`, which reads the HTTP status from OpenCode error events. - `test.ts`: treat a 401 status on the hello probe as `opencode_hello_probe_auth_required`, in addition to the existing wording match. - `test.remote.test.ts`: regression tests with the two recorded OpenRouter 401 outputs, and a negative control (500 and 429 stay generic failures). ## Verification - `pnpm exec vitest run packages/adapters/opencode-local/src/server/test.remote.test.ts packages/adapters/opencode-local/src/server/parse.test.ts` passes (28 tests). - Red check: without the classifier change, the two new 401 tests fail. - `npx tsc --noEmit -p packages/adapters/opencode-local` passes. - I recorded the probe output from the pinned OpenCode 1.18.34 binary against OpenRouter with an empty key and with an unknown key. ## Risks - Low risk. Only a 401 status changes classification. A 401 means the provider rejected the credential. Other statuses keep their current result. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), tool use and code execution in Claude Code. ## 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 --- .../opencode-local/src/server/parse.ts | 11 +++++++++ .../src/server/test.remote.test.ts | 23 +++++++++++++++++++ .../opencode-local/src/server/test.ts | 5 ++-- 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/packages/adapters/opencode-local/src/server/parse.ts b/packages/adapters/opencode-local/src/server/parse.ts index c244fa0e102..db2d1e1e7cc 100644 --- a/packages/adapters/opencode-local/src/server/parse.ts +++ b/packages/adapters/opencode-local/src/server/parse.ts @@ -106,6 +106,17 @@ export function createOpenCodeJsonlParser() { }; } +export function openCodeErrorStatusCodes(stdout: string): number[] { + const statuses: number[] = []; + for (const rawLine of stdout.split(/\r?\n/)) { + const event = parseJson(rawLine.trim()); + if (!event || asString(event.type, "") !== "error") continue; + const status = parseObject(parseObject(event.error).data).statusCode; + if (typeof status === "number" && Number.isInteger(status)) statuses.push(status); + } + return statuses; +} + export function isOpenCodeUnknownSessionError(stdout: string, stderr: string): boolean { const haystack = `${stdout}\n${stderr}` .split(/\r?\n/) diff --git a/packages/adapters/opencode-local/src/server/test.remote.test.ts b/packages/adapters/opencode-local/src/server/test.remote.test.ts index e83848e3f15..7a73d363edd 100644 --- a/packages/adapters/opencode-local/src/server/test.remote.test.ts +++ b/packages/adapters/opencode-local/src/server/test.remote.test.ts @@ -119,6 +119,29 @@ describe("opencode remote environment diagnostics", () => { }, ); + it.each(["Missing Authentication header", "User not found."])( + "reports a provider 401 as missing authentication, not a generic failure (%s)", async message => { + const successfulProbe = await runAdapterExecutionTargetProcess.getMockImplementation()!(); + runAdapterExecutionTargetProcess.mockResolvedValueOnce({ ...successfulProbe, exitCode: 1, stderr: "", + stdout: JSON.stringify({ type: "error", sessionID: "session-1", error: { name: "APIError", + data: { message, statusCode: 401, isRetryable: false, responseHeaders: { "access-control-expose-headers": "WWW-Authenticate" } } } }) }); + const result = await testEnvironment({ companyId: "company-1", adapterType: "paperclip_runner", + config: { model: "openrouter/deepseek/deepseek-v4-flash-0731", env: { XDG_CONFIG_HOME: configHome } } }); + expect(result.status).toBe("warn"); + expect(result.checks.map(check => [check.code, check.level])).toContainEqual(["opencode_hello_probe_auth_required", "warn"]); + expect(result.checks.some(check => check.level === "error")).toBe(false); + }, + ); + + it.each([500, 429])("keeps other provider statuses a generic probe failure (%s)", async statusCode => { + const successfulProbe = await runAdapterExecutionTargetProcess.getMockImplementation()!(); + runAdapterExecutionTargetProcess.mockResolvedValueOnce({ ...successfulProbe, exitCode: 1, stderr: "", + stdout: JSON.stringify({ type: "error", error: { name: "APIError", data: { message: "Upstream error", statusCode } } }) }); + const result = await testEnvironment({ companyId: "company-1", adapterType: "paperclip_runner", + config: { model: "openrouter/deepseek/deepseek-v4-flash-0731", env: { XDG_CONFIG_HOME: configHome } } }); + expect(result.checks).toContainEqual(expect.objectContaining({ code: "opencode_hello_probe_failed", level: "error" })); + }); + it("gives each concurrent native probe its own OpenCode data directory", async () => { vi.stubEnv("HOME", "/host/user"); vi.stubEnv("XDG_DATA_HOME", "/host/user/.local/share"); diff --git a/packages/adapters/opencode-local/src/server/test.ts b/packages/adapters/opencode-local/src/server/test.ts index aad64db7234..367ac7c6aa1 100644 --- a/packages/adapters/opencode-local/src/server/test.ts +++ b/packages/adapters/opencode-local/src/server/test.ts @@ -27,7 +27,7 @@ import { overrideAdapterExecutionTargetRemoteCwd, } from "@paperclipai/adapter-utils/execution-target"; import { discoverOpenCodeModels, ensureOpenCodeModelConfiguredAndAvailable, requireOpenCodeModelId } from "./models.js"; -import { parseOpenCodeJsonl } from "./parse.js"; +import { openCodeErrorStatusCodes, parseOpenCodeJsonl } from "./parse.js"; import { SANDBOX_INSTALL_COMMAND } from "../index.js"; import { prepareOpenCodeRuntimeConfig, prepareManagedOpenCodeRemoteHomes } from "./runtime-config.js"; @@ -418,6 +418,7 @@ export async function testEnvironment( const parsed = parseOpenCodeJsonl(probe.stdout); const detail = summarizeProbeDetail(probe.stdout, probe.stderr, parsed.errorMessage); const authEvidence = `${parsed.errorMessage ?? ""}\n${probe.stdout}\n${probe.stderr}`.trim(); + const providerRejectedAuth = openCodeErrorStatusCodes(probe.stdout).includes(401); if (probe.timedOut) { checks.push({ @@ -450,7 +451,7 @@ export async function testEnvironment( ...(detail ? { detail } : {}), hint: "Run `opencode models` and choose an available provider/model ID.", }); - } else if (OPENCODE_AUTH_REQUIRED_RE.test(authEvidence)) { + } else if (providerRejectedAuth || OPENCODE_AUTH_REQUIRED_RE.test(authEvidence)) { checks.push({ code: "opencode_hello_probe_auth_required", level: "warn", From b96967a97bb66860b528a7962ff71dfc56457761 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:49:19 -0600 Subject: [PATCH 11/12] fix(authz): name the environment settings page when an agent is denied an environment route (#20880) 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 > - Execution environments are the computers that agents run on. Only a board user can list, inspect, test or change them. > - An agent in chat can be asked "Which computer can run Morgan with Claude Code?". Its first environment read returns 403. > - The 403 says the denial is final, but it names no page. The agent cannot link the person to the control that answers the question. > - Other board-only areas (secrets, plugins, budgets) already name their page in the denial. > - This pull request adds the environment settings page to the agent denial for every environment route, and says that testing and changing computers are board-only too. > - The benefit is that the agent can send the person straight to the correct control, and it does not search for a probe route that does not exist. ## Linked Issues or Issue Description **What happened** An agent asked which computer can run a coding harness called the environment list or capabilities route. The route returned 403 "Board access required" with a remediation that named no page ("Link a page only if you already know its route; do not search for one"). The agent had no route to give the person. **Expected behavior** The denial names the environment settings page as a Markdown link with the `` placeholder, like the denials for secrets and plugins. It also says that the other environment steps (capabilities, probes, changes) are board-only, so the agent replies instead of trying them. When an operator hides environment settings (`PAPERCLIP_HIDDEN_SETTINGS=instance.environments`), the denial does not link the page. **Steps to reproduce** 1. Use an agent API key. 2. Call `GET /api/companies//environments/capabilities`. 3. Read the 403 body. Before this change, `remediation` contains no link. ## What Changed - `server/src/routes/authz.ts`: board-only denials on `/companies/:id/environments...`, `/environments/...` and `/environment-leases/...` now link `[Open environment settings](//company/settings/instance/environments)` and add one sentence that says execution environments are board-only throughout. The link is left out when the operator hides `instance.environments`. `/companies/:id/project-environments` (agent-readable) is not matched. - `server/src/__tests__/board-access-denial.test.ts`: regression tests for the list, capabilities, probe and lease routes, the scope sentence, the project-environments exclusion, and the hidden-settings case. ## Verification - `cd server && pnpm exec vitest run src/__tests__/board-access-denial.test.ts`: 33 passed. With the old `authz.ts`, 5 of the new tests fail (red), and they pass with the change (green). - `cd server && pnpm exec vitest run src/__tests__/environment-routes.test.ts src/__tests__/agent-permissions-routes.test.ts`: 99 and 126 passed. ## Risks - Low risk. Only the agent-facing 403 remediation text changes. Status codes, the error code and board behavior do not change. - The scope sentence is environment-specific, so other denials are unchanged. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), tool use and code execution in Claude Code. ## 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 --- .../src/__tests__/board-access-denial.test.ts | 27 +++++++++++++++++++ .../src/__tests__/environment-routes.test.ts | 22 +++++++++++++-- server/src/routes/authz.ts | 13 ++++++++- server/src/routes/environments.ts | 3 ++- 4 files changed, 61 insertions(+), 4 deletions(-) diff --git a/server/src/__tests__/board-access-denial.test.ts b/server/src/__tests__/board-access-denial.test.ts index 04da1f29281..2d9f681769f 100644 --- a/server/src/__tests__/board-access-denial.test.ts +++ b/server/src/__tests__/board-access-denial.test.ts @@ -48,6 +48,11 @@ describe("board-only denial", () => { ["get", "/api/plugins/ui-contributions", "[Open plugin settings](//company/settings/instance/plugins)"], ["post", `/api/projects/${AGENT_ID}/access-members`, `[Open the project's access settings](//projects/${AGENT_ID}/configuration)`], ["delete", `/api/projects/${AGENT_ID}/access-members/m-1`, `[Open the project's access settings](//projects/${AGENT_ID}/configuration)`], + ["get", `/api/companies/${COMPANY_ID}/environments`, "[Open environment settings](//company/settings/instance/environments)"], + ["get", `/api/companies/${COMPANY_ID}/environments/capabilities`, "[Open environment settings](//company/settings/instance/environments)"], + ["post", `/api/environments/${AGENT_ID}/probe`, "[Open environment settings](//company/settings/instance/environments)"], + ["get", `/api/environment-leases/${AGENT_ID}`, "[Open environment settings](//company/settings/instance/environments)"], + ["get", `/api/environment-custom-image-setup-sessions/${AGENT_ID}`, "[Open environment settings](//company/settings/instance/environments)"], ] as const)("tells an agent %s %s is final and names the board page", async (method, path, link) => { const res = await request(createApp(agentActor))[method](path).expect(403); expect(res.body.error).toBe("Board access required"); @@ -122,6 +127,28 @@ describe("board-only denial", () => { } }); + it("tells an agent denied an environment route that testing and changing computers are board-only too", async () => { + const res = await request(createApp(agentActor, assertBoardOrgAccess)).get(`/api/companies/${COMPANY_ID}/environments/capabilities`).expect(403); + expect(res.body.remediation).toContain("Execution environments are board-only throughout"); + expect(res.body.remediation).toContain("testing (probing) them"); + const other = await request(createApp(agentActor)).get(`/api/companies/${COMPANY_ID}/project-environments`).expect(403); + expect(other.body.remediation).not.toContain("Execution environments"); + expect(other.body.remediation).not.toContain("/instance/environments"); + }); + + it("does not link environment settings while the operator hides them", async () => { + const previous = process.env.PAPERCLIP_HIDDEN_SETTINGS; + process.env.PAPERCLIP_HIDDEN_SETTINGS = "instance.environments"; + try { + const res = await request(createApp(agentActor)).get(`/api/companies/${COMPANY_ID}/environments`).expect(403); + expect(res.body.remediation).toContain("this denial is final"); + expect(res.body.remediation).not.toContain("/instance/environments"); + } finally { + if (previous === undefined) delete process.env.PAPERCLIP_HIDDEN_SETTINGS; + else process.env.PAPERCLIP_HIDDEN_SETTINGS = previous; + } + }); + it("applies through the org-access guard", async () => { const res = await request(createApp(agentActor, assertBoardOrgAccess)).delete(`/api/companies/${COMPANY_ID}`).expect(403); expect(res.body.code).toBe(BOARD_ACCESS_REQUIRED_CODE); diff --git a/server/src/__tests__/environment-routes.test.ts b/server/src/__tests__/environment-routes.test.ts index 14842a5661c..235621dc517 100644 --- a/server/src/__tests__/environment-routes.test.ts +++ b/server/src/__tests__/environment-routes.test.ts @@ -1526,6 +1526,24 @@ describe("environment routes", () => { expect(mockEnvironmentService.list).not.toHaveBeenCalled(); }); + it.each([ + ["get", "/api/companies/company-1/environments/capabilities"], + ["post", "/api/companies/company-1/environments"], + ["post", "/api/environments/env-1/probe"], + ["patch", "/api/environments/env-1"], + ["delete", "/api/environments/env-1"], + ["get", "/api/environments/env-1/leases"], + ] as const)("gives an agent denied %s %s the final environment settings guidance", async (method, path) => { + const app = createApp({ type: "agent", agentId: "agent-1", companyId: "company-1", source: "agent_key", runId: "run-1" }); + const res = await request(app)[method](path).send(method === "post" && path.endsWith("/environments") ? { name: "Agent computer", driver: "local", config: {} } : {}); + expect(res.status).toBe(403); + expect(res.body.error).toBe("Board access required"); + expect(res.body.remediation).toContain("this denial is final"); + expect(res.body.remediation).toContain("Execution environments are board-only throughout"); + expect(res.body.remediation).toContain("[Open environment settings](//company/settings/instance/environments)"); + expect(mockEnvironmentService.create).not.toHaveBeenCalled(); + }); + it("rejects agent detail reads for instance-scoped environments", async () => { mockEnvironmentService.getById.mockResolvedValue(createEnvironment()); mockAgentService.getById.mockResolvedValue({ @@ -1679,7 +1697,7 @@ describe("environment routes", () => { }); expect(res.status).toBe(403); - expect(res.body.error).toContain("board operators"); + expect(res.body.error).toBe("Board access required"); expect(mockEnvironmentService.create).not.toHaveBeenCalled(); }); @@ -2577,7 +2595,7 @@ describe("environment routes", () => { }); expect(res.status).toBe(403); - expect(res.body.error).toContain("board operators"); + expect(res.body.error).toBe("Board access required"); expect(mockEnvironmentService.create).not.toHaveBeenCalled(); }); diff --git a/server/src/routes/authz.ts b/server/src/routes/authz.ts index 4fab0967fa7..83dce412aa6 100644 --- a/server/src/routes/authz.ts +++ b/server/src/routes/authz.ts @@ -95,6 +95,13 @@ function pluginControlPage(path: string): [string, string] | null { const PLUGIN_ROUTE = /^\/plugins(?:\/|$)/; const PLUGIN_ADMINISTRATION_SCOPE = "Plugin management is board-only throughout: listing, installing, configuring (including choosing a secret for a plugin setting), enabling, disabling, upgrading and removing plugins have no agent route either."; +const ENVIRONMENT_ROUTE = /^\/(?:companies\/[^/]+\/)?environments(?:\/|$)|^\/environment-(?:leases|custom-image-setup-sessions)(?:\/|$)/; +const ENVIRONMENT_ADMINISTRATION_SCOPE = "Execution environments are board-only throughout: listing computers, reading which coding harnesses they support, testing (probing) them and changing them have no agent route either."; +function environmentControlPage(path: string): [string, string] | null { + if (!ENVIRONMENT_ROUTE.test(path) || getHiddenSettings().has("instance.environments")) return null; + return ["environment settings", "//company/settings/instance/environments"]; +} + function deniedApiPath(req: Request) { return (req.originalUrl ?? "").split("?")[0]!.replace(/^\/api(?=\/)/, ""); } @@ -103,6 +110,8 @@ function boardControlPage(req: Request) { const path = deniedApiPath(req); const pluginPage = pluginControlPage(path); if (pluginPage) return pluginPage; + const environmentPage = environmentControlPage(path); + if (environmentPage) return environmentPage; for (const [pattern, page] of BOARD_CONTROL_PAGES) { const match = pattern.exec(path); if (match) return page(match, req); @@ -117,7 +126,9 @@ function boardControlPage(req: Request) { export function boardAccessRequired(req: Request, controlPage?: BoardControlPage) { if (req.actor.type !== "agent") return forbidden("Board access required"); const page = controlPage ?? boardControlPage(req); - const scope = PLUGIN_ROUTE.test(deniedApiPath(req)) ? `${PLUGIN_ADMINISTRATION_SCOPE} ` : ""; + const deniedPath = deniedApiPath(req); + const scope = PLUGIN_ROUTE.test(deniedPath) ? `${PLUGIN_ADMINISTRATION_SCOPE} ` + : ENVIRONMENT_ROUTE.test(deniedPath) ? `${ENVIRONMENT_ADMINISTRATION_SCOPE} ` : ""; const where = page ? `They can do it in the Paperclip web app: link [Open ${page[0]}](${page[1]}), with this conversation's company prefix as .` : "They can do it in the Paperclip web app or with their own board credentials. Link a page only if you already know its route; do not search for one."; diff --git a/server/src/routes/environments.ts b/server/src/routes/environments.ts index ffdad6429df..506fe19ee8f 100644 --- a/server/src/routes/environments.ts +++ b/server/src/routes/environments.ts @@ -59,7 +59,7 @@ import { assertAgentsReadyForEnvironmentChange, } from "../services/plugin-environment-driver.js"; import { getConfiguredSecretProvider } from "../secrets/configured-provider.js"; -import { assertBoard, assertBoardOrgAccess, getActorInfo } from "./authz.js"; +import { assertBoard, assertBoardOrgAccess, boardAccessRequired, getActorInfo } from "./authz.js"; import type { PluginWorkerManager } from "../services/plugin-worker-manager.js"; import { environmentService } from "../services/environments.js"; import { SANDBOX_PLATFORM_PROBE_METADATA_KEY } from "../services/environment-custom-image-runtime.js"; @@ -388,6 +388,7 @@ export function environmentRoutes( } function assertCanAccessInstanceEnvironments(req: Request) { + if (req.actor.type === "agent") throw boardAccessRequired(req); if (req.actor.type !== "board") { throw forbidden("Instance environment management is restricted to board operators"); } From 683fd1e9a502bba5599670ceb80d72fdc1a3190b Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:58:41 -0600 Subject: [PATCH 12/12] test(restart-chaos): cells for staging's no-restart failures (re-wake, Nth recovery step, long turn, K15 without volume) (#20893) 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 restart-chaos harness (`tests/restart-chaos/`) tests that agent work survives control-plane faults > - In one 8-hour staging window, 20 of 25 failed runs happened with no restart at all, so the harness did not see them > - The harness had blind spots: one short task per agent, no wake right after a successful run, no fault in a later recovery step, short turns, and a redeploy that always keeps its instance home > - This pull request adds cells for those shapes, so the harness reproduces these failure classes on master > - The benefit is that fixes for these classes can be proven red and green with the harness, without staging ## Linked Issues or Issue Description **What happened?** On staging, an agent ran 10–13 tasks at once on reused sandboxes. 30–60 s after a long run succeeded, an ordinary wake (a comment or an issue monitor) started the next run of the same task. That run or its recovery failed before any provider work, with errors such as `runner_remote_process_identity_unavailable`, `Controller journal drain timed out` and `journal_tool_input_unanswered`. Other failures happened in a later recovery step (a held agent-directory lock, a missing runtime asset after a deploy without a volume). **Expected behavior** The chaos harness can reproduce each of these shapes on demand, and grades them: no failed attempt, every task `done`, and no task left blocked without a working Retry. **Steps to reproduce** See the commands in the README sections "Re-wake after success", "Fail the Nth recovery step", "Long turn" and "Redeploy without a volume, with overlap". Related: #20844 (session fault SR1). W2C is the configuration change after a successful run; SR1 is the same change while a question is parked. This PR does not add or change `session-faults.ts`. ## What Changed - New workloads W2, W2Q, W2C (`rewake.ts`): phase 1 ends with the task left open; the harness, as the board, wakes the same task the seeded 0–60 s after its run settled. W2 uses a comment or a board-scheduled issue monitor (by nonce). W2Q parks on an unanswered `request_human_input` question and is woken by a comment before the answer. W2C changes the agent's `adapterConfig.idleTimeoutMs` before the wake. Oracle: phase 1 succeeded, the wake was served by a run that succeeded, `no_failed_attempt`, `done`, markers. - `--faults K0`: cells with no fault, for workloads whose shape is the fault. - `--fail-recovery-step [:]` (`recovery-step-faults.ts`): when the wave's first restart fault starts its replacement, the harness arms one crash point in a new fail mode; the nth hit throws the error of the real step, once. Steps: `runnerd-start` (`spawn paperclip-runnerd EAGAIN`), `teardown` (provider destroy did not finish), `directory-lock` (`Agent directory operation is already active`). Crossed tasks get `recovery_step_failed_once` and `no_failed_attempt`. - Crash points (`packages/shared/src/crash-points.ts`): fail mode in the control file (` : fail [pid=]`), with an optional call-site error; `pid=` binds the line to one server process. The harness arms the step for the replacement only and disarms it once its receipt lands. New point `agent_directory.operation_lock.before_acquire`. The teardown point moved into its `try`, so fail mode behaves like a failed provider destroy; kill mode is unchanged. All points stay disarmed under `NODE_ENV=production`. The runner package's own crash-point copy is not changed (runner image content ID unchanged). - `--long-turn-minutes ` (`long-turn.ts`, 15–60, opt-in): every task's first turn runs rounds of real tool work for n minutes before its workload. Checks `long_turn_rounds` and `long_turn_run_observed`. - K15 `--k15-fresh-home` (Daytona) and `--k15-overlap-seconds -` (`redeploy.ts`, `supervisor.ts`, `edge-proxy.ts`): each deploy generation gets a new, empty instance home and no volume variables; the next generation boots beside the old one behind an edge proxy on the wave's port, takes traffic once ready, and the old one gets SIGTERM after the overlap. - `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed pins for the changed shared crash-point files. - README: one section per new cell, with what it covers. ## Verification - `pnpm exec vitest run --config tests/restart-chaos/vitest.config.ts` (48 files, 581 tests after rebasing on master, includes the new `shape-cells.test.ts`). - `pnpm exec vitest run packages/shared/src/crash-points.test.ts server/src/__tests__/crash-point-call-sites.test.ts` (fail mode, call sites). - `node scripts/typecheck-test-projects.mjs tests/restart-chaos`. - Chaos waves on master `1d67e309e0` server code (Daytona image `ghcr.io/paperclipai/paperclip-daytona-runner@sha256:99fc2671fc320816407f63cffd3acbd27471621febcd26494fe25bb5d7c5dd77`, content ID `1836c515…`), all RED unless noted: | Cell | Wave | Result on master | Staging class | | --- | --- | --- | --- | | W2/W2Q/W2C, 10 tasks on one Codex agent, `--daytona-warm`, K0 | `w-20261111T163206-s5201` | 9/10 fail. 3 tasks (W2 t02, W2C t03, t06): first fault `native_runner_process_exited`, same-run reattach, `native.remote_runner_recovery_failed` with `stage: process_verification`, `reason: process_not_running`, `runnerLifecycle: ready`, `runnerSettled: false`, terminal `runner_remote_process_identity_unavailable`, "Workspace repair required". 3 tasks (t04, t08, t10): `native_restart_recovery_blocked` (`native_retry_source_superseded`) while its successor ran (R4 `concurrent_runs`). 3 W2Q tasks: the answer's continuation was cancelled `issue_not_in_progress` (status `blocked`), and the task needed Retry. 2 W2C tasks then looped: 60+ succeeded runs in 20 minutes on an `in_progress` task. | Dβ€²/T terminal step reproduced with no restart, no governed wait and no PRP timeout (same error code and refusal fields). C+ retry outcome (ownership ambiguous) reproduced as `native_restart_recovery_blocked`. Not reproduced: `Controller journal drain timed out`, `did not durably suspend`, `journal_tool_input_unanswered`. | | Same, local `--lifecycle warm` | `w-20261111T160103-s5101` | 4/10 fail. 3/3 W2Q: continuation cancelled `issue_not_in_progress`, Retry needed. 1 W2C: the same `in_progress` run loop (39+ runs). | The remote-runner classes need a remote runner; locally they do not show. | | `--fail-recovery-step runnerd-start:1`, K1 at 10 s, local A1 | `w-20261111T162432-s5303` | Fail. After K1 the first runnerd start of recovery failed (`spawn paperclip-runnerd EAGAIN`); the run ended `native_provider_terminal_failed` ("previous turn is no longer active", "Automatic recovery stopped") and needed Retry. Control, same seed and K1 without the step fault (`w-20261111T171114-s5303`): pass. | A later recovery step that fails once ends the run instead of trying again (the A-chain shape). | | `runnerd-start:2`, local | `w-20261111T170909-s5304` | Step never reached: recovery started the runner once and succeeded. Grade fails `recovery_step_failed_once` (tested nothing). | β€” | | `teardown:1`, K1, Daytona A1 | `w-20261111T172048-s5312` | Pass. The teardown failed once and the sweep settled it. | Not reproduced. | | `directory-lock:1`, K2, Daytona A1 | `w-20261111T171247-s5311` | Step never reached by A1 after K2. | Not reproduced; A1 recovery does not collect remote agent files. | | K15 `--k15-fresh-home --k15-overlap-seconds 30-150`, `--storage s3`, Codex and OpenCode, T1/C1 | `w-20261111T173618-s5322` | 1/4 fail (OpenCode T1): `native_continuation_requires_reconciliation` with "Agent directory belongs to a different execution environment"; the Retry runs failed `adapter_failed` "Configured instruction entry is missing"; the task rests `blocked` on a board recovery action, and two sandboxes were left (R6). One Codex T1 task finished before its fault (`fault_crossed_tool`). | A-deploy: a controller-local file missing after a deploy without a volume. Here the missing file is the agent's instruction bundle, not a runtime-context asset; whether staging keeps instruction bundles outside the instance home is not verified. | | `--long-turn-minutes 15`, K1 at 600 s, local A1 | `w-20261111T175505-s5401` | Task pass (10/10 rounds, 992 s span, run 1019 s, K1 crossed mid-turn). The wave exited 2 only because I switched branches in the worktree during the wave. | Shape check only. | ## Risks - Product code changes are test instrumentation only: three `crashPoint` call sites take a fail-mode error, and one new call site was added. Disarmed (always in production) each call is one comparison. Moving the teardown point into its `try` does not change kill mode: the process dies at the same instant. - The new cells are opt-in. Default waves plan the same tasks as before for the same seed. - The W2 cells depend on model behaviour (phase 1 leaves the task open). The oracle records the task status at the wake. - `--k15-fresh-home` drops everything under the instance home. Whether staging keeps agent instruction bundles outside the instance home is not verified (see the K15 result). ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, agentic coding with tool use (shell, file edits, test and chaos runs) in Claude Code. ## 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 πŸ€– Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- packages/shared/src/crash-point-registry.ts | 7 + packages/shared/src/crash-points.test.ts | 37 ++- packages/shared/src/crash-points.ts | 55 +++- .../__tests__/crash-point-call-sites.test.ts | 3 +- .../agent-directory-working-copies.ts | 3 + server/src/services/environment-runtime.ts | 3 +- .../native-runtime/native-session-executor.ts | 4 +- tests/restart-chaos/README.md | 133 +++++++- tests/restart-chaos/config.ts | 27 +- tests/restart-chaos/edge-proxy.ts | 38 +++ tests/restart-chaos/journeys.ts | 1 + tests/restart-chaos/long-turn.ts | 100 ++++++ tests/restart-chaos/main.ts | 15 +- tests/restart-chaos/observer.ts | 16 +- tests/restart-chaos/recovery-step-faults.ts | 90 ++++++ tests/restart-chaos/redeploy.ts | 49 ++- tests/restart-chaos/rewake.ts | 293 ++++++++++++++++++ tests/restart-chaos/scheduler.ts | 12 +- tests/restart-chaos/shape-cells.test.ts | 252 +++++++++++++++ tests/restart-chaos/supervisor.ts | 133 +++++++- tests/restart-chaos/types.ts | 28 +- tests/restart-chaos/workloads.ts | 2 + .../runner-e2e/source-sdk-public-inputs.json | 6 +- 23 files changed, 1261 insertions(+), 46 deletions(-) create mode 100644 tests/restart-chaos/edge-proxy.ts create mode 100644 tests/restart-chaos/long-turn.ts create mode 100644 tests/restart-chaos/recovery-step-faults.ts create mode 100644 tests/restart-chaos/rewake.ts create mode 100644 tests/restart-chaos/shape-cells.test.ts diff --git a/packages/shared/src/crash-point-registry.ts b/packages/shared/src/crash-point-registry.ts index 8d6f60e8ad8..6e9694699cb 100644 --- a/packages/shared/src/crash-point-registry.ts +++ b/packages/shared/src/crash-point-registry.ts @@ -121,6 +121,13 @@ export const CRASH_POINTS = { invariants: ["I2"], prerequisite: "A reuse_by_environment lease that expires or is replaced (destroyReusableSandboxLease). The chaos Daytona environment's leases are ephemeral by default.", }, + "agent_directory.operation_lock.before_acquire": { + description: "A remote agent-directory operation (collect, checkpoint, release) is about to take its per-company-and-agent Postgres lock; no agent file has been read or written. In fail mode the call site throws the lock's own conflict (\"Agent directory operation is already active\"), staging class A's terminal step, so a recovery that collects a stopped run's agent files meets a held lock.", + environments: ["daytona"], + kinds: ["copyback_owner_hold"], + invariants: ["I2", "I7"], + prerequisite: "A remote (Daytona) agent directory copy: a task whose run materialized the agent's files in a sandbox.", + }, "environment.stop_retain.after_claim_before_stop": { description: "A stop-and-retain intent and its claim are committed; the provider stop has not been retried.", environments: ["daytona"], diff --git a/packages/shared/src/crash-points.test.ts b/packages/shared/src/crash-points.test.ts index 804a3acfd7a..3564a1f62d2 100644 --- a/packages/shared/src/crash-points.test.ts +++ b/packages/shared/src/crash-points.test.ts @@ -53,7 +53,13 @@ describe("parseCrashPointSpec", () => { describe("parseCrashPointControl", () => { it("reads a token and a spec, and treats anything else as disarmed", () => { - expect(parseCrashPointControl(`t1 ${first}:3\n`)).toEqual({ token: "t1", spec: { name: first, nth: 3 } }); + expect(parseCrashPointControl(`t1 ${first}:3\n`)).toEqual({ token: "t1", spec: { name: first, nth: 3 }, mode: "kill" }); + expect(parseCrashPointControl(`t1 ${first}:2 fail\n`)).toEqual({ token: "t1", spec: { name: first, nth: 2 }, mode: "fail" }); + expect(parseCrashPointControl(`t1 ${first}:2 fail pid=42`)).toEqual({ token: "t1", spec: { name: first, nth: 2 }, mode: "fail", pid: 42 }); + expect(parseCrashPointControl(`t1 ${first} pid=42`)).toEqual({ token: "t1", spec: { name: first, nth: 1 }, mode: "kill", pid: 42 }); + expect(parseCrashPointControl(`t1 ${first} fail fail`)).toBeNull(); + expect(parseCrashPointControl(`t1 ${first}:2 explode`)).toBeNull(); + expect(parseCrashPointControl(`t1 ${first}:2 fail extra`)).toBeNull(); expect(parseCrashPointControl("")).toBeNull(); expect(parseCrashPointControl(first)).toBeNull(); expect(parseCrashPointControl("t1 sandbox.create.after_typo")).toBeNull(); @@ -185,6 +191,35 @@ describe("crashPoint armed by the environment", { timeout: 60_000 }, () => { } }); + it("fails the nth hit once in fail mode, with the call site's own error, and never kills", () => { + const dir = mkdtempSync(path.join(os.tmpdir(), "crash-point-fail-")); + try { + const control = path.join(dir, "control"); + const receipt = path.join(dir, "receipt.jsonl"); + const hit = (label: string) => `try { crashPoint(${JSON.stringify(first)}, { fail: () => new Error("lock held") }); process.stdout.write("${label}-ok\\n"); }` + + ` catch (error) { process.stdout.write("${label}-" + error.message + "\\n"); }`; + const source = [ + `const { crashPoint } = await import(${JSON.stringify(path.join(import.meta.dirname, "crash-points.ts"))});`, + `const { writeFileSync } = await import("node:fs");`, + `writeFileSync(${JSON.stringify(control)}, "t1 ${first}:2 fail\\n");`, + hit("one"), hit("two"), hit("three"), + `try { crashPoint(${JSON.stringify(second)}); crashPoint(${JSON.stringify(first)}); process.stdout.write("plain-ok\\n"); } catch (error) { process.stdout.write("plain-" + error.name + "\\n"); }`, + `writeFileSync(${JSON.stringify(control)}, "t3 ${first} fail pid=1\\n");`, + `try { crashPoint(${JSON.stringify(first)}); process.stdout.write("other-pid-ok\\n"); } catch (error) { process.stdout.write("other-pid-" + error.name + "\\n"); }`, + `writeFileSync(${JSON.stringify(control)}, "t2 ${first} fail pid=" + process.pid + "\\n");`, + `try { crashPoint(${JSON.stringify(first)}); } catch (error) { process.stdout.write("default-" + error.name + "\\n"); }`, + ].join("\n"); + const result = runChild({ PAPERCLIP_CRASH_POINT_CONTROL: control, PAPERCLIP_CRASH_POINT_RECEIPT: receipt }, source); + expect(result.signal).toBeNull(); + expect(result.stdout).toBe("one-ok\ntwo-lock held\nthree-ok\nplain-ok\nother-pid-ok\ndefault-CrashPointInjectedFailure\n"); + const receipts = readFileSync(receipt, "utf8").trim().split("\n").map(line => JSON.parse(line)); + expect(receipts).toEqual([expect.objectContaining({ point: first, hit: 2, token: "t1", mode: "fail" }), + expect.objectContaining({ point: first, hit: 1, token: "t2", mode: "fail" })]); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + it("stays disarmed in production", () => { const result = runChild({ PAPERCLIP_CRASH_POINT: first, NODE_ENV: "production" }); expect(result.signal).toBeNull(); diff --git a/packages/shared/src/crash-points.ts b/packages/shared/src/crash-points.ts index d9f31d95c78..c15259f3961 100644 --- a/packages/shared/src/crash-points.ts +++ b/packages/shared/src/crash-points.ts @@ -16,10 +16,17 @@ * * Runtime arming (one booted server, many points), instead of PAPERCLIP_CRASH_POINT: * - * PAPERCLIP_CRASH_POINT_CONTROL= each hit reads " [:]" from the file; + * PAPERCLIP_CRASH_POINT_CONTROL= each hit reads " [:] [fail]" from the file; * no file or an empty one means disarmed. Hits count per * token, so writing a new token re-arms with a fresh count. * + * Fail mode (control file only): a trailing `fail` makes the nth hit throw instead of + * killing the process, once. An optional `pid=` binds a line to one process, so a + * server started earlier (still draining) never counts its hits. The call site may name the error its real step throws + * (`crashPoint(name, { fail: () => conflict("...") })`); otherwise it throws + * `CrashPointInjectedFailure`. The restart-chaos harness uses it to fail the Nth + * attempt of a recovery step (`--fail-recovery-step`), so recovery chains are exercised. + * * The variable is read once, when this module is first imported. It is ignored * when `NODE_ENV=production`, and an unknown name throws at import so a typo * cannot silently arm nothing. Disarmed, `crashPoint` is a single comparison @@ -47,6 +54,10 @@ export const CRASH_POINT_CONTROL_ENV = "PAPERCLIP_CRASH_POINT_CONTROL"; export const CRASH_POINT_LOG_PREFIX = "[crash-point]"; export type CrashPointSpec = { name: CrashPointName; nth: number }; +/** `kill` (default) SIGKILLs the process at the hit; `fail` throws once (control file only). */ +export type CrashPointMode = "kill" | "fail"; +/** What the call site's real step throws when it fails; used in fail mode. */ +export type CrashPointOptions = { fail?: () => Error }; export type CrashPointReceipt = { point: CrashPointName; @@ -55,8 +66,18 @@ export type CrashPointReceipt = { at: string; /** Runtime arming only: the control file token the hit counted under. */ token?: string; + /** Present for fail mode: the hit threw instead of killing the process. */ + mode?: "fail"; }; +/** Thrown at a point armed in fail mode whose call site names no error of its own. */ +export class CrashPointInjectedFailure extends Error { + constructor(readonly point: CrashPointName, readonly hit: number) { + super(`injected failure at ${point} (hit ${hit})`); + this.name = "CrashPointInjectedFailure"; + } +} + /** Thrown by a point armed with `armCrashPointForTest`. */ export class CrashPointReached extends Error { constructor(readonly point: CrashPointName, readonly hit: number) { @@ -84,7 +105,7 @@ export function parseCrashPointSpec(raw: string | undefined): CrashPointSpec | n type Armed = { spec: CrashPointSpec; hits: number; - mode: "kill" | "throw"; + mode: "kill" | "throw" | "fail"; receiptPath: string | null; /** Hits count only once this file exists; null when ungated. */ gatePath: string | null; @@ -93,13 +114,21 @@ type Armed = { token?: string | null; }; -/** Parses a control file line, " [:]"; null when empty or malformed. */ -export function parseCrashPointControl(text: string): { token: string; spec: CrashPointSpec } | null { +/** Parses a control file line, " [:] [fail] [pid=]"; null when empty or malformed. */ +export function parseCrashPointControl(text: string): { token: string; spec: CrashPointSpec; mode: CrashPointMode; pid?: number } | null { const [token, raw, ...rest] = text.trim().split(/\s+/); - if (!token || !raw || rest.length > 0) return null; + if (!token || !raw || rest.length > 2) return null; + let mode: CrashPointMode = "kill"; + let pid: number | undefined; + for (const option of rest) { + const match = /^pid=([1-9][0-9]{0,9})$/.exec(option); + if (option === "fail" && mode === "kill") mode = "fail"; + else if (match && pid === undefined) pid = Number(match[1]); + else return null; + } try { const spec = parseCrashPointSpec(raw); - return spec ? { token, spec } : null; + return spec ? { token, spec, mode, ...(pid !== undefined ? { pid } : {}) } : null; } catch { return null; } @@ -132,13 +161,13 @@ let armed: Armed | null = armFromEnvironment(); * immediately. Armed for this name, the nth hit kills the process with SIGKILL * (or throws `CrashPointReached` under `armCrashPointForTest`). */ -export function crashPoint(name: CrashPointName): void { +export function crashPoint(name: CrashPointName, options?: CrashPointOptions): void { if (armed === null) return; if (armed.controlPath) { if (!readControl(armed)) return; } if (armed.spec.name !== name) return; - reach(armed); + reach(armed, options); } /** Runtime arming: loads the control file's spec; a new token resets the count. */ @@ -147,15 +176,18 @@ function readControl(current: Armed): boolean { try { text = readFileSync(current.controlPath!, "utf8"); } catch { return false; } const control = parseCrashPointControl(text); if (!control) return false; + // A line bound to another process is disarmed here. + if (control.pid !== undefined && control.pid !== process.pid) return false; if (control.token !== current.token) { current.token = control.token; current.spec = control.spec; + current.mode = control.mode; current.hits = 0; } return true; } -function reach(current: Armed): void { +function reach(current: Armed, options?: CrashPointOptions): void { if (current.gatePath !== null) { if (!existsSync(current.gatePath)) return; current.gatePath = null; @@ -166,10 +198,15 @@ function reach(current: Armed): void { const receipt: CrashPointReceipt = { point: current.spec.name, hit: current.hits, pid: process.pid, at: new Date().toISOString(), ...(current.token ? { token: current.token } : {}), + ...(current.mode === "fail" ? { mode: "fail" as const } : {}), }; if (current.receiptPath) { try { appendFileSync(current.receiptPath, `${JSON.stringify(receipt)}\n`); } catch { /* the log line below still records it */ } } + if (current.mode === "fail") { + try { process.stderr.write(`${CRASH_POINT_LOG_PREFIX} FAIL ${JSON.stringify(receipt)}\n`); } catch { /* ignore */ } + throw options?.fail?.() ?? new CrashPointInjectedFailure(current.spec.name, current.hits); + } try { process.stderr.write(`${CRASH_POINT_LOG_PREFIX} SIGKILL ${JSON.stringify(receipt)}\n`); } catch { /* ignore */ } process.kill(process.pid, "SIGKILL"); } diff --git a/server/src/__tests__/crash-point-call-sites.test.ts b/server/src/__tests__/crash-point-call-sites.test.ts index ea26342286b..60d619f4d75 100644 --- a/server/src/__tests__/crash-point-call-sites.test.ts +++ b/server/src/__tests__/crash-point-call-sites.test.ts @@ -6,7 +6,8 @@ import { OWNABLE_KINDS } from "../services/recovery/ownership-registry.js"; const repositoryRoot = path.resolve(import.meta.dirname, "../../.."); const SOURCE_ROOTS = ["server/src", "packages/paperclip-runner/src"]; -const CALL = /\bcrashPoint\(\s*"([^"]+)"\s*\)/g; +// A call may pass fail-mode options after the name: crashPoint("", { fail: ... }). +const CALL = /\bcrashPoint\(\s*"([^"]+)"\s*[,)]/g; function sourceFiles(directory: string): string[] { return readdirSync(directory, { withFileTypes: true }).flatMap(entry => { diff --git a/server/src/services/agent-directory-working-copies.ts b/server/src/services/agent-directory-working-copies.ts index b1c8de72e5d..3e277345440 100644 --- a/server/src/services/agent-directory-working-copies.ts +++ b/server/src/services/agent-directory-working-copies.ts @@ -20,6 +20,7 @@ import { hasRemoteTerminationReceipt, resolveRemoteTerminationLease } from "./re import { cachedAgentFileManifest, captureAgentFileCheckpoint, checkpointBaseline, checkpointSnapshot, type AgentFileManifest } from "./agent-file-checkpoints.js"; import { withWorkspaceLockKeepalive } from "./native-runtime/native-workspace-lock-keepalive.js"; import { logger } from "../middleware/logger.js"; +import { crashPoint } from "@paperclipai/shared/crash-points"; type Copy = typeof copies.$inferSelect; function adoptionAuthority(row: Copy) { @@ -654,6 +655,8 @@ export function agentDirectoryWorkingCopyService(db: Db, get: (companyId: string if (!disposableRemoteCopy(row)) return run(); // Different controllers have different cache roots. Serialize their active // collection/cleanup operations in Postgres, without holding row locks over I/O. + // Test instrumentation only (disarmed in production): restart chaos fails the Nth attempt with the lock's own conflict. + crashPoint("agent_directory.operation_lock.before_acquire", { fail: () => conflict("Agent directory operation is already active") }); return withDedicatedDbConnection(db, dedicated => dedicated.transaction(async tx => { const [lock] = await tx.execute(sql`select pg_try_advisory_xact_lock(hashtextextended(${`agent-directory:${row.companyId}:${row.agentId}`}, 0)) as acquired, (select setting::bigint from pg_settings where name = 'idle_in_transaction_session_timeout') as idle_timeout_ms`); diff --git a/server/src/services/environment-runtime.ts b/server/src/services/environment-runtime.ts index 8252eebfb1f..8c84a559b04 100644 --- a/server/src/services/environment-runtime.ts +++ b/server/src/services/environment-runtime.ts @@ -3853,10 +3853,11 @@ export function environmentRuntimeService( )`, )).returning(), { companyId: input.leaseRow.companyId, runId: input.leaseRow.heartbeatRunId ?? undefined }); if (!claimed) return null; - crashPoint("environment.teardown.after_claim_before_destroy"); const lease = toEnvironmentLeaseSnapshot(claimed); const renewal = renewCleanupClaim(lease.id, attemptId, "scoped cleanup ownership renewal failed"); try { + // Kill mode leaves the claim in flight; fail mode (restart chaos only) is a provider destroy that did not finish. + crashPoint("environment.teardown.after_claim_before_destroy", { fail: () => new Error("sandbox teardown incomplete: provider destroy did not finish") }); const driver = getDriver(getLeaseDriverKey(lease, input.environment)); if (!driver?.destroyRunLease) return lease; const released = await driver.destroyRunLease({ diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index c46e7976c96..8cf6139f013 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -11913,7 +11913,9 @@ async function executePaperclipNativeSessionAttempt( // the work-based budget (provider-attempt-outcome.ts). payload: { hostname: hostname(), providerAttempt: attempt, requestedAt: new Date().toISOString() }, }); - crashPoint("native.process_start.after_requested_before_spawn"); + // Fail mode (restart chaos only) is a runnerd start that failed before the process existed. + crashPoint("native.process_start.after_requested_before_spawn", { fail: () => Object.assign( + new Error("spawn paperclip-runnerd EAGAIN"), { code: "EAGAIN", syscall: "spawn paperclip-runnerd" }) }); }, input: runnerExecution, startup: executionContext && (!usesPluginTask || executionContext.pluginSupported) ? executionContext : undefined, diff --git a/tests/restart-chaos/README.md b/tests/restart-chaos/README.md index e96feb427fd..ee87afb64aa 100644 --- a/tests/restart-chaos/README.md +++ b/tests/restart-chaos/README.md @@ -22,9 +22,11 @@ node scripts/typecheck-test-projects.mjs tests/restart-chaos # typecheck ``` Options: `--triggers time,comment,retry,queued,tool,result` (fault timing, below), -`--workloads A1,B1,B5,C1` (opt-in: G1, H1, L1, R1, S1), `--db-pressure ` (below), `--budget-cents` (company hard cap, +`--workloads A1,B1,B5,C1` (opt-in: G1, H1, L1, R1, S1, W2, W2Q, W2C), `--db-pressure ` (below), `--budget-cents` (company hard cap, default 3000), `--poll-ms` (2000–5000), `--keep` (keep the temporary instance), `--k4-hold-max-seconds` (raise the seeded K4 hold upper end from 300 s, up to the 600 s outage cap). +`--faults K0` plans cells with no fault, for workloads whose shape is the fault (W2, below). `--fail-recovery-step`, +`--long-turn-minutes`, `--k15-overlap-seconds` and `--k15-fresh-home` are described in their own sections. `--fault-after-seconds ` fires every planned fault `n` seconds after its task launches (5–3600; with `--triggers time`), keeping the rest of the seeded plan, for example to restart a Daytona R1 task after its workspace preparation. `--matrix` crosses every selected workload with every fault kind (below), and `--server-from ` @@ -389,6 +391,35 @@ minutes. In staging class R, recovery then found the remote Runner gone `deadlineExceeded`, and the restart continues. A probe that answers after the deadline writes nothing, because its evidence is from after the outage window. +### Redeploy without a volume, with overlap (`--k15-fresh-home`, `--k15-overlap-seconds`) + +```sh +node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/main.ts --env daytona --daytona-image $IMG --daytona-cpu 3 --storage s3 \ + --adapters codex,opencode --workloads A1,C1 --faults K15 --k15-fresh-home --k15-overlap-seconds 30-150 --concurrency 3 --tasks 6 --seed 9320 +``` + +Staging's deploys after 07:25Z on 2026-11-11 reported `volumeId: null`, and the old container kept running +for a while after the new one was up. Plain K15 restarts on the same instance home and has no overlap. + +- **`--k15-fresh-home`** (Daytona only): every deploy generation gets a new, empty instance home + (`home-g` in the wave's temporary root) and no `RAILWAY_VOLUME_*` variables. Only what a hosted + deploy gets from outside its container is carried over: the configuration (database, storage) and the + secrets master key. Controller-local files such as `runtime-context-assets` bundles and runtime caches + are gone, as in staging class A-deploy (`ENOENT … runtime-context-assets/bundles/…`). Use + `--storage s3`, as staging does. A local run keeps its workspace and runner under the instance home, so + the option refuses `--env local`. +- **`--k15-overlap-seconds ` or `-`** (5–600 s; staging's shape is 30–150): the wave's port + becomes an edge proxy (`edge-proxy.ts`), and each server listens on its own port behind it. A K15 boots + the next generation beside the old server, sends new connections to it once its `/api/ready` reports + `ready`, keeps the old server running for the seeded overlap, then stops the old one with SIGTERM. There + is no outage, so the seeded K15 hold is the overlap; it does not combine with `--k15-hold-seconds`. + The timeline records `k15_fresh_home`, `k15_traffic_switched` and `fault_server_down` (the old server's + stop). + +Pass is the usual grade: no Retry (R3), no stuck record (R6), and the oracle. Staging's terminal errors here +were `ENOENT` on a runtime asset, `Agent directory operation is already active` after a 9.5-minute +`controller_lease_held` wait. + ## Absolute symlink in the workspace (F1) ```sh @@ -957,6 +988,102 @@ plus `predecessor_unretirable_fell_back` and `follow_up_fresh_sandbox` (the succ on a different sandbox than the asking run). SR1U needs `--env daytona --daytona-warm`, and it arms its fault for the whole server, so it does not share a wave with SR1. +## Re-wake after success (W2, W2Q, W2C) + +```sh +# Ten tasks on one Codex agent with warm sandboxes; each task is woken again 0–60 s after its run succeeded. +node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/main.ts --env daytona --daytona-image $IMG --daytona-warm --daytona-cpu 3 \ + --adapters codex --workloads W2,W2Q,W2C --faults K0 --concurrency 10 --tasks 10 --seed 5201 +# The same locally (warm local Runners). +node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/main.ts --env local --lifecycle warm \ + --adapters codex --workloads W2,W2Q,W2C --faults K0 --concurrency 10 --tasks 10 --seed 5101 +``` + +In one 8-hour staging window (2026-11-11), 20 of 25 failures happened with no restart at all. One agent had +10–13 runs at once on reused sandboxes, and 30–60 s after a 20–43 minute run of a task succeeded, an +ordinary wake (`issue_commented`, `issue_monitor_due`) started the next run of that task. That run had to +retire the previous run's warm owner first, and failed before any provider work: `Controller journal drain +timed out`, `runner did not durably suspend before checkpoint` (class C+), or +`journal_tool_input_unanswered` after a predecessor that ended on an unanswered question (class C3). + +The workload is the fault, so these cells usually run with `--faults K0` (no fault). Every task of an +adapter runs on that adapter's one agent: `--adapters codex --tasks 10 --concurrency 10` is ten tasks on one +agent. Phase 1 ends with the task left `in_progress` (`in_review` would gate completion on a review). Then the harness, as the board, wakes the same task the +seeded 0–60 s after that run settled (`rewake.ts`): + +- **W2**: a board comment, or, by the task's nonce, a board-scheduled issue monitor due now, so the + scheduler's own `issue_monitor_due` wake starts the run. +- **W2Q**: phase 1 asks one `request_human_input` question and parks. A board comment (a note to include, + not the answer) wakes the task while the question is pending. The board answers after that run settled. +- **W2C**: as W2, and first the board changes the agent's `adapterConfig.idleTimeoutMs`, so the next run + cannot resume the saved session. SR1 (`session-faults.ts`, #20844) is the same change while a question + is parked; W2C is the change after a run succeeded. + +Until the wake is served (and, for W2Q, answered), the task waits on the board: not a rest, no Retry. The +oracle checks that phase 1 succeeded, the wake was sent and a run created after it succeeded, +`no_failed_attempt` (no run of the task failed or timed out), the task is `done`, and the brief's markers. +A task left blocked gets the usual Retry (R3), which fails the grade. A restart fault (for example K2) +may also join; it lands around the first run or the wake. + +Add `--long-turn-minutes 20` for staging's long predecessor turns. + +## Fail the Nth recovery step (`--fail-recovery-step`) + +```sh +# Local: K1, then the replacement's first runnerd start fails once (spawn EAGAIN). +node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/main.ts --env local --adapters codex --workloads A1 \ + --faults K1 --fail-recovery-step runnerd-start:1 --fault-after-seconds 10 --concurrency 1 --tasks 1 --seed 5303 +# Daytona: K1, then the replacement's first sandbox teardown does not finish. +node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/main.ts --env daytona --daytona-image $IMG --daytona-cpu 3 \ + --adapters codex --workloads A1 --faults K1 --fail-recovery-step teardown:1 --fault-after-seconds 30 --concurrency 1 --tasks 1 --seed 5312 +``` + +Every other fault hits the control plane once and lets recovery run. On staging the first fault was often +harmless and a later step failed: a bootstrap retry met a missing runtime asset, a reattach met +`Agent directory operation is already active`, a bounded retry met an unfinished teardown. + +`--fail-recovery-step [:]` lets the wave's first restart fault (K1, K2, K4, K6, K14, K15 or +RR1–RR3) fire normally. When that fault's replacement server starts, the harness arms one crash point in +fail mode: the nth hit of the point in the replacement throws, once, the error its real step throws. The +control line is bound to the replacement's pid (`pid=`), so an old server still draining during a K15 +overlap never counts hits, and the harness disarms it once the receipt lands, so a later restart (RR, K6, +another task's fault) does not fail the step again. `nth` +1 fails recovery's first attempt at the step, 2 its second, 3 its third. Steps: + +| Step | Crash point | Error thrown | Environments | +| --- | --- | --- | --- | +| `runnerd-start` | `native.process_start.after_requested_before_spawn` | `spawn paperclip-runnerd EAGAIN` | local, Daytona | +| `teardown` | `environment.teardown.after_claim_before_destroy` | `sandbox teardown incomplete: provider destroy did not finish` | Daytona | +| `directory-lock` | `agent_directory.operation_lock.before_acquire` | `Agent directory operation is already active` (409) | Daytona | + +Any other registered crash point name also works; without its own error it throws +`CrashPointInjectedFailure`. Hits count across the server, so with several tasks in flight the nth hit can +belong to any of them: run one task per wave to aim at one task's nth attempt. A step that recovery calls +only once is never reached with `nth` 2 or more, and the task fails `recovery_step_failed_once`. On +2026-11-11 an A1 task with K2 on Daytona never reached `directory-lock`: pick a workload whose recovery +collects remote agent files. + +Every task the armed fault crossed gets two more checks: `recovery_step_failed_once` (the receipt in +`recovery-step-receipts.jsonl`; a step never reached tested nothing) and `no_failed_attempt`. The fault's +receipt in `faults.json` names the armed step (`recoveryStep`). + +## Long turn (`--long-turn-minutes`) + +```sh +node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/main.ts --env daytona --daytona-image $IMG --daytona-warm --daytona-cpu 3 \ + --adapters codex --workloads W2 --faults K0 --long-turn-minutes 20 --concurrency 4 --tasks 4 --seed 5401 +``` + +Staging's failures followed turns of 14–43 minutes; every other workload finishes in a few. With +`--long-turn-minutes ` (15–60, opt-in), every task's first turn first runs n minutes of real tool work: +rounds of one foreground shell command each (about 90 s of hashing and sleeping, short of provider +shell-tool timeouts) that append `ROUND ` to a log in the working directory. The agent +saves the log as the issue document `long-turn` and then does its workload in the same turn +(`long-turn.ts`). Any workload and fault can take it; the task's time budget grows by n minutes. Two checks +join the oracle: `long_turn_rounds` (every round reported, spanning n minutes) and `long_turn_run_observed` +(the harness saw one run of the task last n minutes). Use `--fault-after-seconds` to land a fault late in +the turn. Waves get long and expensive: keep them small. + ## Database contention (L1, `--db-pressure`) ```sh @@ -1474,6 +1601,10 @@ and grades only (no server logs). 4. Run the point: `node scripts/crash-points.mjs --points `. A `not_reached` result means the workload never crosses it. +**Fail mode.** A control-file line may end in `fail` (` : fail`): the nth hit then +throws once instead of killing the server. An optional `pid=` binds the line to one server process. A call site can name the error its real step throws +(`crashPoint("", { fail: () => conflict("...") })`). `--fail-recovery-step` uses it. + Disarmed, a point costs one comparison (about 4 ns), and the arming variables (`PAPERCLIP_CRASH_POINT`, `PAPERCLIP_CRASH_POINT_CONTROL`) are ignored under `NODE_ENV=production`, so points may sit on the path before `turn.start`. diff --git a/tests/restart-chaos/config.ts b/tests/restart-chaos/config.ts index 1e532c83885..0dba1ec0ed8 100644 --- a/tests/restart-chaos/config.ts +++ b/tests/restart-chaos/config.ts @@ -5,7 +5,10 @@ import { applyJourneyOptions } from "./journey-matrix.js"; import { takesJourneyTriggers } from "./journeys.js"; import { STORAGE_FAULT_KINDS, type StorageFaultKind } from "./storage-chaos.js"; import { isMultiServerFault, validateMultiServerOptions } from "./multi-server.js"; -import { parseK15HoldSeconds } from "./redeploy.js"; +import { parseK15DeployShape, parseK15HoldSeconds } from "./redeploy.js"; +import { validateRecoveryStep } from "./recovery-step-faults.js"; +import { parseLongTurnMinutes } from "./long-turn.js"; +import { isRewakeWorkload } from "./rewake.js"; import { parseTimeFaultOptions } from "./time-faults-config.js"; import { parseStorageTrigger } from "./storage-trigger.js"; import { parseNativeTrigger, parseNativeTriggerOutage } from "./native-trigger.js"; @@ -137,14 +140,18 @@ export function parseCommand(argv: readonly string[], now = Date.now()): ParsedC "rr-gap-seconds": { type: "string" }, "rr-stop-on": { type: "string" }, "k15-hold-seconds": { type: "string" }, + "k15-overlap-seconds": { type: "string" }, + "k15-fresh-home": { type: "boolean" }, "tm1-hold-seconds": { type: "string" }, + "fail-recovery-step": { type: "string" }, + "long-turn-minutes": { type: "string" }, }, }); const keep = values.keep === true; const pollMs = integer(values["poll-ms"], "poll-ms", 3_000, 2_000, 5_000); const budgetCents = integer(values["budget-cents"], "budget-cents", 3_000, 1, 100_000); if (values.replay !== undefined) { - for (const key of ["env", "adapters", "workloads", "faults", "triggers", "concurrency", "tasks", "seed", "daytona-image", "daytona-pack-mismatch", "daytona-cpu", "daytona-reuse-lease", "daytona-warm", "daytona-inherit", "storm-minutes", "lifecycle", "k4-hold-max-seconds", "crash-point", "crash-point-hold-ms", "upgrade-from", "workspace-repo", "storage", "storage-faults", "storage-fault-seconds", "storage-trigger", "native-trigger", "native-trigger-outage", "fault-after-seconds", "provider-fault-message", "provider-fault-delays", "db-pressure", "matrix", "server-from", "time-age-hours", "provider-fault-restart", "provider-fault-restart-after-seconds", "rr-gap-seconds", "rr-stop-on", "k15-hold-seconds", "tm1-hold-seconds"] as const) { + for (const key of ["env", "adapters", "workloads", "faults", "triggers", "concurrency", "tasks", "seed", "daytona-image", "daytona-pack-mismatch", "daytona-cpu", "daytona-reuse-lease", "daytona-warm", "daytona-inherit", "storm-minutes", "lifecycle", "k4-hold-max-seconds", "crash-point", "crash-point-hold-ms", "upgrade-from", "workspace-repo", "storage", "storage-faults", "storage-fault-seconds", "storage-trigger", "native-trigger", "native-trigger-outage", "fault-after-seconds", "provider-fault-message", "provider-fault-delays", "db-pressure", "matrix", "server-from", "time-age-hours", "provider-fault-restart", "provider-fault-restart-after-seconds", "rr-gap-seconds", "rr-stop-on", "k15-hold-seconds", "k15-overlap-seconds", "k15-fresh-home", "tm1-hold-seconds", "fail-recovery-step", "long-turn-minutes"] as const) { if (values[key] !== undefined) throw new Error(`--replay reproduces the saved plan; do not combine it with --${key}`); } return { mode: "replay", ref: parseReplayRef(values.replay), keep, @@ -186,23 +193,25 @@ export function parseCommand(argv: readonly string[], now = Date.now()): ParsedC if (lifecycle !== undefined && lifecycle !== "per_turn" && lifecycle !== "warm" && lifecycle !== "default") throw new Error("--lifecycle must be per_turn, warm or default"); const adapters = list(values.adapters, ADAPTER_IDS, "adapters", ["codex", "claude"]); // `--faults` takes restart faults (K*), provider message faults (PV*, provider-faults.ts), the - // sandbox disk-full fault (DF1, disk-full-faults.ts) and session faults (SR*, session-faults.ts). - const allFaults = list(values.faults, [...FAULT_KINDS, ...PROVIDER_FAULT_KINDS, ...DISK_FULL_FAULT_KINDS, ...SESSION_FAULT_KINDS], "faults", + // sandbox disk-full fault (DF1, disk-full-faults.ts), session faults (SR*, session-faults.ts) and K0, cells with no fault. + const allFaults = list(values.faults, [...FAULT_KINDS, ...PROVIDER_FAULT_KINDS, ...DISK_FULL_FAULT_KINDS, ...SESSION_FAULT_KINDS, "K0"], "faults", stormMinutes ? STORM_DEFAULT_FAULTS : crashPoint ? ["K1"] : ["K1", "K2", "K4"]); const providerFaults = allFaults.filter(isProviderFault); const diskFullFaults = allFaults.filter(isDiskFullFault); const sessionFaults = allFaults.filter(isSessionFault); + const baseline = allFaults.includes("K0"); const options: WaveOptions = { env, adapters, // The governance scenarios (G1, H1), the journeys (Q1–Q4) and the contention run (L1) are opt-in: H1 needs a wave of its own. workloads: list(values.workloads, workloadChoices, "workloads", workloadChoices.filter(id => id !== "G1" && id !== "H1" && id !== "R1" && id !== "S1" && id !== "L1" && id !== "F1" && id !== "T1" && id !== "Q4" - && !takesJourneyTriggers(id) && (id !== "M1" || adapters.length >= 2))), + && !takesJourneyTriggers(id) && !isRewakeWorkload(id) && (id !== "M1" || adapters.length >= 2))), // A crash-point wave schedules no fault; K1 is the restart its self-kill gets. - faults: allFaults.filter((fault): fault is FaultKind => !isProviderFault(fault) && !isDiskFullFault(fault) && !isSessionFault(fault)), + faults: allFaults.filter((fault): fault is FaultKind => !isProviderFault(fault) && !isDiskFullFault(fault) && !isSessionFault(fault) && fault !== "K0"), ...(providerFaults.length ? { providerFaults } : {}), ...(diskFullFaults.length ? { diskFullFaults } : {}), ...(sessionFaults.length ? { sessionFaults } : {}), + ...(baseline ? { baseline: true } : {}), triggers: list(values.triggers, TRIGGER_IDS, "triggers", ["time"]), concurrency: integer(values.concurrency, "concurrency", 4, 1, 20), tasks: integer(values.tasks, "tasks", stormMinutes ? 200 : 8, 1, 200), @@ -239,6 +248,11 @@ export function parseCommand(argv: readonly string[], now = Date.now()): ParsedC // The matrix planner builds its cells from restart and provider faults only; DF1 would silently drop out. if (values.matrix) throw new Error("The disk-full fault (DF1) is not a --matrix cell; run it as a planned wave"); } + if (baseline && (stormMinutes || crashPoint)) throw new Error("--faults K0 plans cells with no fault; a storm or crash-point wave has its own faults"); + Object.assign(options, validateRecoveryStep(options, values["fail-recovery-step"])); + Object.assign(options, parseLongTurnMinutes(values["long-turn-minutes"])); + // The matrix planner builds its own task plans; a long turn would silently drop out of them. + if (options.longTurnMinutes && values.matrix) throw new Error("--long-turn-minutes is not a --matrix option; run it as a planned wave"); if (providerFaults.length) { if (stormMinutes) throw new Error("Provider message faults (PV*) are planned per task; do not combine them with --storm-minutes"); if (env !== "local") throw new Error("Provider message faults (PV*) shim the local provider; run them with --env local"); @@ -294,6 +308,7 @@ export function parseCommand(argv: readonly string[], now = Date.now()): ParsedC Object.assign(options, parseTimeFaultOptions(options, values["time-age-hours"], values["tm1-hold-seconds"])); Object.assign(options, parseRepeatedRestartOptions(options, values["rr-gap-seconds"], values["rr-stop-on"])); Object.assign(options, parseK15HoldSeconds(options, values["k15-hold-seconds"])); + Object.assign(options, parseK15DeployShape(options, values["k15-overlap-seconds"], values["k15-fresh-home"] === true)); const upgradeFrom = values["upgrade-from"]; if (options.faults.includes("K14") !== (upgradeFrom !== undefined)) { throw new Error("K14 (upgrade mid-run) and --upgrade-from go together: pass both or neither"); diff --git a/tests/restart-chaos/edge-proxy.ts b/tests/restart-chaos/edge-proxy.ts new file mode 100644 index 00000000000..b9f2700f102 --- /dev/null +++ b/tests/restart-chaos/edge-proxy.ts @@ -0,0 +1,38 @@ +/** + * `--k15-overlap-seconds`: the wave's stable port in front of the serving deploy generation, as the hosting + * platform's edge is in front of its containers. Each server of such a wave listens on its own loopback port; + * the proxy forwards new connections to the current one. A K15 switches the target once the next generation is + * ready, while the old server keeps its open connections until it is stopped, as a rolling deploy does. + */ +import net from "node:net"; + +export interface EdgeProxy { + readonly port: number; + /** The backend port new connections go to. */ + target: number; + close(): Promise; +} + +export async function startEdgeProxy(port: number, target: number): Promise { + const sockets = new Set(); + const proxy: EdgeProxy = { port, target, close: async () => { + for (const socket of sockets) socket.destroy(); + await new Promise(resolve => server.close(() => resolve())); + } }; + const server = net.createServer(client => { + const upstream = net.connect(proxy.target, "127.0.0.1"); + for (const socket of [client, upstream]) { + sockets.add(socket); + socket.on("close", () => sockets.delete(socket)); + // A backend that is gone or restarting refuses the connection: the client sees a reset, as at the edge. + socket.on("error", () => { client.destroy(); upstream.destroy(); }); + } + client.pipe(upstream); + upstream.pipe(client); + }); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(port, "127.0.0.1", () => { server.off("error", reject); resolve(); }); + }); + return proxy; +} diff --git a/tests/restart-chaos/journeys.ts b/tests/restart-chaos/journeys.ts index 67a54a9fb72..7d49bc0494e 100644 --- a/tests/restart-chaos/journeys.ts +++ b/tests/restart-chaos/journeys.ts @@ -36,6 +36,7 @@ export type JourneyTrigger = (typeof JOURNEY_TRIGGERS)[number]; export const WORKLOAD_TRIGGERS: Record = { A1: ["time"], B1: ["time"], B5: ["tool"], C1: ["comment", "result"], M1: ["time"], G1: ["approval"], H1: ["paused"], R1: ["time"], S1: ["stop"], L1: ["time"], F1: ["time"], T1: ["time"], Q1: JOURNEY_TRIGGERS, Q2: JOURNEY_TRIGGERS, Q3: JOURNEY_TRIGGERS, Q4: ["time"], + W2: ["time"], W2Q: ["time"], W2C: ["time"], }; /** Q3 reviews must survive a delay longer than the implicit deadline #20340 removed. */ diff --git a/tests/restart-chaos/long-turn.ts b/tests/restart-chaos/long-turn.ts new file mode 100644 index 00000000000..8760db54d64 --- /dev/null +++ b/tests/restart-chaos/long-turn.ts @@ -0,0 +1,100 @@ +/** + * `--long-turn-minutes ` (15–60): every task's first turn does n minutes of real tool work before its + * workload, for any cell (README "Long turn"). + * + * The staging failures of 2026-11-11 followed turns of 14–43 minutes, while every chaos workload finishes in + * a few minutes. A long turn grows what the run holds when its fault or next wake arrives: the provider + * session's history, the controller journal, tool receipts and the sandbox's working files. + * + * The agent runs one shell command per round, in the foreground, each about 90 s (well short of provider + * shell-tool timeouts). Each round appends `ROUND ` to a log in its working directory and + * hashes data as it goes. Then it saves the log as the issue document `long-turn` and carries on with the + * workload. The oracle checks the rounds the agent reported and, from the harness's own observations, that + * one run of the task ran at least n minutes. + */ +import type { OracleArtifacts, OracleResult } from "./types.js"; +import type { WorkloadDefinition } from "./workloads.js"; + +export const LONG_TURN_MINUTES_RANGE: readonly [number, number] = [15, 60]; +/** Seconds of one round (45 ticks of 2 s). */ +export const LONG_TURN_ROUND_SECONDS = 90; +export const LONG_TURN_DOCUMENT = "long-turn"; +/** Sandbox and host clocks differ, and a round may start a little late: slack on the reported span. */ +const SPAN_SLACK_SECONDS = 60; + +export function parseLongTurnMinutes(raw: string | undefined): { longTurnMinutes?: number } { + if (raw === undefined) return {}; + if (!/^[0-9]+$/.test(raw)) throw new Error("--long-turn-minutes takes whole minutes"); + const minutes = Number(raw); + const [min, max] = LONG_TURN_MINUTES_RANGE; + if (minutes < min || minutes > max) throw new Error(`--long-turn-minutes must be between ${min} and ${max}`); + return { longTurnMinutes: minutes }; +} + +export function longTurnRounds(minutes: number): number { + return Math.ceil((minutes * 60) / LONG_TURN_ROUND_SECONDS); +} + +export const longTurnLog = (nonce: string) => `long-turn-${nonce}.log`; + +/** One round: ticks of real work (hashing) with a sleep, then one log line with the round's own clock window. */ +export function longTurnCommand(nonce: string, round: number): string { + const ticks = LONG_TURN_ROUND_SECONDS / 2; + return `s=$(date +%s); i=0; h=${nonce}; while [ $i -lt ${ticks} ]; do i=$((i+1)); h=$(printf '%s %s' "$h" "$i" | cksum | cut -d' ' -f1); sleep 2; done;` + + ` echo "ROUND ${round} $s $(date +%s) $h" >> ${longTurnLog(nonce)}; tail -n 1 ${longTurnLog(nonce)}`; +} + +export function longTurnPreamble(nonce: string, minutes: number): string { + const rounds = longTurnRounds(minutes); + return [ + `Before anything else in this task, do about ${minutes} minutes of preparation in your working directory, in this same turn.`, + `Run this shell command ${rounds} times, once per round, as separate tool calls in the foreground, replacing with the round number 1 to ${rounds}`, + `(each takes about ${LONG_TURN_ROUND_SECONDS} seconds; do not run rounds in the background or in parallel, and do not skip or shorten any):`, + `\`${longTurnCommand(nonce, 0).replace("ROUND 0 ", "ROUND ")}\``, + `After the last round, save the full contents of \`${longTurnLog(nonce)}\` as this issue's document with key \`${LONG_TURN_DOCUMENT}\``, + "(title \"Long turn\"), exactly as the file reads. Then, still in this turn, do the task below.", + "", + ].join("\n"); +} + +/** The rounds the agent reported, in order. */ +export function parseLongTurnLog(text: string | null | undefined): Array<{ round: number; start: number; end: number }> { + return (text ?? "").split(/\r?\n/).flatMap(line => { + const match = /^\s*ROUND ([0-9]+) ([0-9]{9,11}) ([0-9]{9,11})(?: \S+)?\s*$/.exec(line); + return match ? [{ round: Number(match[1]), start: Number(match[2]), end: Number(match[3]) }] : []; + }); +} + +export function longTurnChecks(minutes: number, artifacts: Pick): OracleResult["checks"] { + const rounds = parseLongTurnLog(artifacts.documents[LONG_TURN_DOCUMENT]); + const wanted = longTurnRounds(minutes); + const complete = rounds.length >= wanted && rounds.slice(0, wanted).every((entry, index) => entry.round === index + 1 + && entry.end - entry.start >= LONG_TURN_ROUND_SECONDS - 10); + const span = rounds.length ? rounds[rounds.length - 1]!.end - rounds[0]!.start : 0; + // The harness's own evidence: a run of the task that ran for the whole turn. + const longest = Math.max(0, ...(artifacts.runs ?? []).map(run => { + const started = Date.parse(run.createdAt ?? ""), finished = Date.parse(run.finishedAt ?? ""); + return Number.isFinite(started) && Number.isFinite(finished) ? (finished - started) / 1000 : 0; + })); + return [ + { name: "long_turn_rounds", ok: complete && span >= minutes * 60 - SPAN_SLACK_SECONDS, + detail: `rounds=${rounds.length}/${wanted} span=${span}s` }, + { name: "long_turn_run_observed", ok: longest >= minutes * 60 - SPAN_SLACK_SECONDS, detail: `longest run ${Math.round(longest)}s` }, + ]; +} + +/** The workload with the long turn in front: description, budget, collected documents and oracle. */ +export function withLongTurn(definition: WorkloadDefinition, minutes: number | undefined): WorkloadDefinition { + if (!minutes) return definition; + return { + ...definition, + budgetMs: definition.budgetMs + minutes * 60_000, + description: (nonce, agents) => `${longTurnPreamble(nonce, minutes)}${definition.description(nonce, agents)}`, + collect: { ...definition.collect, documents: [...new Set([...definition.collect.documents, LONG_TURN_DOCUMENT])] }, + grade(nonce, artifacts, agents) { + const base = definition.grade(nonce, artifacts, agents); + const checks = [...base.checks, ...longTurnChecks(minutes, artifacts)]; + return { verdict: checks.every(check => check.ok) ? "pass" : "fail", checks }; + }, + }; +} diff --git a/tests/restart-chaos/main.ts b/tests/restart-chaos/main.ts index 8312373d9f6..b34a3a4b0b9 100644 --- a/tests/restart-chaos/main.ts +++ b/tests/restart-chaos/main.ts @@ -41,6 +41,7 @@ import { closeJourneyApps } from "./journey-driver.js"; import { matrixMayLaunch, planMatrixWave } from "./journey-matrix.js"; import { redeployWave } from "./redeploy.js"; import { withT1CrossingCheck } from "./workloads.js"; +import { parseRecoveryStepReceipts, withRecoveryStepCheck } from "./recovery-step-faults.js"; import { captureWaveRunnerLogs } from "./daytona-runner-logs.js"; import { StormRun, TASK_FAULT_LOG, observedFaultSchedule, planWave, replayOnCurrentBuild, replayRecordFor, replayWave, type TaskFaultLog } from "./scheduler.js"; import { chaosLifecycleOverrides, seedChaosLab } from "./seed.js"; @@ -244,6 +245,14 @@ async function main(): Promise { timeline.add("db_pressure_stopped", { ...stats }); }; const violationKey = (violation: { rule: string; kind: string; recordId: string }) => `${violation.rule}:${violation.kind}:${violation.recordId}`; + // `--k15-overlap-seconds`, `--k15-fresh-home`: the staging deploy shape (redeploy.ts). + supervisor.deployShape = { overlap: plan.options.k15Overlap === true, freshHome: plan.options.k15FreshHome === true }; + // `--fail-recovery-step`: fail the nth hit of one recovery step once, after the wave's first restart fault. + const recoveryStepReceipts = path.join(waveDir, "recovery-step-receipts.jsonl"); + if (plan.options.failRecoveryStep) { + supervisor.armRecoveryStepOnFirstFault(plan.options.failRecoveryStep, { + controlPath: path.join(supervisor.paths.temporaryRoot, "crash-point.control"), receiptPath: recoveryStepReceipts }); + } if (crashPoint) { supervisor.crashPointHoldMs = plan.options.crashPointHoldMs ?? 0; supervisor.useCrashPointControl({ controlPath: path.join(supervisor.paths.temporaryRoot, "crash-point.control"), @@ -704,8 +713,12 @@ async function main(): Promise { } // T1: a mid-tool fault only counts when one of the task's faults started while its loop ran (workloads.ts). // DF1 restarts nothing, so T1's mid-tool restart check does not apply; the disk-full check replaces it. - const toolOracle = isDiskFullFault(observer.plan.fault) ? withDiskFullCheck(oracle, observer.plan, observer.record) + const t1Oracle = isDiskFullFault(observer.plan.fault) ? withDiskFullCheck(oracle, observer.plan, observer.record) : withT1CrossingCheck(oracle, observer.plan, artifacts?.documents.brief, faults); + // `--fail-recovery-step`: the step failed in the replacement, and no attempt of the task failed (recovery-step-faults.ts). + const armedStep = faults.find(receipt => receipt.recoveryStep); + const toolOracle = withRecoveryStepCheck(t1Oracle, armedStep?.recoveryStep ? { faultId: armedStep.faultId, ...armedStep.recoveryStep } : null, + observer.record.faultIds, parseRecoveryStepReceipts(await readFile(recoveryStepReceipts, "utf8").catch(() => "")), artifacts?.runs ?? []); const grade = gradeTask(observer.record, faults, observer.definition.budgetMs, toolOracle, universalByIssue ? { runMessages: allRunMessages, recoveryActions: universalByIssue.get(observer.record.issueId ?? "")?.recoveryActions ?? [] } : undefined); let evidence: string | null = null; diff --git a/tests/restart-chaos/observer.ts b/tests/restart-chaos/observer.ts index 06fba901307..c86614d119b 100644 --- a/tests/restart-chaos/observer.ts +++ b/tests/restart-chaos/observer.ts @@ -17,6 +17,8 @@ import type { UiRetryClick } from "./board-ui.js"; import { runOracleCommand } from "./oracle-sandbox.js"; import { awaitingQuestionAnswer, collectQuestionArtifacts, questionStep } from "./question-handoff.js"; import { isSessionFault, rotateAgentSession } from "./session-faults.js"; +import { awaitingRewake, collectRewakeArtifacts, isRewakeWorkload, rewakeStep } from "./rewake.js"; +import { withLongTurn } from "./long-turn.js"; import { captureRemoteWorkspaceFiles, readRemoteWorkspaceFile } from "./remote-workspace-files.js"; import { taskFaultSchedule } from "./scheduler.js"; import { g1ChildTitle, g1Decision, workloadDefinitions, type WorkloadAgents } from "./workloads.js"; @@ -233,7 +235,8 @@ export class TaskObserver { /** Q1–Q3: the board's side of the journey (journey-driver.ts). */ readonly journey: JourneyDriver | null; - get definition() { return workloadDefinitions[this.plan.workload]; } + /** The workload, with `--long-turn-minutes` tool work in front of its first turn (long-turn.ts). */ + get definition() { return withLongTurn(workloadDefinitions[this.plan.workload], this.plan.longTurnMinutes); } /** * Crash-point suite: create the issue without an assignee, so no wake is @@ -820,6 +823,7 @@ export class TaskObserver { if (this.plan.workload === "G1") return Boolean(governance?.approvalSeenAt) && !governance?.decision; if (this.plan.workload === "H1") return Boolean(governance?.budgetPausedAt) && !governance?.resume && !governance?.pauseLostAt; if (this.plan.workload === "Q1" || this.plan.workload === "Q4") return awaitingQuestionAnswer(this.record); + if (isRewakeWorkload(this.plan.workload)) return awaitingRewake(this.record); return false; } @@ -862,6 +866,10 @@ export class TaskObserver { note: (kind, data) => this.timeline.add(kind, { taskId: this.plan.taskId, ...data }), ...(sessionFault ? { beforeAnswer: () => rotateAgentSession(this.api, this.lab.agents[this.plan.adapter].id, this.plan.index, now, sessionFault) } : {}) }); } + if (isRewakeWorkload(this.plan.workload)) { + await rewakeStep({ api: this.api, record: this.record, plan: this.plan, issueId: this.record.issueId, agentId: this.lab.agents[this.plan.adapter].id, + sample, now, boardMayAct: this.boardMayAct(sample), note: (kind, data) => this.timeline.add(kind, { taskId: this.plan.taskId, ...data }) }); + } } private async approvalStep(sample: TaskSample, now: number): Promise { @@ -1039,7 +1047,11 @@ export class TaskObserver { ...(this.plan.workload === "G1" ? { approvals: await this.collectApprovals(issueId) } : {}), ...(this.plan.workload === "H1" ? await this.finalPauseCheck(issueId) : {}), ...(this.record.governance ? { governance: this.record.governance } : {}), - ...(this.plan.workload === "Q1" || this.plan.workload === "Q4" ? { question: await collectQuestionArtifacts(this.api, issueId, this.record) } : {}), + ...(this.plan.workload === "Q1" || this.plan.workload === "Q4" || this.plan.workload === "W2Q" ? { question: await collectQuestionArtifacts(this.api, issueId, this.record) } : {}), + ...(isRewakeWorkload(this.plan.workload) ? { rewake: await collectRewakeArtifacts(this.api, issueId, this.record) } : {}), + // The task's runs, for the shape checks (`no_failed_attempt`, the long turn's own evidence). + runs: await this.api.get(`/api/issues/${issueId}/runs`, 10_000).then(rows => (rows ?? []).map(run => ({ id: String(run.runId ?? run.id), + status: String(run.status), errorCode: run.errorCode ?? null, createdAt: run.createdAt ?? null, finishedAt: run.finishedAt ?? null }))).catch(() => []), ...(this.journey ? { journey: await this.journey.collect(issueId).finally(() => this.journey!.close()) } : {}), }; } diff --git a/tests/restart-chaos/recovery-step-faults.ts b/tests/restart-chaos/recovery-step-faults.ts new file mode 100644 index 00000000000..d2d37d0d185 --- /dev/null +++ b/tests/restart-chaos/recovery-step-faults.ts @@ -0,0 +1,90 @@ +/** + * `--fail-recovery-step [:]`: fail the Nth attempt of one recovery step once (README "Fail the Nth + * recovery step"). + * + * Every other fault hits the control plane once and then lets recovery run. On staging the first fault was + * often harmless and a later recovery step failed: the retry of a bootstrap met a missing runtime asset, a + * reattach met `Agent directory operation is already active`, a bounded retry met an unfinished teardown. + * This option lets the wave's first restart fault fire normally. When that fault's replacement server + * starts, the harness arms one crash point in fail mode (`packages/shared/src/crash-points.ts`): the nth hit + * of the point in the replacement throws the error its real step throws, once. nth = 1 fails recovery's + * first attempt at the step, 2 its second, and so on, so recovery chains are exercised. + * + * Hits count across the whole server: with several tasks in flight, the nth hit may belong to any of them. + * Run one task per wave (`--tasks 1 --concurrency 1`) to aim at one task's nth attempt. + */ +import { CRASH_POINTS, isCrashPointName, type CrashPointName } from "../../packages/shared/src/crash-point-registry.js"; +import { noFailedAttemptCheck } from "./rewake.js"; +import type { EnvironmentKind, FaultKind, OracleResult } from "./types.js"; + +/** Short names for the steps staging failed at; any registered crash point name is also accepted. */ +export const RECOVERY_STEPS: Record = { + // A runnerd start that fails before the process exists (spawn EAGAIN), local and Daytona. + "runnerd-start": "native.process_start.after_requested_before_spawn", + // A sandbox teardown whose provider destroy did not finish (Daytona). + teardown: "environment.teardown.after_claim_before_destroy", + // The agent-directory lock still held by another operation (Daytona): staging class A's terminal error. + "directory-lock": "agent_directory.operation_lock.before_acquire", +}; + +/** Restart faults whose replacement start arms the step. */ +export const RECOVERY_STEP_FAULTS: readonly FaultKind[] = ["K1", "K2", "K4", "K6", "K14", "K15", "RR1", "RR2", "RR3"]; + +export interface RecoveryStepSpec { point: CrashPointName; nth: number } + +export function parseRecoveryStep(raw: string): RecoveryStepSpec { + const match = /^([a-z0-9_.-]+)(?::([1-9][0-9]?))?$/.exec(raw.trim()); + if (!match) throw new Error("--fail-recovery-step takes [:], for example directory-lock:2"); + const point = RECOVERY_STEPS[match[1]!] ?? match[1]!; + if (!isCrashPointName(point)) { + throw new Error(`--fail-recovery-step: unknown step "${match[1]}"; use ${Object.keys(RECOVERY_STEPS).join(", ")} or a crash point name`); + } + return { point, nth: match[2] ? Number(match[2]) : 1 }; +} + +/** The control-file spec the supervisor writes: ": fail". */ +export function recoveryStepControlSpec(spec: RecoveryStepSpec): string { + return `${spec.point}:${spec.nth} fail`; +} + +export function validateRecoveryStep(options: { env: EnvironmentKind; faults: readonly string[]; crashPoint?: string; stormMinutes?: number }, + raw: string | undefined): { failRecoveryStep?: string } { + if (raw === undefined) return {}; + const spec = parseRecoveryStep(raw); + if (options.crashPoint) throw new Error("--fail-recovery-step arms its own point; do not combine it with --crash-point"); + if (!options.faults.some(fault => RECOVERY_STEP_FAULTS.includes(fault as FaultKind))) { + throw new Error(`--fail-recovery-step fails a step of the recovery after a restart; add one of ${RECOVERY_STEP_FAULTS.join(", ")} to --faults`); + } + const environments = CRASH_POINTS[spec.point].environments as readonly string[]; + if (!environments.includes(options.env)) { + throw new Error(`--fail-recovery-step ${spec.point} is reached only with --env ${environments.join(" or ")}`); + } + return { failRecoveryStep: `${spec.point}:${spec.nth}` }; +} + +export interface RecoveryStepHit { point: string; hit: number; pid: number; token?: string; mode?: string; at?: string } + +/** Every fail-mode receipt the server appended. */ +export function parseRecoveryStepReceipts(text: string): RecoveryStepHit[] { + return text.split("\n").flatMap(line => { + try { + const parsed = JSON.parse(line) as RecoveryStepHit; + return parsed.mode === "fail" && typeof parsed.point === "string" ? [parsed] : []; + } catch { return []; } + }); +} + +/** + * The task's checks, added to every task the armed fault crossed: the armed step failed in the replacement (else + * the cell tested nothing), and recovery absorbed it: no attempt of the task failed. + */ +export function withRecoveryStepCheck(oracle: OracleResult, armed: { faultId: string; spec: string; token: string } | null, + taskFaultIds: readonly string[], hits: readonly RecoveryStepHit[], + runs: ReadonlyArray<{ id: string; status: string; errorCode: string | null }>): OracleResult { + if (!armed || !taskFaultIds.includes(armed.faultId)) return oracle; + const hit = hits.find(entry => entry.token === armed.token); + const checks = [...oracle.checks, { name: "recovery_step_failed_once", ok: Boolean(hit), + detail: hit ? `${hit.point} hit ${hit.hit} failed at ${hit.at ?? "?"} after ${armed.faultId}` : `${armed.spec} never reached after ${armed.faultId}` }, + ...(oracle.checks.some(check => check.name === "no_failed_attempt") ? [] : [noFailedAttemptCheck(runs)])]; + return { ...oracle, checks, verdict: checks.every(check => check.ok) ? "pass" : "fail" }; +} diff --git a/tests/restart-chaos/redeploy.ts b/tests/restart-chaos/redeploy.ts index 2af7d2ef4f5..8deb3cad1cf 100644 --- a/tests/restart-chaos/redeploy.ts +++ b/tests/restart-chaos/redeploy.ts @@ -46,6 +46,44 @@ export function parseK15HoldSeconds(options: { faults: readonly string[] }, raw: return { k15HoldMs: [min * 1000, max * 1000] }; } +/** `--k15-overlap-seconds` bounds: staging's old server kept running 30–150 s after the new one was up. */ +export const K15_OVERLAP_SECONDS_RANGE: readonly [number, number] = [5, 600]; + +/** + * The staging deploy shape (README "Redeploy without a volume, with overlap"): + * + * - `--k15-overlap-seconds ` or `-`: a K15 boots the next deploy generation beside the old server, + * switches traffic (the wave's stable port) to it once it is ready, keeps the old server running for the seeded + * overlap, then stops the old one with SIGTERM. The seeded K15 hold becomes the overlap; there is no outage. + * - `--k15-fresh-home`: every deploy generation gets a new, empty instance home and no Railway volume, as staging's + * deploys after 07:25Z reported `volumeId: null`. The database, secrets key and storage stay (they live outside + * the instance home on staging); controller-local files such as `runtime-context-assets` do not. Daytona only: + * a local run's workspace and runner live under the instance home. + */ +export function parseK15DeployShape(options: { env: string; faults: readonly string[]; k15HoldMs?: [number, number] }, + overlapRaw: string | undefined, freshHome: boolean): { k15HoldMs?: [number, number]; k15Overlap?: true; k15FreshHome?: true } { + const out: { k15HoldMs?: [number, number]; k15Overlap?: true; k15FreshHome?: true } = {}; + if ((overlapRaw !== undefined || freshHome) && !options.faults.includes("K15")) { + throw new Error("--k15-overlap-seconds and --k15-fresh-home shape the K15 redeploy; add K15 to --faults"); + } + if (overlapRaw !== undefined) { + if (options.k15HoldMs) throw new Error("--k15-overlap-seconds replaces the K15 outage; do not combine it with --k15-hold-seconds"); + const match = /^([0-9]+)(?:-([0-9]+))?$/.exec(overlapRaw.trim()); + if (!match) throw new Error("--k15-overlap-seconds takes or - seconds"); + const min = Number(match[1]); + const max = match[2] === undefined ? min : Number(match[2]); + const [low, high] = K15_OVERLAP_SECONDS_RANGE; + if (min < low || max > high || max < min) throw new Error(`--k15-overlap-seconds must be between ${low} and ${high} seconds, min not above max`); + out.k15HoldMs = [min * 1000, max * 1000]; + out.k15Overlap = true; + } + if (freshHome) { + if (options.env !== "daytona") throw new Error("--k15-fresh-home runs only with --env daytona: a local run's workspace and runner live in the instance home"); + out.k15FreshHome = true; + } + return out; +} + /** The seeded hold of one K15. Draws only when a range is set, so existing seeds keep their plans. */ export function k15HoldMs(range: readonly [number, number] | undefined, int: (min: number, max: number) => number): number { return range ? int(range[0], range[1]) : 0; @@ -98,18 +136,23 @@ export function nextRedeployIdentity(waveId: string, current: RedeployIdentity): * Server environment for one generation. The volume mount is the instance home: on staging the * instance directory lives on the exclusive volume that survives each deploy. */ -export function redeployEnvironment(identity: RedeployIdentity, volumeMountPath: string): Record { +export function redeployEnvironment(identity: RedeployIdentity, volumeMountPath: string | null): Record { return { [REDEPLOY_HOSTNAME_ENV]: identity.hostname, RAILWAY_PROJECT_ID: identity.projectId, RAILWAY_ENVIRONMENT_ID: identity.environmentId, RAILWAY_SERVICE_ID: identity.serviceId, RAILWAY_DEPLOYMENT_ID: identity.deploymentId, - RAILWAY_VOLUME_ID: identity.volumeId, - RAILWAY_VOLUME_MOUNT_PATH: volumeMountPath, + // `--k15-fresh-home`: no volume, as staging's later deploys reported `volumeId: null`. + ...(volumeMountPath === null ? {} : { RAILWAY_VOLUME_ID: identity.volumeId, RAILWAY_VOLUME_MOUNT_PATH: volumeMountPath }), }; } +/** `--k15-fresh-home`: generation N's own instance home (generation 0 keeps the wave's first home). */ +export function generationHome(temporaryRoot: string, firstHome: string, generation: number): string { + return generation === 0 ? firstHome : `${temporaryRoot}/home-g${generation}`; +} + /** Node arguments that load the preload ahead of the server entry's own `--import` loader. */ export function redeployNodeArgs(args: readonly string[]): string[] { return ["--import", REDEPLOY_PRELOAD_PATH, ...args]; diff --git a/tests/restart-chaos/rewake.ts b/tests/restart-chaos/rewake.ts new file mode 100644 index 00000000000..54d87c5a49c --- /dev/null +++ b/tests/restart-chaos/rewake.ts @@ -0,0 +1,293 @@ +/** + * W2, W2Q, W2C: the same task woken again right after a run of it finished (README "Re-wake after success"). + * + * On staging, 20 of 25 failures in one 8-hour window happened with no restart at all. Ten or more runs of + * one agent ran at once on reused (warm) sandboxes, and 30–60 s after a long run of a task succeeded, an + * ordinary wake (a comment, an issue monitor) started the next run of that same task. That run first had to + * retire the previous run's warm owner, and it failed before any provider work ("Controller journal drain + * timed out", "runner did not durably suspend before checkpoint", `journal_tool_input_unanswered`). + * + * The workload is the fault. Every task runs on its adapter's one agent, so `--tasks 10 --concurrency 10` + * puts ten tasks on one agent. Phase 1 ends with the task left `in_progress` (`in_review` would gate completion on a + * review). Then the harness, acting as the + * board, wakes the same task 0–60 s after that run settled (the seeded `followUpAfterMs`): + * + * W2 a board comment, or (by the task's nonce) a board-scheduled issue monitor (`issue_monitor_due`). + * W2Q phase 1 parks on an unanswered `request_human_input` question; a comment wakes the task before the + * board answers (staging class C3). The board answers after that run settled. + * W2C as W2, and the board changes the agent's `adapterConfig.idleTimeoutMs` before the wake, so the next + * run cannot resume the saved session (SR1, session-faults.ts, is the same change while parked). + * + * Pass: no attempt failed, the wake was served by a run that succeeded, and the task ends `done` with its + * markers. A task left blocked gets the usual Retry (R3), which itself fails the grade. + */ +import type { ChaosApi } from "./api.js"; +import { q1AnswerMarker, q1Code, q1Question, Q1_CODES, questionStep } from "./question-handoff.js"; +import type { OracleArtifacts, OracleResult, TaskPlan, TaskRecord, TaskSample, WorkloadId } from "./types.js"; +import type { WorkloadDefinition } from "./workloads.js"; + +type Json = Record; + +export const REWAKE_WORKLOADS = ["W2", "W2Q", "W2C"] as const satisfies readonly WorkloadId[]; +export type RewakeWorkload = (typeof REWAKE_WORKLOADS)[number]; +export function isRewakeWorkload(id: string): id is RewakeWorkload { + return (REWAKE_WORKLOADS as readonly string[]).includes(id); +} + +/** Seeded delay between the first run settling and the re-wake (staging: 30–60 s). */ +export const REWAKE_DELAY_RANGE_MS: readonly [number, number] = [0, 60_000]; +/** W2C: the configuration change commits at least this long before the wake. */ +export const CONFIG_SETTLE_MS = 5_000; +/** A wake that started no run within this long after it was sent is recorded as not served. */ +export const REWAKE_SERVE_TIMEOUT_MS = 180_000; +const ACTIVE = new Set(["queued", "running", "scheduled_retry"]); +const FAILED = new Set(["failed", "timed_out"]); + +export type RewakeKind = "comment" | "monitor"; + +/** W2Q is woken by a comment (C3's shape); W2 and W2C alternate by nonce between a comment and a monitor. */ +export function rewakeKind(plan: Pick): RewakeKind { + if (plan.workload === "W2Q") return "comment"; + return Number.parseInt(plan.nonce.slice(-2, -1), 16) % 2 === 0 ? "comment" : "monitor"; +} + +const briefMarker = (nonce: string) => `CHAOS-${nonce}`; +export const rewakeMarker = (nonce: string) => `REWAKE-${nonce}`; +export const noteMarker = (nonce: string) => `NOTE-${nonce}`; + +export interface RewakeRecord { + kind: RewakeKind; + /** The run that finished phase 1 (for W2Q, the run that asked). */ + firstRunId: string | null; + /** First poll that saw phase 1 finished and nothing of the task active. */ + firstSettledAt: number | null; + /** W2C: the board's agent configuration change, made before the wake. */ + configChange?: { at: number; idleTimeoutMs: number; httpStatus: number | null; error: string | null }; + sent?: { at: number; kind: RewakeKind; statusAtWake: string | null; httpStatus: number | null; error: string | null; + commentId?: string | null; nextCheckAt?: string }; + /** First run created after the wake was sent. */ + servedByRunId?: string | null; + servedSeenAt?: number | null; +} + +export interface RewakeArtifacts extends RewakeRecord { + runs: Array<{ id: string; status: string; errorCode: string | null; createdAt: string | null; finishedAt: string | null }>; +} + +const phaseTwo = (nonce: string) => [ + "Phase 2 happens only when the board wakes you again with a comment or a scheduled monitor check on this task.", + `Then add the line \`${rewakeMarker(nonce)}\` on its own line to the \`brief\` document (keep everything else), and mark this task done.`, + "If you are woken for any other reason before that, change nothing and end your turn.", +].join("\n"); + +const w2Description = (nonce: string) => [ + "This task has two phases.", + "Phase 1 (now): write a short brief on why idempotent retries matter for background job queues.", + "Save it as this issue's document with key `brief` (title \"Brief\"), in markdown.", + `It must contain the line \`${briefMarker(nonce)}\` exactly, on its own line, and at least three bullet points that start with "- ".`, + "Then leave this task `in_progress` and end your turn. Do not mark it done or move it to review in phase 1. Do not create files or other tasks.", + phaseTwo(nonce), +].join("\n"); + +const w2qDescription = (nonce: string) => [ + "This task needs one answer from the board before you write anything.", + `1. Ask exactly one question with your \`request_human_input\` tool: a questions card (continuationPolicy \`wake_assignee\`,`, + ` idempotencyKey \`w2q-${nonce}\`) with one required single-select question "${q1Question(nonce)}"`, + ` and exactly two options labelled \`${Q1_CODES[0]}\` and \`${Q1_CODES[1]}\`.`, + "2. Then end your turn and wait for the answer. Do not guess, do not ask again, and do not create documents, files or tasks yet.", + " If the board comments before it answers, follow the comment's note and end your turn again; do not ask again.", + "3. When you are woken with the answer, save this issue's document with key `brief` (title \"Brief\"), in markdown.", + ` It must contain the line \`${q1AnswerMarker(nonce, "")}\` exactly, on its own line, with replaced by the chosen option,`, + " every line the board's comments asked you to include, and at least three bullet points starting with \"- \".", + "4. When the document is saved, mark this task done.", +].join("\n"); + +/** The board's re-wake comment. W2Q's asks only for a note, so its run must end while the question stays pending. */ +export function rewakeComment(plan: Pick): string { + if (plan.workload === "W2Q") { + return `Note before I answer your question: when you write the brief, also include the line \`${noteMarker(plan.nonce)}\` on its own line. ` + + "I will answer shortly; do not ask again and do not write the brief yet."; + } + return `Phase 2 now: add the line \`${rewakeMarker(plan.nonce)}\` on its own line to the \`brief\` document, then mark this task done.`; +} + +/** W2C: one adapter setting in the session's configuration fingerprint, harmless to the run (as SR1 changes). */ +export function rewakeIdleTimeoutMs(taskIndex: number): number { + return 300_000 + 1_000 + taskIndex; +} + +/** The task waits on the board between its first run settling and the wake being served (and, for W2Q, the answer). */ +export function awaitingRewake(record: TaskRecord, now = Date.now()): boolean { + const rewake = record.rewake; + if (!rewake?.firstSettledAt) return false; + if (!rewake.sent) return true; + if (rewake.sent.error) return false; + if (!rewake.servedByRunId && now - rewake.sent.at < REWAKE_SERVE_TIMEOUT_MS) return true; + return record.plan.workload === "W2Q" && Boolean(record.question?.pendingNow) && !record.question?.answer; +} + +/** The first run of the task that succeeded, when nothing of the task is active. */ +function settledFirstRun(sample: TaskSample): string | null { + const runs = sample.runs ?? []; + if (runs.some(run => ACTIVE.has(run.status))) return null; + const succeeded = runs.filter(run => run.status === "succeeded") + .sort((a, b) => Date.parse(a.createdAt ?? "") - Date.parse(b.createdAt ?? "")); + return succeeded[0]?.id ?? null; +} + +export interface RewakeStepInput { + api: Pick; + record: TaskRecord; + plan: TaskPlan; + issueId: string; + agentId: string; + sample: TaskSample; + now: number; + /** The server is ready, no fault is in progress and the task's planned faults fired. */ + boardMayAct: boolean; + note: (kind: string, data: Record) => void; +} + +/** Board step of W2, W2Q and W2C, called on every poll. */ +export async function rewakeStep(input: RewakeStepInput): Promise { + const { plan, record, sample, now } = input; + const rewake = record.rewake ??= { kind: rewakeKind(plan), firstRunId: null, firstSettledAt: null }; + if (plan.workload === "W2Q") { + // The question is answered only after the comment's run settled; questionStep keeps Q1's record. + await questionStep({ api: input.api, issueId: input.issueId, nonce: plan.nonce, record, sample, now, note: input.note, + boardMayAct: input.boardMayAct && Boolean(rewake.servedByRunId) && !(sample.runs ?? []).some(run => ACTIVE.has(run.status)) }); + } + if (!sample.reachable) return; + if (rewake.sent) { + if (!rewake.servedByRunId) { + const served = (sample.runs ?? []).filter(run => run.createdAt && Date.parse(run.createdAt) >= rewake.sent!.at - 1_000) + .sort((a, b) => Date.parse(a.createdAt!) - Date.parse(b.createdAt!))[0]; + if (served) { + rewake.servedByRunId = served.id; + rewake.servedSeenAt = now; + input.note("rewake_served", { runId: served.id }); + } + } + return; + } + if (rewake.firstSettledAt === null) { + // W2Q: phase 1 is the asking run, settled while the question is pending. + if (plan.workload === "W2Q" && !record.question?.pendingNow) return; + if (plan.workload !== "W2Q" && sample.issueStatus === "done") return; + const first = settledFirstRun(sample); + if (!first) return; + rewake.firstRunId = plan.workload === "W2Q" ? record.question?.askedByRunId ?? first : first; + rewake.firstSettledAt = now; + input.note("rewake_first_run_settled", { runId: rewake.firstRunId, status: sample.issueStatus ?? null }); + } + if (!input.boardMayAct || (sample.runs ?? []).some(run => ACTIVE.has(run.status))) return; + if (plan.workload === "W2C" && !rewake.configChange) { + const idleTimeoutMs = rewakeIdleTimeoutMs(plan.index); + const change: NonNullable = { at: now, idleTimeoutMs, httpStatus: null, error: null }; + try { + await input.api.patch(`/api/agents/${input.agentId}`, { adapterConfig: { idleTimeoutMs } }); + change.httpStatus = 200; + } catch (error) { + change.httpStatus = statusOf(error); + change.error = error instanceof Error ? error.message : String(error); + } + rewake.configChange = change; + input.note("rewake_config_changed", { ...change }); + return; + } + if (now < rewake.firstSettledAt + (plan.followUpAfterMs ?? 0)) return; + // W2C: the change commits at least CONFIG_SETTLE_MS before the wake, however late the board made it. + if (rewake.configChange && now < rewake.configChange.at + CONFIG_SETTLE_MS) return; + const sent: NonNullable = { at: now, kind: rewake.kind, statusAtWake: sample.issueStatus ?? null, httpStatus: null, error: null }; + try { + if (rewake.kind === "comment") { + const comment = await input.api.post(`/api/issues/${input.issueId}/comments`, { body: rewakeComment(plan) }); + sent.commentId = typeof comment?.id === "string" ? comment.id : null; + } else { + // A board-scheduled monitor due now: the scheduler's own `issue_monitor_due` wake, as on staging. + sent.nextCheckAt = new Date(now + 2_000).toISOString(); + await input.api.patch(`/api/issues/${input.issueId}`, { executionPolicy: { monitor: { nextCheckAt: sent.nextCheckAt, + notes: `Phase 2 check for ${plan.nonce}`, scheduledBy: "board" } } }); + } + sent.httpStatus = 200; + } catch (error) { + sent.httpStatus = statusOf(error); + sent.error = error instanceof Error ? error.message : String(error); + } + rewake.sent = sent; + input.note("rewake_sent", { ...sent, delayMs: now - rewake.firstSettledAt }); +} + +function statusOf(error: unknown): number | null { + return typeof (error as { status?: unknown }).status === "number" ? (error as { status: number }).status : null; +} + +export async function collectRewakeArtifacts(api: Pick, issueId: string, record: TaskRecord): Promise { + const runs = await api.get(`/api/issues/${issueId}/runs`, 10_000).catch(() => []); + return { + ...(record.rewake ?? { kind: rewakeKind(record.plan), firstRunId: null, firstSettledAt: null }), + runs: (runs ?? []).map(run => ({ id: String(run.runId ?? run.id), status: String(run.status), errorCode: run.errorCode ?? null, + createdAt: run.createdAt ?? null, finishedAt: run.finishedAt ?? null })), + }; +} + +/** No run of the task failed or timed out; the shared pass condition of the shape cells. */ +export function noFailedAttemptCheck(runs: ReadonlyArray<{ id: string; status: string; errorCode: string | null }>) { + const failed = runs.filter(run => FAILED.has(run.status)); + return { name: "no_failed_attempt", ok: failed.length === 0, + detail: failed.map(run => `${run.id}:${run.status}:${run.errorCode ?? ""}`).join(",") || "none" }; +} + +export function gradeRewake(plan: Pick, artifacts: OracleArtifacts): OracleResult { + const rewake = artifacts.rewake; + const runs = rewake?.runs ?? []; + const brief = artifacts.documents.brief ?? ""; + const bullets = brief.split(/\r?\n/).filter(line => /^\s*[-*] \S/.test(line)).length; + const first = runs.find(run => run.id === rewake?.firstRunId); + const served = runs.find(run => run.id === rewake?.servedByRunId); + const sent = rewake?.sent; + const markers = plan.workload === "W2Q" + ? [q1AnswerMarker(plan.nonce, q1Code(plan.nonce)), noteMarker(plan.nonce)] : [briefMarker(plan.nonce), rewakeMarker(plan.nonce)]; + const checks: OracleResult["checks"] = [ + { name: "issue_done", ok: artifacts.issueStatus === "done", detail: `status=${artifacts.issueStatus ?? "unknown"}` }, + { name: "first_run_succeeded", ok: first?.status === "succeeded", + detail: first ? `${first.id} ${first.status}${first.errorCode ? ` ${first.errorCode}` : ""}` : "phase 1 never settled" }, + { name: "rewake_sent", ok: sent?.httpStatus === 200, + detail: sent ? `${sent.kind} status=${sent.statusAtWake ?? "?"} http=${sent.httpStatus}${sent.error ? ` ${sent.error}` : ""}` + + ` after ${rewake?.firstSettledAt ? Math.round((sent.at - rewake.firstSettledAt) / 1000) : "?"}s` : "never sent" }, + { name: "rewake_served", ok: served?.status === "succeeded", + detail: served ? `${served.id} ${served.status}${served.errorCode ? ` ${served.errorCode}` : ""}` : "no run after the wake" }, + noFailedAttemptCheck(runs), + ...(plan.workload === "W2C" ? [{ name: "config_changed_before_wake", ok: rewake?.configChange?.httpStatus === 200 + && (sent === undefined || rewake.configChange.at < sent.at), + detail: rewake?.configChange ? `idleTimeoutMs=${rewake.configChange.idleTimeoutMs} http=${rewake.configChange.httpStatus}` : "not changed" }] : []), + ...(plan.workload === "W2Q" ? [{ name: "question_answered_after_wake", ok: artifacts.question?.answer?.httpStatus === 200 + && sent !== undefined && artifacts.question.answer.at > sent.at, detail: artifacts.question?.answer + ? `${artifacts.question.answer.code} http=${artifacts.question.answer.httpStatus}` : "never answered" }, + { name: "one_question_asked", ok: artifacts.question?.interactionIds.length === 1, detail: `questions=${artifacts.question?.interactionIds.length ?? 0}` }] : []), + ...markers.map(marker => ({ name: `brief_contains_${marker.split("-")[0]!.toLowerCase()}_marker`, ok: brief.includes(marker), detail: marker })), + { name: "brief_has_three_bullets", ok: bullets >= 3, detail: `bullets=${bullets}` }, + ]; + return { verdict: checks.every(check => check.ok) ? "pass" : "fail", checks }; +} + +const definition = (id: RewakeWorkload, label: string, description: (nonce: string) => string): WorkloadDefinition => ({ + id, + label, + usesRepository: false, + // A restart fault, if any, lands around the first run or the wake. + fireWindowMs: [20_000, 120_000], + // The seeded re-wake delay after the first run settled. + followUpWindowMs: REWAKE_DELAY_RANGE_MS, + budgetMs: 20 * 60_000, + title: nonce => `Chaos ${id} re-wake ${nonce}`, + description, + collect: { documents: ["brief"], files: () => [], commands: [] }, + grade: (nonce, artifacts) => gradeRewake({ workload: id, nonce }, artifacts), +}); + +export const rewakeWorkloadDefinitions: Record = { + W2: definition("W2", "Same task woken again after its run succeeded", w2Description), + W2Q: definition("W2Q", "Parked question, then woken by a comment before the answer", w2qDescription), + W2C: definition("W2C", "Agent configuration changed, then the same task woken again", w2Description), +}; diff --git a/tests/restart-chaos/scheduler.ts b/tests/restart-chaos/scheduler.ts index ef829e802b4..f151252844b 100644 --- a/tests/restart-chaos/scheduler.ts +++ b/tests/restart-chaos/scheduler.ts @@ -81,8 +81,8 @@ const STORM_RESULT_FAULTS: readonly FaultKind[] = ["K1", "K2"]; * A `result` task in a storm also fires its own K1 or K2 just after its run * accepts a result, the window of RC-30, RC-33 and RC-41. */ -function stormCellFaults(options: Pick, trigger: TriggerId): readonly TaskFaultKind[] { - if (!options.stormMinutes) return [...options.faults, ...(options.providerFaults ?? []), ...(options.diskFullFaults ?? []), ...(options.sessionFaults ?? [])]; +function stormCellFaults(options: Pick, trigger: TriggerId): readonly TaskFaultKind[] { + if (!options.stormMinutes) return [...options.faults, ...(options.providerFaults ?? []), ...(options.diskFullFaults ?? []), ...(options.sessionFaults ?? []), ...(options.baseline ? ["K0" as const] : [])]; if (trigger === "time") return ["K13"]; if (trigger !== "result") throw new Error(`A K13 storm fires on its own clock; --triggers ${trigger} does not combine with it (use time or result)`); const faults = options.faults.filter(fault => STORM_RESULT_FAULTS.includes(fault)); @@ -98,7 +98,7 @@ function pinnedFireAfterMs(faultAfterMs: number | undefined, drawn: number): num return faultAfterMs ?? drawn; } -export function planTasks(options: Pick): TaskPlan[] { +export function planTasks(options: Pick): TaskPlan[] { const rng = createRng(options.seed); const triggers = options.triggers?.length ? options.triggers : ["time" as const]; for (const trigger of triggers) { @@ -128,7 +128,7 @@ export function planTasks(options: Pick options.longTurnMinutes ? { ...task, longTurnMinutes: options.longTurnMinutes } : task), ...(options.stormMinutes ? { storm: planStorm(options.seed, options.stormMinutes, options.faults, options.k4HoldMaxMs, options.k15HoldMs) } : {}) }; } diff --git a/tests/restart-chaos/shape-cells.test.ts b/tests/restart-chaos/shape-cells.test.ts new file mode 100644 index 00000000000..6170f0e51af --- /dev/null +++ b/tests/restart-chaos/shape-cells.test.ts @@ -0,0 +1,252 @@ +import net from "node:net"; +import { describe, expect, it } from "vitest"; +import { parseCommand } from "./config.js"; +import { startEdgeProxy } from "./edge-proxy.js"; +import { longTurnChecks, longTurnCommand, longTurnRounds, parseLongTurnLog, withLongTurn } from "./long-turn.js"; +import { q1AnswerMarker, q1Code } from "./question-handoff.js"; +import { parseRecoveryStep, parseRecoveryStepReceipts, recoveryStepControlSpec, withRecoveryStepCheck } from "./recovery-step-faults.js"; +import { generationHome, parseK15DeployShape, redeployEnvironment, redeployIdentity } from "./redeploy.js"; +import { awaitingRewake, gradeRewake, noteMarker, rewakeKind, rewakeMarker, rewakeStep, type RewakeArtifacts } from "./rewake.js"; +import { planTasks, planWave, taskFaultSchedule } from "./scheduler.js"; +import type { OracleArtifacts, RunSample, TaskPlan, TaskRecord, TaskSample } from "./types.js"; +import { workloadDefinitions } from "./workloads.js"; + +const wave = (argv: string[]) => { + const command = parseCommand(argv); + if (command.mode !== "wave") throw new Error("expected a wave"); + return command.options; +}; + +const run = (id: string, status: string, createdAt: number): RunSample => ({ id, status, createdAt: new Date(createdAt).toISOString(), startedAt: null, + finishedAt: null, errorCode: null, retryOfRunId: null, wakeCommentIds: [], livenessState: null }); +const sample = (issueStatus: string, runs: RunSample[]): TaskSample => ({ at: 0, reachable: true, serverReady: true, issueStatus, runs }); + +describe("W2, W2Q, W2C: re-wake after success", () => { + it("are opt-in workloads that run as K0 cells on one agent", () => { + expect(wave(["--adapters", "codex"]).workloads).not.toContain("W2"); + const options = wave(["--adapters", "codex", "--workloads", "W2,W2Q,W2C", "--faults", "K0", "--tasks", "10", "--concurrency", "10", "--lifecycle", "warm"]); + expect(options).toMatchObject({ faults: [], baseline: true, workloads: ["W2", "W2Q", "W2C"] }); + const tasks = planTasks(options); + expect(tasks).toHaveLength(10); + expect(new Set(tasks.map(task => task.adapter))).toEqual(new Set(["codex"])); + expect(tasks.every(task => task.fault === "K0" && taskFaultSchedule(task).length === 0)).toBe(true); + // The seeded re-wake delay is 0–60 s after the first run settled. + expect(tasks.every(task => task.followUpAfterMs !== null && task.followUpAfterMs >= 0 && task.followUpAfterMs <= 60_000)).toBe(true); + expect(() => parseCommand(["--workloads", "W2", "--faults", "K0", "--storm-minutes", "5"])).toThrow("K0"); + // A restart may also land around the first run or the wake. + expect(planTasks(wave(["--workloads", "W2", "--faults", "K2", "--adapters", "codex", "--tasks", "2"])).map(task => task.fault)).toEqual(["K2", "K2"]); + }); + + it("asks phase 1 to leave the task open and phase 2 to wait for the board", () => { + const text = workloadDefinitions.W2.description("0bcd1234"); + expect(text).toContain("leave this task `in_progress`"); + expect(text).toContain(rewakeMarker("0bcd1234")); + expect(workloadDefinitions.W2Q.description("0bcd1234")).toContain("request_human_input"); + expect(rewakeKind({ workload: "W2Q", nonce: "0bcd1234" })).toBe("comment"); + expect(new Set(["00", "10", "20", "30"].map(tail => rewakeKind({ workload: "W2", nonce: `0bcd12${tail}` })))).toEqual(new Set(["comment", "monitor"])); + }); + + function harness(plan: Partial) { + const calls: Array<{ method: string; route: string; body: unknown }> = []; + const record = { plan: { taskId: "t01", index: 3, nonce: "0bcd1204", followUpAfterMs: 10_000, workload: "W2", ...plan } } as unknown as TaskRecord; + const api = { + async get(route: string) { return (route.endsWith("/interactions") ? interactions : []) as T; }, + async post(route: string, body?: unknown) { calls.push({ method: "post", route, body }); return { id: "c1" } as T; }, + async patch(route: string, body?: unknown) { calls.push({ method: "patch", route, body }); return {} as T; }, + }; + let interactions: Array> = []; + const notes: string[] = []; + const step = (s: TaskSample, now: number, boardMayAct = true) => rewakeStep({ api, record, plan: record.plan, issueId: "i1", agentId: "a1", + sample: s, now, boardMayAct, note: kind => notes.push(kind) }); + return { calls, record, notes, step, setInteractions: (rows: Array>) => { interactions = rows; } }; + } + + it("W2: wakes the task with a comment after the seeded delay, and waits until a run serves it", async () => { + const { calls, record, notes, step } = harness({}); + await step(sample("in_progress", [run("r1", "running", 1_000)]), 2_000); + expect(awaitingRewake(record, 2_000)).toBe(false); + await step(sample("in_review", [run("r1", "succeeded", 1_000)]), 5_000); + expect(record.rewake).toMatchObject({ firstRunId: "r1", firstSettledAt: 5_000 }); + expect(awaitingRewake(record, 5_000)).toBe(true); + await step(sample("in_review", [run("r1", "succeeded", 1_000)]), 14_000); + expect(calls).toHaveLength(0); + // Faults still pending: the board waits. + await step(sample("in_review", [run("r1", "succeeded", 1_000)]), 16_000, false); + expect(calls).toHaveLength(0); + await step(sample("in_review", [run("r1", "succeeded", 1_000)]), 16_000); + expect(calls).toEqual([{ method: "post", route: "/api/issues/i1/comments", body: { body: expect.stringContaining(rewakeMarker("0bcd1204")) } }]); + expect(awaitingRewake(record, 17_000)).toBe(true); + await step(sample("in_progress", [run("r1", "succeeded", 1_000), run("r2", "running", 16_500)]), 20_000); + expect(record.rewake).toMatchObject({ servedByRunId: "r2" }); + expect(awaitingRewake(record, 20_000)).toBe(false); + expect(notes).toEqual(["rewake_first_run_settled", "rewake_sent", "rewake_served"]); + }); + + it("W2 monitor: schedules a board monitor due now", async () => { + const { calls, step } = harness({ nonce: "0bcd1214" }); + await step(sample("in_review", [run("r1", "succeeded", 1_000)]), 5_000); + await step(sample("in_review", [run("r1", "succeeded", 1_000)]), 15_000); + expect(calls).toEqual([{ method: "patch", route: "/api/issues/i1", body: { executionPolicy: { monitor: { + nextCheckAt: new Date(17_000).toISOString(), notes: "Phase 2 check for 0bcd1214", scheduledBy: "board" } } } }]); + }); + + it("W2C: changes the agent configuration first, then wakes at least 5 s later", async () => { + const { calls, record, step } = harness({ workload: "W2C", followUpAfterMs: 0 }); + await step(sample("in_review", [run("r1", "succeeded", 1_000)]), 5_000); + expect(calls).toEqual([{ method: "patch", route: "/api/agents/a1", body: { adapterConfig: { idleTimeoutMs: 301_003 } } }]); + await step(sample("in_review", [run("r1", "succeeded", 1_000)]), 7_000); + expect(calls).toHaveLength(1); + await step(sample("in_review", [run("r1", "succeeded", 1_000)]), 10_000); + expect(calls).toHaveLength(2); + }); + + it("W2C: waits CONFIG_SETTLE_MS after a late configuration change", async () => { + const { calls, record, step } = harness({ workload: "W2C", followUpAfterMs: 0 }); + await step(sample("in_review", [run("r1", "succeeded", 1_000)]), 5_000, false); + // The board was held for 30 s; the seeded delay is long past when it may act. + await step(sample("in_review", [run("r1", "succeeded", 1_000)]), 35_000); + await step(sample("in_review", [run("r1", "succeeded", 1_000)]), 38_000); + expect(calls).toHaveLength(1); + await step(sample("in_review", [run("r1", "succeeded", 1_000)]), 40_000); + expect(calls).toHaveLength(2); + expect(record.rewake?.configChange).toMatchObject({ httpStatus: 200, idleTimeoutMs: 301_003 }); + }); + + it("W2Q: comments while the question is pending, and answers only after that run settled", async () => { + const { calls, record, step, setInteractions } = harness({ workload: "W2Q", followUpAfterMs: 0 }); + setInteractions([{ id: "q1", kind: "ask_user_questions", status: "pending", sourceRunId: "r1", + payload: { questions: [{ id: "codename", options: [{ id: "opt-a", label: "ALPHA" }, { id: "opt-b", label: "BRAVO" }] }] } }]); + await step(sample("in_progress", [run("r1", "running", 1_000)]), 2_000); + expect(record.rewake?.firstSettledAt).toBeNull(); + await step(sample("in_progress", [run("r1", "succeeded", 1_000)]), 4_000); + expect(calls.map(call => call.route)).toEqual(["/api/issues/i1/comments"]); + expect(calls[0]!.body).toEqual({ body: expect.stringContaining(noteMarker("0bcd1204")) }); + await step(sample("in_progress", [run("r1", "succeeded", 1_000), run("r2", "running", 4_500)]), 6_000); + expect(calls).toHaveLength(1); + expect(awaitingRewake(record, 6_000)).toBe(true); + await step(sample("in_progress", [run("r1", "succeeded", 1_000), run("r2", "succeeded", 4_500)]), 9_000); + expect(calls.map(call => call.route)).toEqual(["/api/issues/i1/comments", "/api/issues/i1/interactions/q1/respond"]); + expect(awaitingRewake(record, 9_000)).toBe(false); + }); + + const rewakeArtifacts = (overrides: Partial = {}): RewakeArtifacts => ({ kind: "comment", firstRunId: "r1", firstSettledAt: 5_000, + sent: { at: 16_000, kind: "comment", statusAtWake: "in_review", httpStatus: 200, error: null }, servedByRunId: "r2", + runs: [{ id: "r1", status: "succeeded", errorCode: null, createdAt: null, finishedAt: null }, + { id: "r2", status: "succeeded", errorCode: null, createdAt: null, finishedAt: null }], ...overrides }); + const artifacts = (brief: string, rewake: RewakeArtifacts, extra: Partial = {}): OracleArtifacts => ({ issueStatus: "done", + documents: { brief }, agentComments: [], files: {}, commands: {}, workspacePath: null, rewake, ...extra }); + + it("grades a served wake and fails a failed attempt before it (staging class C+)", () => { + const brief = `CHAOS-0bcd1204\n- a\n- b\n- c\n${rewakeMarker("0bcd1204")}\n`; + expect(gradeRewake({ workload: "W2", nonce: "0bcd1204" }, artifacts(brief, rewakeArtifacts())).verdict).toBe("pass"); + const failed = gradeRewake({ workload: "W2", nonce: "0bcd1204" }, artifacts(brief, rewakeArtifacts({ servedByRunId: "r2", runs: [ + { id: "r1", status: "succeeded", errorCode: null, createdAt: null, finishedAt: null }, + { id: "r2", status: "failed", errorCode: "provider_transport_failed", createdAt: null, finishedAt: null }, + { id: "r3", status: "succeeded", errorCode: null, createdAt: null, finishedAt: null }] }))); + expect(failed.checks.filter(check => !check.ok).map(check => check.name)).toEqual(["rewake_served", "no_failed_attempt"]); + const w2q = gradeRewake({ workload: "W2Q", nonce: "0bcd1204" }, artifacts(`${q1AnswerMarker("0bcd1204", q1Code("0bcd1204"))}\n${noteMarker("0bcd1204")}\n- a\n- b\n- c`, + rewakeArtifacts(), { question: { interactionIds: ["q1"], seenAt: 1, askedByRunId: "r1", pendingNow: false, statuses: {}, runs: [], + answer: { at: 20_000, interactionId: "q1", code: q1Code("0bcd1204"), httpStatus: 200, error: null } } })); + expect(w2q.verdict).toBe("pass"); + }); +}); + +describe("--fail-recovery-step", () => { + it("names a step by its short name or crash point, after a restart fault, in an environment that reaches it", () => { + expect(parseRecoveryStep("directory-lock:2")).toEqual({ point: "agent_directory.operation_lock.before_acquire", nth: 2 }); + expect(parseRecoveryStep("native.process_start.after_requested_before_spawn")).toEqual({ point: "native.process_start.after_requested_before_spawn", nth: 1 }); + expect(recoveryStepControlSpec({ point: "environment.teardown.after_claim_before_destroy", nth: 3 })).toBe("environment.teardown.after_claim_before_destroy:3 fail"); + expect(() => parseRecoveryStep("nope")).toThrow("unknown step"); + expect(wave(["--faults", "K1", "--fail-recovery-step", "runnerd-start:2"]).failRecoveryStep).toBe("native.process_start.after_requested_before_spawn:2"); + expect(() => parseCommand(["--faults", "K0", "--workloads", "A1", "--fail-recovery-step", "runnerd-start"])).toThrow("add one of"); + expect(() => parseCommand(["--faults", "K1", "--fail-recovery-step", "directory-lock"])).toThrow("--env daytona"); + }); + + it("checks that the armed step failed and that no attempt of a crossed task failed", () => { + const hits = parseRecoveryStepReceipts([JSON.stringify({ point: "x", hit: 2, pid: 1, token: "rs-f01", mode: "fail" }), + JSON.stringify({ point: "y", hit: 1, pid: 1 }), "partial"].join("\n")); + expect(hits).toHaveLength(1); + const base = { verdict: "pass" as const, checks: [{ name: "issue_done", ok: true }] }; + const armed = { faultId: "f01", spec: "x:2", token: "rs-f01" }; + expect(withRecoveryStepCheck(base, armed, ["f02"], hits, [])).toBe(base); + expect(withRecoveryStepCheck(base, armed, ["f01"], hits, [{ id: "r1", status: "succeeded", errorCode: null }]).verdict).toBe("pass"); + const failed = withRecoveryStepCheck(base, armed, ["f01"], hits, [{ id: "r1", status: "failed", errorCode: "runner_remote_process_identity_unavailable" }]); + expect(failed.checks.find(check => check.name === "no_failed_attempt")).toMatchObject({ ok: false }); + expect(withRecoveryStepCheck(base, armed, ["f01"], [], []).checks.find(check => check.name === "recovery_step_failed_once")).toMatchObject({ ok: false }); + }); +}); + +describe("--long-turn-minutes", () => { + it("puts rounds of real tool work in front of any workload, with a longer budget and its own checks", () => { + const options = wave(["--workloads", "A1", "--faults", "K1", "--long-turn-minutes", "15", "--adapters", "codex", "--tasks", "1"]); + expect(options.longTurnMinutes).toBe(15); + expect(planWave("w-20261111T000000-s1", options).tasks[0]).toMatchObject({ longTurnMinutes: 15 }); + expect(() => parseCommand(["--long-turn-minutes", "5"])).toThrow("between 15 and 60"); + expect(() => parseCommand(["--workloads", "Q1", "--faults", "K1", "--matrix", "--long-turn-minutes", "15"])).toThrow("not a --matrix option"); + const definition = withLongTurn(workloadDefinitions.A1, 15); + expect(definition.budgetMs).toBe(workloadDefinitions.A1.budgetMs + 15 * 60_000); + expect(definition.collect.documents).toEqual(["brief", "long-turn"]); + expect(definition.description("0bcd1234")).toContain(`Run this shell command ${longTurnRounds(15)} times`); + expect(longTurnCommand("0bcd1234", 3)).toContain("ROUND 3 $s"); + expect(withLongTurn(workloadDefinitions.A1, undefined)).toBe(workloadDefinitions.A1); + }); + + it("checks the reported rounds and a run the harness saw last the whole turn", () => { + const start = 1_800_000_000; + const log = Array.from({ length: 10 }, (_, index) => `ROUND ${index + 1} ${start + index * 92} ${start + index * 92 + 91} 1234`).join("\n"); + expect(parseLongTurnLog(log)).toHaveLength(10); + const runs = [{ id: "r1", status: "succeeded", errorCode: null, createdAt: new Date(0).toISOString(), finishedAt: new Date(16 * 60_000).toISOString() }]; + expect(longTurnChecks(15, { documents: { "long-turn": log }, runs }).every(check => check.ok)).toBe(true); + const short = longTurnChecks(15, { documents: { "long-turn": log.split("\n").slice(0, 4).join("\n") }, runs: [{ ...runs[0]!, finishedAt: new Date(5 * 60_000).toISOString() }] }); + expect(short.map(check => check.ok)).toEqual([false, false]); + }); +}); + +describe("K15 staging deploy shape", () => { + it("parses the overlap and the fresh home, and refuses what does not fit", () => { + const options = wave(["--env", "daytona", "--daytona-image", `ghcr.io/x/y@sha256:${"a".repeat(64)}`, "--faults", "K15", "--k15-overlap-seconds", "30-150", + "--k15-fresh-home", "--concurrency", "2"]); + expect(options).toMatchObject({ k15HoldMs: [30_000, 150_000], k15Overlap: true, k15FreshHome: true }); + expect(planTasks(options).every(task => task.fault !== "K15" || (task.holdMs >= 30_000 && task.holdMs <= 150_000))).toBe(true); + expect(() => parseK15DeployShape({ env: "local", faults: ["K15"] }, undefined, true)).toThrow("--env daytona"); + expect(() => parseK15DeployShape({ env: "daytona", faults: ["K1"] }, "30", false)).toThrow("add K15"); + expect(() => parseK15DeployShape({ env: "daytona", faults: ["K15"], k15HoldMs: [1, 2] }, "30", false)).toThrow("--k15-hold-seconds"); + expect(() => parseK15DeployShape({ env: "daytona", faults: ["K15"] }, "2-3", false)).toThrow("between 5 and 600"); + }); + + it("drops the volume variables for a fresh home, and gives each generation its own home", () => { + const identity = redeployIdentity("w-20261111T000000-s1", 1); + expect(redeployEnvironment(identity, "/tmp/home")).toMatchObject({ RAILWAY_VOLUME_MOUNT_PATH: "/tmp/home" }); + expect(redeployEnvironment(identity, null)).not.toHaveProperty("RAILWAY_VOLUME_ID"); + expect(generationHome("/tmp/root", "/tmp/root/home", 0)).toBe("/tmp/root/home"); + expect(generationHome("/tmp/root", "/tmp/root/home", 2)).toBe("/tmp/root/home-g2"); + }); + + it("switches new connections at the edge while old connections stay on the old backend", async () => { + const listen = (reply: string) => new Promise(resolve => { + const server = net.createServer(socket => socket.end(reply)); + server.listen(0, "127.0.0.1", () => resolve(server)); + }); + const port = (server: net.Server) => (server.address() as net.AddressInfo).port; + const read = (edgePort: number) => new Promise((resolve, reject) => { + const socket = net.connect(edgePort, "127.0.0.1"); + let text = ""; + socket.on("data", chunk => { text += chunk.toString(); }); + socket.on("end", () => resolve(text)); + socket.on("error", reject); + }); + const [a, b] = await Promise.all([listen("A"), listen("B")]); + const free = await listen(""); + const edgePort = port(free); + await new Promise(resolve => free.close(() => resolve())); + const edge = await startEdgeProxy(edgePort, port(a)); + try { + expect(await read(edgePort)).toBe("A"); + edge.target = port(b); + expect(await read(edgePort)).toBe("B"); + } finally { + await edge.close(); + a.close(); b.close(); + } + }); +}); diff --git a/tests/restart-chaos/supervisor.ts b/tests/restart-chaos/supervisor.ts index ddb982d2be8..671e5b1b7f7 100644 --- a/tests/restart-chaos/supervisor.ts +++ b/tests/restart-chaos/supervisor.ts @@ -16,7 +16,7 @@ import { execFileSync, spawn, type ChildProcess } from "node:child_process"; import { randomBytes } from "node:crypto"; import { createWriteStream, readFileSync, statSync, writeFileSync, type WriteStream } from "node:fs"; -import { mkdir, readFile, symlink, writeFile } from "node:fs/promises"; +import { copyFile, mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises"; import { createRequire } from "node:module"; import os from "node:os"; import path from "node:path"; @@ -39,7 +39,8 @@ import { isRepeatedRestartFault, newRepeatedRestartRecord, recordFirstRestart, r type RepeatedRestartRecord, type RestartStep } from "./repeated-restarts.js"; import type { FaultKind, FaultReceipt, TriggerId } from "./types.js"; import { isMultiServerFault, runMultiServerFault, type MultiServerKind, type MultiServerRecord, type ServerProcessWindow } from "./multi-server.js"; -import { nextRedeployIdentity, redeployEnvironment, redeployIdentity, redeployNodeArgs, redeployReceipt, type RedeployIdentity } from "./redeploy.js"; +import { generationHome, nextRedeployIdentity, redeployEnvironment, redeployIdentity, redeployNodeArgs, redeployReceipt, type RedeployIdentity } from "./redeploy.js"; +import { startEdgeProxy, type EdgeProxy } from "./edge-proxy.js"; /** First boot applies every migration; a loaded host can need longer (RESTART_CHAOS_HEALTH_TIMEOUT_MS). */ const HEALTH_TIMEOUT_MS = (() => { @@ -93,7 +94,9 @@ export function readCrashPointReceipt(receiptPath: string, pid: number | undefin try { text = readFileSync(receiptPath, "utf8"); } catch { return null; } for (const line of text.split("\n").reverse()) { try { - const parsed = JSON.parse(line) as { point?: unknown; hit?: unknown; pid?: unknown }; + const parsed = JSON.parse(line) as { point?: unknown; hit?: unknown; pid?: unknown; mode?: unknown }; + // A fail-mode hit (`--fail-recovery-step`) threw in the server; it did not kill it. + if (parsed.mode === "fail") continue; if (pid !== undefined && parsed.pid === pid && typeof parsed.point === "string" && typeof parsed.hit === "number") { const token = (parsed as { token?: unknown }).token; return { name: parsed.point, hit: parsed.hit, pid, ...(typeof token === "string" ? { token } : {}) }; @@ -115,6 +118,8 @@ async function prepareProviderPath(repositoryRoot: string, temporaryRoot: string const manifest = JSON.parse(await readFile(codexPackage, "utf8")) as { bin?: string | Record }; const codexBin = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.codex; if (!codexBin) throw new Error("Pinned Codex executable not found"); + // A K15 with a fresh home or an overlap prepares the environment again: replace the link. + await rm(path.join(toolBin, "codex"), { force: true }); await symlink(path.resolve(path.dirname(codexPackage), codexBin), path.join(toolBin, "codex")); return [toolBin, path.join(repositoryRoot, "packages/paperclip-runner/node_modules/.bin"), inherited].filter(Boolean).join(path.delimiter); } @@ -162,6 +167,16 @@ export class ChaosSupervisor { * before the next deploy starts, while the server is down. It must not throw. */ redeployEvidence: ((faultId: string, phase: "stopped" | "before_start") => Promise) | null = null; + /** K15 deploy shape (redeploy.ts `parseK15DeployShape`); main.ts sets it before `start`. */ + deployShape: { overlap: boolean; freshHome: boolean } = { overlap: false, freshHome: false }; + /** `--k15-fresh-home`: the instance home and config of the serving generation (generation 0 uses `paths`). */ + private serverHome: { home: string; configPath: string }; + /** `--k15-overlap-seconds`: the edge on the wave's port, and the serving generation's own port behind it. */ + private edge: EdgeProxy | null = null; + private backendPort: number; + /** `--fail-recovery-step`: ":", armed in fail mode when the first restart fault starts its replacement. */ + private pendingRecoveryStep: string | null = null; + private recoveryStepWatch: NodeJS.Timeout | null = null; /** Wave secrets, kept across a K14 switch as an in-place upgrade keeps its configuration. */ private readonly secrets = { PAPERCLIP_AGENT_JWT_SECRET: secret(), PAPERCLIP_DECISION_SIGNING_SECRET: secret(), PAPERCLIP_TOOL_ACTION_SIGNING_SECRET: secret(), BETTER_AUTH_SECRET: secret() }; @@ -169,6 +184,8 @@ export class ChaosSupervisor { private constructor(readonly repositoryRoot: string, readonly port: number, readonly paths: SupervisorPaths, private readonly timeline: Timeline, upgradeFrom: string | null, redeployWaveId: string | null) { this.serverRoot = upgradeFrom ?? repositoryRoot; + this.serverHome = { home: paths.home, configPath: paths.configPath }; + this.backendPort = port; if (redeployWaveId) this.redeploy = { waveId: redeployWaveId, identity: redeployIdentity(redeployWaveId, 0) }; this.baseUrl = `http://127.0.0.1:${port}`; this.log = createWriteStream(paths.serverLogPath, { flags: "a", mode: 0o600 }); @@ -211,6 +228,12 @@ export class ChaosSupervisor { this.database = await prepareControllerDatabase(configPath, temporaryRoot); this.timeline.add("database_started", {}); this.extraEnvironment = extraEnvironment; + if (this.deployShape.overlap) { + // The wave's port becomes the edge; each generation listens behind it on its own port. + this.backendPort = await reserveRunnerE2EServerPort(); + this.edge = await startEdgeProxy(this.port, this.backendPort); + this.timeline.add("edge_proxy_started", { port: this.port, target: this.backendPort }); + } await this.prepareServerEnvironment(this.serverRoot); const child = await this.spawnServer(); await this.waitForHealth(child); @@ -224,7 +247,8 @@ export class ChaosSupervisor { * switch, as an in-place upgrade keeps them. */ private async prepareServerEnvironment(root: string): Promise { - const { temporaryRoot, home, configPath } = this.paths; + const { temporaryRoot } = this.paths; + const { home, configPath } = this.serverHome; const extraEnvironment = this.extraEnvironment; const runnerBinary = resolvePaperclipRunnerBinaryForHarness( [{ profile: { generation: "native" } } as unknown as MatrixExecution], root); @@ -239,7 +263,7 @@ export class ChaosSupervisor { PAPERCLIP_VITE_CACHE_DIR: path.join(temporaryRoot, "vite-cache"), }; const overrides = { - NODE_ENV: "test", PORT: String(this.port), XDG_CACHE_HOME: path.join(temporaryRoot, "xdg-cache"), + NODE_ENV: "test", PORT: String(this.backendPort), XDG_CACHE_HOME: path.join(temporaryRoot, "xdg-cache"), PAPERCLIP_HOME: home, PAPERCLIP_CONFIG: configPath, PAPERCLIP_INSTANCE_ID: "default", ...this.secrets, PAPERCLIP_BIND: "loopback", PAPERCLIP_BIND_HOST: "127.0.0.1", PAPERCLIP_DEPLOYMENT_MODE: "local_trusted", @@ -254,7 +278,7 @@ export class ChaosSupervisor { ...waveServerUrlEnvironment(this.port), ...extraEnvironment, // K15: the generation's emulated host name and Railway deployment identity; the volume is the instance home. - ...(this.redeploy ? redeployEnvironment(this.redeploy.identity, home) : {}), + ...(this.redeploy ? redeployEnvironment(this.redeploy.identity, this.deployShape.freshHome ? null : home) : {}), }; const environment = buildPaperclipServerEnvironment(source, overrides); const workspaceStorage = extraEnvironment.PAPERCLIP_STORAGE_PROVIDER === "s3" @@ -474,6 +498,8 @@ export class ChaosSupervisor { let outage: ControllerOutageReceipt | undefined; if (kind === "TM1" || kind === "TM2") await this.freeze(kind, previous, holdMs, receipt); else if (isMultiServerFault(kind)) await this.multiServer(kind, previous, holdMs, receipt); + // `--k15-overlap-seconds`: the next deploy boots beside the old server; its hold is the overlap. + else if (kind === "K15" && this.deployShape.overlap) await this.rollingRedeploy(previous, holdMs, receipt); else outage = await replaceController({ requestId: `chaos-${receipt.faultId}-${requestedBy}`, previousPid: previous.pid, @@ -506,10 +532,12 @@ export class ChaosSupervisor { if (kind === "K15") { // After the hold, before the next deploy starts: what its recovery will find in the sandboxes. await this.redeployEvidence?.(receipt.faultId, "before_start"); - receipt.redeploy = this.advanceDeploy(receipt.faultId); + receipt.redeploy = await this.advanceDeploy(receipt.faultId); } this.timeline.add("fault_restarting", { faultId: receipt.faultId }); - return this.spawnServer(); + const replacement = await this.spawnServer(); + this.armPendingRecoveryStep(receipt, replacement.pid); + return replacement; }, waitForReady: async replacement => { // RR with `--rr-stop-on`: watch the first replacement from spawn; waiting for health first would let a @@ -693,18 +721,101 @@ export class ChaosSupervisor { } /** K15: move the next server to the next deploy generation (redeploy.ts). */ - private advanceDeploy(faultId: string): NonNullable { + private async advanceDeploy(faultId: string): Promise> { if (!this.redeploy || !this.environment) throw new Error("K15 needs a redeploy wave (ChaosSupervisor.create redeployWaveId)"); const from = this.redeploy.identity; const to = nextRedeployIdentity(this.redeploy.waveId, from); this.redeploy.identity = to; - Object.assign(this.environment, redeployEnvironment(to, this.paths.home)); + if (this.deployShape.freshHome) this.serverHome = await this.freshGenerationHome(faultId, to.generation); + if (this.deployShape.overlap) this.backendPort = await reserveRunnerE2EServerPort(); + if (this.deployShape.freshHome || this.deployShape.overlap) await this.prepareServerEnvironment(this.serverRoot); + else Object.assign(this.environment, redeployEnvironment(to, this.paths.home)); const receipt = redeployReceipt(from, to); this.timeline.add("redeploy_switched", { faultId, ...receipt }); this.log.write(`\n[restart-chaos] ${faultId} K15 redeploy ${from.hostname}/${from.deploymentId} -> ${to.hostname}/${to.deploymentId}\n`); return receipt; } + /** + * `--k15-fresh-home`: a new, empty instance home for the next generation. Only what a hosted deploy gets from + * outside its container is carried over: the configuration (database, storage) and the secrets master key. + */ + private async freshGenerationHome(faultId: string, generation: number): Promise<{ home: string; configPath: string }> { + const home = generationHome(this.paths.temporaryRoot, this.paths.home, generation); + const instanceRoot = path.join(home, "instances", "default"); + await mkdir(path.join(instanceRoot, "secrets"), { recursive: true, mode: 0o700 }); + const config = JSON.parse(await readFile(this.paths.configPath, "utf8")) as Record; + const keyFile = path.join(instanceRoot, "secrets", "master.key"); + await copyFile(String(config.secrets?.localEncrypted?.keyFilePath ?? path.join(path.dirname(this.paths.configPath), "secrets", "master.key")), keyFile); + config.secrets = { ...config.secrets, localEncrypted: { ...config.secrets?.localEncrypted, keyFilePath: keyFile } }; + config.logging = { ...config.logging, logDir: path.join(instanceRoot, "logs") }; + const configPath = path.join(instanceRoot, "config.json"); + await writeFile(configPath, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 }); + this.timeline.add("k15_fresh_home", { faultId, generation, home }); + return { home, configPath }; + } + + /** + * `--k15-overlap-seconds`: the staging deploy shape. The next generation boots beside the old server on its own + * port; once it is ready, the edge sends new connections to it; the old server keeps running for the overlap and + * then gets SIGTERM. There is no outage. + */ + private async rollingRedeploy(previous: ChildProcess, overlapMs: number, receipt: FaultReceipt): Promise { + if (!this.edge) throw new Error("--k15-overlap-seconds needs the edge proxy started with the wave"); + const fromPort = this.backendPort; + receipt.redeploy = await this.advanceDeploy(receipt.faultId); + receipt.restartedAt = Date.now(); + this.timeline.add("fault_restarting", { faultId: receipt.faultId, overlapMs }); + const next = await this.spawnServer(); + // Bound to the next generation: the old server keeps serving during the overlap and must not count hits. + this.armPendingRecoveryStep(receipt, next.pid); + const backendUrl = `http://127.0.0.1:${this.backendPort}`; + receipt.healthyAt = await this.waitForHealth(next, receipt.phases, backendUrl); + const deadline = Date.now() + READY_TIMEOUT_MS; + while (await this.readPhase(backendUrl) !== "ready") { + if (this.shuttingDown) throw new Error("Harness shutdown interrupted the rolling redeploy"); + if (this.exited(next)) throw new Error(`Next deploy exited during startup (code=${next.exitCode} signal=${next.signalCode})`); + if (Date.now() > deadline) throw new Error(`Next deploy did not report ready within ${READY_TIMEOUT_MS}ms`); + await delay(250); + } + this.edge.target = this.backendPort; + this.timeline.add("k15_traffic_switched", { faultId: receipt.faultId, fromPort, toPort: this.backendPort, overlapMs }); + for (const until = Date.now() + overlapMs; Date.now() < until && !this.shuttingDown;) await delay(Math.min(1_000, until - Date.now())); + await this.stopper(previous, "SIGTERM"); + receipt.stoppedAt = Date.now(); + this.timeline.add("fault_server_down", { faultId: receipt.faultId, previousPid: previous.pid, overlapMs }); + await this.redeployEvidence?.(receipt.faultId, "stopped"); + } + + /** `--fail-recovery-step`: arm the step in fail mode for the wave's first restart fault only. */ + armRecoveryStepOnFirstFault(spec: string, control: CrashPointControl): void { + this.useCrashPointControl(control); + this.pendingRecoveryStep = spec; + } + + /** + * Arms the step for the replacement process only (`pid=`), and disarms the control file once its receipt + * landed, so a later server (RR, K6, another task's restart) never fails the step again. + */ + private armPendingRecoveryStep(receipt: FaultReceipt, pid: number | undefined): void { + if (!this.pendingRecoveryStep || !pid || !this.crashPointControl) return; + const token = `rs-${receipt.faultId}`; + this.armCrashPoint(token, `${this.pendingRecoveryStep} fail pid=${pid}`); + receipt.recoveryStep = { spec: this.pendingRecoveryStep, token }; + this.pendingRecoveryStep = null; + const receiptPath = this.crashPointControl.receiptPath; + const watch = setInterval(() => { + let text = ""; + try { text = readFileSync(receiptPath, "utf8"); } catch { return; } + if (!text.includes(`"token":"${token}"`)) return; + clearInterval(watch); + this.disarmCrashPoint(); + this.timeline.add("recovery_step_disarmed", { faultId: receipt.faultId, token }); + }, 500); + watch.unref(); + this.recoveryStepWatch = watch; + } + /** * K14: move the server from the older build to this checkout. Only the first K14 switches; a later * one restarts the current build (recorded with `switched: false`). @@ -834,8 +945,10 @@ export class ChaosSupervisor { async stop(): Promise { this.shuttingDown = true; + if (this.recoveryStepWatch) clearInterval(this.recoveryStepWatch); const errors: string[] = []; try { await this.stopper.stopAll(); } catch (error) { errors.push(error instanceof Error ? error.message : String(error)); } + await this.edge?.close().catch(error => { errors.push(error instanceof Error ? error.message : String(error)); }); try { await this.database?.cleanup(); } catch (error) { errors.push(error instanceof Error ? error.message : String(error)); } await new Promise(resolve => this.log.end(resolve)); this.timeline.add("supervisor_stopped", { errors }); diff --git a/tests/restart-chaos/types.ts b/tests/restart-chaos/types.ts index 7c28ff11f6c..efd17f66eb0 100644 --- a/tests/restart-chaos/types.ts +++ b/tests/restart-chaos/types.ts @@ -32,8 +32,9 @@ export type TaskFaultKind = FaultKind | "K13" | "K0" | ProviderFaultKind | DiskF * L1: high-output, high-accounting run for database contention (contention.ts). * F1: an absolute symlink pointing out of the repository workspace, kept at rest (staging save-back class F). * T1: a 100-second shell tool in the agent's workspace, so a fault lands while the remote Runner runs a tool (staging class R). + * W2, W2Q, W2C: the same task woken again 0–60 s after its run succeeded (rewake.ts), many tasks on one agent. */ -export const WORKLOAD_IDS = ["A1", "B1", "B5", "C1", "M1", "G1", "H1", "R1", "S1", "Q1", "L1", "Q2", "Q3", "Q4", "F1", "T1"] as const; +export const WORKLOAD_IDS = ["A1", "B1", "B5", "C1", "M1", "G1", "H1", "R1", "S1", "Q1", "L1", "Q2", "Q3", "Q4", "F1", "T1", "W2", "W2Q", "W2C"] as const; export type WorkloadId = (typeof WORKLOAD_IDS)[number]; export const ADAPTER_IDS = ["codex", "claude", "opencode"] as const; @@ -77,8 +78,21 @@ export interface WaveOptions { daytonaInherit?: boolean; /** `--k4-hold-max-seconds`: upper end of the seeded K4 hold (default 300 s, cap 600 s). */ k4HoldMaxMs?: number; - /** `--k15-hold-seconds`: the seeded K15 outage range (redeploy.ts); absent restarts at once. */ + /** `--k15-hold-seconds`: the seeded K15 outage range (redeploy.ts); absent restarts at once. With `--k15-overlap-seconds`, the overlap range. */ k15HoldMs?: [number, number]; + /** `--k15-overlap-seconds`: a K15 boots the next deploy beside the old server and SIGTERMs the old one after the seeded overlap (redeploy.ts). */ + k15Overlap?: boolean; + /** `--k15-fresh-home`: each deploy generation gets a new, empty instance home and no volume (redeploy.ts). */ + k15FreshHome?: boolean; + /** `--faults K0`: cells with no fault, for workloads whose shape is the fault (W2, W2Q, W2C). */ + baseline?: boolean; + /** + * `--fail-recovery-step [:]` (recovery-step-faults.ts): once the wave's first restart fault fired, the + * nth hit of that crash point in the replacement throws its step's own error, once. + */ + failRecoveryStep?: string; + /** `--long-turn-minutes`: every task's first turn does this much real tool work before its workload (long-turn.ts). */ + longTurnMinutes?: number; /** `--tm1-hold-seconds`: the seeded TM1 stall range (time-faults-config.ts); absent uses 95–150 s. */ tm1HoldMs?: [number, number]; faultAfterMs?: number; @@ -190,6 +204,8 @@ export interface TaskPlan { providerFault?: ProviderFaultRule; /** RR1–RR3: the seeded restarts after the first kill. */ restartSteps?: RestartStep[]; + /** `--long-turn-minutes`: the first turn's tool work before the workload (long-turn.ts). */ + longTurnMinutes?: number; } export interface ScheduledFault { @@ -305,6 +321,8 @@ export interface FaultReceipt { upgrade?: { fromRoot: string; fromSha: string | null; toRoot: string; toSha: string | null; switched: boolean }; /** K15: the deploy generation, emulated host name and deployment id before and after. */ redeploy?: ReturnType; + /** `--fail-recovery-step`: the step armed (fail mode) when this fault's replacement started. */ + recoveryStep?: { spec: string; token: string }; /** TM1–TM3: what was frozen and which rows were aged. */ timeFault?: TimeFaultRecord; /** RR1–RR3: every stop and replacement of the sequence, the first kill included. */ @@ -341,6 +359,10 @@ export interface OracleArtifacts { contention?: import("./contention.js").ContentionEvidence; /** Q2, Q3: what the board did and what the task, its runs and the harness's app saw. */ journey?: import("./journeys.js").JourneyArtifacts; + /** W2, W2Q, W2C: the re-wake and the task's runs (rewake.ts). */ + rewake?: import("./rewake.js").RewakeArtifacts; + /** `--long-turn-minutes`: the task's runs, for the harness's own long-turn evidence (long-turn.ts). */ + runs?: import("./rewake.js").RewakeArtifacts["runs"]; } /** What the board did for a governance task (G1, H1), and what the observer saw. */ @@ -429,6 +451,8 @@ export interface TaskRecord { question?: QuestionRecord; /** Q2, Q3: the board's journey actions (journey-driver.ts). */ journey?: import("./journeys.js").JourneyRecord; + /** W2, W2Q, W2C: the first run, the board's wake and the run that served it (rewake.ts). */ + rewake?: import("./rewake.js").RewakeRecord; /** PV with `--provider-fault-restart`: when the shim logged the task's fault (arms the `provider` trigger). */ providerFaultAppliedAt?: number; /** DF1: when the fault was armed and cleared, and what the board showed at the disk-full rest. */ diff --git a/tests/restart-chaos/workloads.ts b/tests/restart-chaos/workloads.ts index 73cf39825fe..e54ebda7f2f 100644 --- a/tests/restart-chaos/workloads.ts +++ b/tests/restart-chaos/workloads.ts @@ -1,6 +1,7 @@ import { questionHandoffWorkload, questionSequenceWorkload } from "./question-handoff.js"; import { l1Workload } from "./contention.js"; import { journeyWorkloadDefinitions } from "./journeys.js"; +import { rewakeWorkloadDefinitions } from "./rewake.js"; import type { OracleArtifacts, OracleResult, WorkloadId } from "./types.js"; /** Deterministic bench output: sum of squares 1..240. */ @@ -218,6 +219,7 @@ export const workloadDefinitions: Record = { Q4: questionSequenceWorkload, L1: l1Workload, ...journeyWorkloadDefinitions, + ...rewakeWorkloadDefinitions, G1: { id: "G1", label: "Approval-gated action across a restart", diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 3ef601ea748..3ca35ccbe57 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -226,9 +226,9 @@ "packages/shared/src/connector-identity.test.ts": "d58357707faefa7c98bb906cdaeb4db39d31081a", "packages/shared/src/connector-identity.ts": "5ede83c9c5225dbe8af9cf3a49c74e477ef5b955", "packages/shared/src/constants.ts": "3149ee1cc5ffa34b50ecd493276b3a70fc46adc2", - "packages/shared/src/crash-point-registry.ts": "8d6f60e8ad8f90338fb3047955bb32160f50b9ae", - "packages/shared/src/crash-points.test.ts": "804a3acfd7a51010f31dbc3fb9a4dca771562c99", - "packages/shared/src/crash-points.ts": "d9f31d95c78f32290190d7728f42cd9573681fc8", + "packages/shared/src/crash-point-registry.ts": "6e9694699cb8de9c934f92170b9cfcab2eed4a1a", + "packages/shared/src/crash-points.test.ts": "3564a1f62d22f54a3c2fb0a72b3a6cde17c957d2", + "packages/shared/src/crash-points.ts": "c15259f39610e352eac5423a491548ec1bae94fe", "packages/shared/src/customer-success.ts": "a2d02aaa8223164c0eae4267b2a6da82242eaa6f", "packages/shared/src/decision-models.ts": "a07aefd87d2fae34283ce21a0334d57e2108aa7e", "packages/shared/src/decision.test.ts": "d0783d18613c73102f662e8a5da795ff6e7faed5",