Merge current master while preserving Photon recovery and event wake ownership

Keep all current master recovery, plugin, and shared contract changes alongside the reviewed Photon lifecycle fixes and normal event-owner negotiation.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-11-11 13:07:42 -06:00
commit bec8d35e7c
108 files changed
+4435 -306

No files matched your search

+25 -3
View File
@@ -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
@@ -1454,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,
@@ -1711,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
+67 -1
View File
@@ -172,6 +172,18 @@ 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`.
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
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
@@ -251,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
@@ -264,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 |
@@ -352,6 +390,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
+6 -2
View File
@@ -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
+3 -2
View File
@@ -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.
@@ -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/)
@@ -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");
@@ -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",
@@ -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
@@ -1327,6 +1327,12 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
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())
@@ -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 }) } }]);
});
@@ -17,6 +17,11 @@ export function createOpenCodeFinishDiagnosticForwarder(send: (frame: Warning) =
if (message.length > 2048) return;
let value: Record<string, unknown>;
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<string, unknown>): 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";
}
@@ -76,6 +76,8 @@ export interface CodexAppServerTransport {
* diagnostic context; transports must not forward it to the provider.
*/
close(reason?: string): Promise<void>;
/** 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<DurableRecoveryIdentity | false>;
/** Relinquish controller authority while leaving durable runner work alive. */
@@ -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 });
@@ -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<void> { 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]);
@@ -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<Answer> {
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<void>(resolve => { release = resolve; });
let started!: () => void;
const handlerStarted = new Promise<void>(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,
});
});
@@ -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++) {
@@ -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<string, { fingerprint: string; promise: Promise<unknown>; waiting: Set<ServerResponse> }>();
const controllers = new Map<string, AbortController>();
const socketUses = new WeakMap<Socket, SocketUse>();
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<void> {
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) }] });
}
}
@@ -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);
@@ -1023,6 +1023,11 @@ function turnStartCommandResultValid(input: {
);
}
type CloseCheckpointRetry = {
checkpoint: () => Promise<void> | void;
finish: (deadline: number) => Promise<void>;
};
async function releaseRunnerProcessOwnership(input: {
runnerSettled: boolean;
checkpoint:
@@ -4044,7 +4049,10 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
readonly #closedSignal: Promise<void>;
#resolveClosedSignal!: () => void;
#closePromise: Promise<void> | null = null;
#pendingCloseCheckpointRetry: CloseCheckpointRetry | null = null;
#failedCloseCheckpoint: CloseCheckpointRetry | null = null;
#shutdownSettled = false;
#closeFinished = false;
#probeRetirement: Promise<void> | null = null;
readonly prepareConversationResume?: CodexAppServerTransport["prepareConversationResume"];
#detachPromise: Promise<void> | null = null;
@@ -4275,6 +4283,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<string, unknown>,
@@ -5292,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<void> {
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
@@ -5421,12 +5458,16 @@ 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) {
this.#diagnostic(`controller retirement after failed close is unconfirmed: ${String(retirementError)}`);
}
this.#failedCloseCheckpoint = this.#pendingCloseCheckpointRetry;
this.#pendingCloseCheckpointRetry = null;
throw error;
}
}
@@ -5637,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;
@@ -5655,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<ReturnType<typeof waitForProcess>>;
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(
@@ -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);
+2 -1
View File
@@ -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<PluginEnvironmentValidationResult>;
/** Required with manifest.workspaceProvider, together with project resource lifecycle. */
onWorkspacePrepare?(params: PluginWorkspacePrepareParams): Promise<PluginWorkspacePrepareResult>;
onWorkspaceOperation?(params: PluginWorkspaceParams): Promise<PluginWorkspaceResult>;
/** Provide Runner execution: prepare resources, start Runner, connect via PRP, and manage task lifecycle. */
+3 -1
View File
@@ -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",
+8 -2
View File
@@ -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");
@@ -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
@@ -124,6 +125,34 @@ export const pluginWorkspaceParamsSchema = z
/** Finalization receives the originating run/agent context; maintenance remains agent-independent. */
export type PluginWorkspaceParams = z.infer<typeof pluginWorkspaceParamsSchema>;
export const pluginWorkspacePrepareParamsSchema = pluginWorkspaceParamsSchema.extend({
phase: z.enum(["submit", "poll"]),
}).refine((input) => input.operation.kind === "prepare");
export type PluginWorkspacePrepareParams = z.infer<typeof pluginWorkspacePrepareParamsSchema>;
export type PluginWorkspacePrepareResult =
| { kind: "unsupported" }
| { kind: "pending"; deadline: string }
| Extract<PluginWorkspaceResult, { kind: "prepared" }>;
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,
@@ -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) } : {}) };
@@ -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"],
+36 -1
View File
@@ -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();
+46 -9
View File
@@ -16,10 +16,17 @@
*
* Runtime arming (one booted server, many points), instead of PAPERCLIP_CRASH_POINT:
*
* PAPERCLIP_CRASH_POINT_CONTROL=<file> each hit reads "<token> <name>[:<nth>]" from the file;
* PAPERCLIP_CRASH_POINT_CONTROL=<file> each hit reads "<token> <name>[:<nth>] [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=<n>` 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, "<token> <name>[:<nth>]"; null when empty or malformed. */
export function parseCrashPointControl(text: string): { token: string; spec: CrashPointSpec } | null {
/** Parses a control file line, "<token> <name>[:<nth>] [fail] [pid=<n>]"; 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");
}
+1
View File
@@ -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;
+1
View File
@@ -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(),
@@ -48,6 +48,11 @@ describe("board-only denial", () => {
["get", "/api/plugins/ui-contributions", "[Open plugin settings](/<prefix>/company/settings/instance/plugins)"],
["post", `/api/projects/${AGENT_ID}/access-members`, `[Open the project's access settings](/<prefix>/projects/${AGENT_ID}/configuration)`],
["delete", `/api/projects/${AGENT_ID}/access-members/m-1`, `[Open the project's access settings](/<prefix>/projects/${AGENT_ID}/configuration)`],
["get", `/api/companies/${COMPANY_ID}/environments`, "[Open environment settings](/<prefix>/company/settings/instance/environments)"],
["get", `/api/companies/${COMPANY_ID}/environments/capabilities`, "[Open environment settings](/<prefix>/company/settings/instance/environments)"],
["post", `/api/environments/${AGENT_ID}/probe`, "[Open environment settings](/<prefix>/company/settings/instance/environments)"],
["get", `/api/environment-leases/${AGENT_ID}`, "[Open environment settings](/<prefix>/company/settings/instance/environments)"],
["get", `/api/environment-custom-image-setup-sessions/${AGENT_ID}`, "[Open environment settings](/<prefix>/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);
@@ -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("<name>", { fail: ... }).
const CALL = /\bcrashPoint\(\s*"([^"]+)"\s*[,)]/g;
function sourceFiles(directory: string): string[] {
return readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
@@ -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](/<prefix>/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();
});
@@ -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<ReturnType<typeof seed>>) {
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) => {
@@ -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<typeof createDb>, options: { failDescriptorOnce?: { failed: boolean } } = {}):
function nativeBackend(db: ReturnType<typeof createDb>, options: { failDescriptorOnce?: { failed: boolean };
unretiredPredecessorOnce?: { failed: boolean; environmentId: string } } = {}):
NonNullable<HeartbeatServiceOptions["nativeSessionBackendFactory"]> {
return execution => {
let identity: NativeRunIdentity;
@@ -71,6 +74,19 @@ function nativeBackend(db: ReturnType<typeof createDb>, 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 });
@@ -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", () => {
@@ -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<ReturnType<typeof seed>>, context: Record<string, unknown> = {}) {
@@ -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<string, string | null | undefined>();
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<typeof storage.workers.call>) => {
const result = await storage.workers.call(...args) as Record<string, unknown>;
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");
@@ -1,10 +1,11 @@
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,
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,120 @@ 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 call = vi.fn<WorkspaceWorkers["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 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";
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(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: [] }],
@@ -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();
+12 -1
View File
@@ -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", "/<prefix>/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 <prefix>.`
: "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.";
+2 -1
View File
@@ -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");
}
@@ -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`);
@@ -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();
});
});
@@ -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=<file>
*
* Each acquisition reads the file. Missing, empty or malformed means disarmed.
* Content: {"token":"<id>","kind":"timeout"|"database","failures":<n>|null}.
* The first <n> 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<string, unknown>;
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<string, number>();
/** 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: <chaos>", {
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);
}
@@ -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");
});
});
@@ -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<TransientLeaseFailureReason, string> = {
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",
};
}
@@ -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<EnvironmentRuntimeLeaseRecord> {
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)}`,
+16 -2
View File
@@ -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",
@@ -3840,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({
@@ -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"
@@ -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<string, Promise<boolean>>();
for (const candidate of only ? freshCandidates : []) {
const checked = await retainedIssueWorkspaceForRetry(db, { companyId, issueId, agentId,
@@ -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<typeof heartbeatRuns.$inferSelect, "id" | "resultJson" | "status" | "finishedAt" | "controllerLeaseExpiresAt">;
evidence: Record<string, unknown> | null; gitProbes?: Map<string, Promise<boolean>>;
}): Promise<{ id: string; cwd: string } | null> {
verifyProviderWorkspace?: (workspace: typeof executionWorkspaces.$inferSelect) => Promise<boolean>;
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<typeof heart
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}`));
let retained: { id: string; cwd: string } | null = null;
let retained: { id: string; cwd: string | null } | null = null;
const gitProbes = new Map<string, Promise<boolean>>();
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<typeof heart
if (!wake) throw new Error("Fresh workspace admission lost its input receipt");
return readiness;
}
/** A running retry can retain its previous checkout after verifying a committed fresh fallback. */
export async function verifyRetryWorkspace(
db: Db,
workers: WorkspaceWorkers | undefined,
run: Pick<typeof heartbeatRuns.$inferSelect, "id" | "companyId" | "agentId" | "contextSnapshot">,
issueId: string,
responsibleUserId: string | null,
readiness: ContinuationReadiness,
): Promise<ContinuationReadiness> {
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;
}
+19 -5
View File
@@ -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";
@@ -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";
@@ -2254,7 +2255,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 +2538,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,
@@ -3841,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,
@@ -3858,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) {
@@ -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 });
@@ -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<typeof heartbeatRuns.$inferSelect, "id" | "companyId">;
/**
* 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<PredecessorRetirementFallback | null> {
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<boolean> {
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<typeof readRemoteWorkspaceAuthority>;
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 }));
});
}
@@ -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<Outcome> {
@@ -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))
+22 -2
View File
@@ -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,
@@ -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<string, unknown>; 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;
}
/**
@@ -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";
@@ -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<void> {
};
export function persistNativeHarnessBackup(input: PersistNativeHarnessBackupInput): Promise<void> {
return waitOutStorageOutages(() => storageOutageWaitFor("saving the provider session", () => persistNativeHarnessBackupOnce(input)));
}
async function persistNativeHarnessBackupOnce(input: PersistNativeHarnessBackupInput): Promise<void> {
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");
@@ -142,4 +142,51 @@ describeEmbeddedPostgres("durable native provider backups under an object-storag
await new Promise<void>(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<string, Buffer>(), refusals = new Map<string, number>();
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(
"<Error><Code>SlowDown</Code><Message>Please reduce your request rate.</Message><RequestId>throttled</RequestId></Error>");
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("<Error><Code>NoSuchKey</Code></Error>"); 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<void>((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<void>(resolve => server.close(() => resolve()));
}
}, 60_000);
});
@@ -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" });
@@ -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
@@ -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
@@ -446,6 +446,9 @@ import {
NATIVE_PROVIDER_SESSION_CLOSED,
NATIVE_PROVIDER_STARTUP_REJECTED,
nativeRemoteStartupRejectionCode,
nativeRepeatedStartupFailureAction,
nativePreviousStartupFailureSignature,
nativeStartupFailureSignature,
nativeSessionRecoveryProjection,
nativeGovernedWaitResult,
nativeConversationReplyResult,
@@ -10816,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<void> | 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<typeof target>) => 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");
@@ -12012,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<void> | 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<typeof target>) => {
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}`);
@@ -12151,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);
@@ -14169,6 +14249,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<string, unknown> = {}) =>
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", () => {
@@ -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<typeof closeWarmNativeSession>[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<NativeInstructionWorkingCopy | null>;
}): Promise<(() => Promise<void>) | 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>) => void; release: () => Promise<void> } | 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<void> {
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<string, string>,
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<string, str
return refuse(unsettled.length > 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<boolean> {
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<boolean> {
@@ -6176,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)) {
@@ -6235,7 +6315,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;
@@ -6773,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 {
@@ -8437,6 +8540,9 @@ export function nativeSessionFailureDisposition(
sourceFailureCode?: ReturnType<typeof nativeSessionFailureSourceCode>,
) {
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" ||
@@ -8517,14 +8623,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<string, unknown>;
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<Code extends string>(
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. */
@@ -8581,7 +8735,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;
@@ -9992,6 +10148,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"
@@ -10752,6 +10909,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();
@@ -11382,7 +11540,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) {
@@ -11426,7 +11586,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");
@@ -11753,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,
@@ -11959,6 +12121,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,
@@ -12310,7 +12473,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
@@ -12330,12 +12497,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 +12550,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 +12668,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 +12685,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 +12742,7 @@ async function executePaperclipNativeSessionAttempt(
providerSessionEstablished:
recoveryEvidence.providerSessionEstablished,
checkpointExists: recoveryEvidence.checkpointExists,
...(startupFailureSignature ? { startupFailureSignature } : {}),
})}::jsonb)
) with ordinality as history(item, ordinal)
where ordinal > greatest(
@@ -12569,6 +12760,7 @@ async function executePaperclipNativeSessionAttempt(
providerSessionEstablished:
recoveryEvidence.providerSessionEstablished,
checkpointExists: recoveryEvidence.checkpointExists,
...(startupFailureSignature ? { startupFailureSignature } : {}),
})}::jsonb)
) - 20,
0
@@ -12772,7 +12964,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"
@@ -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<string, unknown>[] } = {}) {
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<string, unknown>[]),
{ 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);
});
@@ -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<string, unknown>)[PREDECESSOR_RETIREMENT_FALLBACK_KEY];
if (typeof value !== "object" || value === null) return null;
const record = value as Record<string, unknown>;
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<string, unknown> | null | undefined): ReplaceBeforeReuseMarker | null {
const value = metadata?.[REPLACE_BEFORE_REUSE_KEY];
if (typeof value !== "object" || value === null) return null;
const marker = value as Record<string, unknown>;
return marker.schema === REPLACE_BEFORE_REUSE_SCHEMA && typeof marker.runId === "string"
? marker as ReplaceBeforeReuseMarker : null;
}
@@ -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<string, unknown>): Pick<RemoteRunnerRecoveryDiagnostic,
@@ -55,12 +57,13 @@ export class RemoteRunnerRecoveryError extends Error {
export function readRemoteRunnerRecoveryDiagnostic(value: unknown): RemoteRunnerRecoveryDiagnostic | null {
if (!value || typeof value !== "object") return null;
try {
const { stage, reason, runnerLifecycle, runnerSettled } = value as Record<string, unknown>;
const { stage, reason, runnerLifecycle, runnerSettled, providerTurnIssued } = value as Record<string, unknown>;
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;
@@ -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");
});
});
+1 -1
View File
@@ -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;
@@ -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<PluginWorkspaceParams, "deadline">;
type WorkspaceWorker = Pick<PluginWorkerManager, "call" | "getWorker">;
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<PluginWorkerManager, "call">, 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");
}
}
+31 -62
View File
@@ -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,
@@ -19,68 +17,30 @@ import {
type WorkspaceProviderBinding,
} from "@paperclipai/shared";
import {
parseWorkspaceProviderResult,
workspaceProviderOperationSchema,
type PluginWorkspaceOperation,
type PluginWorkspaceRecoveryPullRequest,
type PluginWorkspaceParams,
type PluginWorkspaceResult,
type PluginFreshWorkspace,
} from "@paperclipai/plugin-sdk";
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
import { invokeWorkspaceProvider } from "./plugin-workspace-preparation.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 { WorkspaceProviderFailureError, workspaceProviderCallFailure } from "./workspace-provider-failure.js";
import {
assertTaskWorkspaceExecutionAccess,
assertTaskWorkspaceSourceProjectAccess,
} from "./task-workspace-access.js";
import { forbidden, conflict } from "../errors.js";
export type WorkspaceWorkers = Pick<PluginWorkerManager, "call" | "getWorker">;
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 +63,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,12 +83,12 @@ 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 });
}
const params: PluginWorkspaceParams = {
const params: Omit<PluginWorkspaceParams, "deadline"> = {
pluginId,
companyId: workspace.companyId,
projectId: workspace.projectId,
@@ -140,26 +103,21 @@ export async function callWorkspaceProvider(
)
.digest("hex")),
generation: operationGeneration,
deadline: new Date(Date.now() + (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,
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.
await provider(db, workers, workspace.companyId, pluginId);
await requireWorkspaceProviderWorker(db, workers, workspace.companyId, pluginId);
const [fresh] = await db
.select()
.from(executionWorkspaces)
@@ -177,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;
@@ -204,6 +161,7 @@ export async function preparePluginWorkspace(
baseRef?: string | null;
fresh?: PluginFreshWorkspace;
expectedBindingRevision?: number;
verifyExisting?: true;
},
) {
const [previous] = input.existingWorkspaceId
@@ -223,6 +181,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 +236,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 +390,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 +453,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 +629,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 +817,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");
+3 -2
View File
@@ -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,
};
@@ -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<Db, "select">;
export type WorkspaceWorkers = Pick<PluginWorkerManager, "call" | "getWorker">;
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 })
+20 -2
View File
@@ -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,
@@ -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 = {
@@ -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",
@@ -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) });
@@ -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"]);
@@ -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<ReturnType<typeof restartAllocationLostSource>>, 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" })
+178 -3
View File
@@ -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 <writers>` (below), `--budget-cents` (company hard cap,
`--workloads A1,B1,B5,C1` (opt-in: G1, H1, L1, R1, S1, W2, W2Q, W2C), `--db-pressure <writers>` (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 <n>` 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 <dir>`
@@ -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<N>` 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 <n>` or `<min>-<max>`** (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
@@ -461,6 +492,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/<wave>-ep/`.
## Config faults (CF1–CF3, `config-wave.ts`)
```sh
@@ -535,11 +590,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.
@@ -913,6 +969,121 @@ 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 <image@sha256:…> --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.
## 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 <step>[:<nth>]` 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=<n>`), 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 <n>` (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 <i> <start> <end>` 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
@@ -1430,6 +1601,10 @@ and grades only (no server logs).
4. Run the point: `node scripts/crash-points.mjs --points <name>`. A
`not_reached` result means the workload never crosses it.
**Fail mode.** A control-file line may end in `fail` (`<token> <name>:<nth> fail`): the nth hit then
throws once instead of killing the server. An optional `pid=<n>` binds the line to one server process. A call site can name the error its real step throws
(`crashPoint("<name>", { 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`.
+24 -6
View File
@@ -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<AdapterId>(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<FaultKind | ProviderFaultKind | DiskFullFaultKind | SessionFaultKind>(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<FaultKind | ProviderFaultKind | DiskFullFaultKind | SessionFaultKind | "K0">(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<WorkloadId>(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<TriggerId>(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");
@@ -282,6 +296,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.
@@ -291,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 <older checkout> go together: pass both or neither");
+38
View File
@@ -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<void>;
}
export async function startEdgeProxy(port: number, target: number): Promise<EdgeProxy> {
const sockets = new Set<net.Socket>();
const proxy: EdgeProxy = { port, target, close: async () => {
for (const socket of sockets) socket.destroy();
await new Promise<void>(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<void>((resolve, reject) => {
server.once("error", reject);
server.listen(port, "127.0.0.1", () => { server.off("error", reject); resolve(); });
});
return proxy;
}
@@ -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>): 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);
});
});
+106
View File
@@ -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<EnvProviderFaultKind, EnvProviderFault> = {
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 };
}
+205
View File
@@ -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<string, any>;
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<Json>(`/api/issues/${record.issueId}`, 5_000),
api.get<Json[]>(`/api/issues/${record.issueId}/runs`, 5_000),
// A failed read is recorded, never taken as "no actions": the grade needs this evidence.
api.get<Json>(`/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<Array<{ record: EpTaskRecord; grade: EpGrade }>> {
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<Json>(`/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<Json>(`/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<Json>(`/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<number> {
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; }));
}
+1
View File
@@ -36,6 +36,7 @@ export type JourneyTrigger = (typeof JOURNEY_TRIGGERS)[number];
export const WORKLOAD_TRIGGERS: Record<WorkloadId, readonly TriggerId[]> = {
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. */
+100
View File
@@ -0,0 +1,100 @@
/**
* `--long-turn-minutes <n>` (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 <i> <start> <end>` 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 <N> 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 <N> ")}\``,
`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<OracleArtifacts, "documents" | "runs">): 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 };
},
};
}
+16 -1
View File
@@ -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";
@@ -50,6 +51,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, "../..");
@@ -243,6 +245,14 @@ async function main(): Promise<number> {
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"),
@@ -354,6 +364,7 @@ async function main(): Promise<number> {
}
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);
@@ -702,8 +713,12 @@ async function main(): Promise<number> {
}
// 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;
+16 -3
View File
@@ -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;
}
@@ -855,11 +859,16 @@ 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) } : {}) });
}
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 }) });
}
}
@@ -1038,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<Json[]>(`/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()) } : {}),
};
}
+30 -1
View File
@@ -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");
});
});
});
+31 -4
View File
@@ -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<string, any>;
@@ -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<string, string>;
}
@@ -214,10 +216,14 @@ export async function collectQuestionArtifacts(api: Pick<ChaosApi, "get">, 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<string, string | null>();
const sandboxes = new Map<string, { failureCause: string | null; providerLeaseId: string | null }>();
if (question.rotation) for (const run of runs ?? []) {
const id = String(run.runId ?? run.id);
const detail = await api.get<Json>(`/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<ChaosApi, "get">, 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}` },
];
@@ -0,0 +1,90 @@
/**
* `--fail-recovery-step <step>[:<nth>]`: 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<string, CrashPointName> = {
// 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 <step>[:<nth>], 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: "<name>:<nth> 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" };
}
+46 -3
View File
@@ -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 <n>` or `<min>-<max>`: 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 <seconds> or <min>-<max> 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<string, string> {
export function redeployEnvironment(identity: RedeployIdentity, volumeMountPath: string | null): Record<string, string> {
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];
+293
View File
@@ -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<string, any>;
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<TaskPlan, "workload" | "nonce">): 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, "<CODENAME>")}\` exactly, on its own line, with <CODENAME> 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<TaskPlan, "workload" | "nonce">): 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<ChaosApi, "get" | "post" | "patch">;
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<string, unknown>) => void;
}
/** Board step of W2, W2Q and W2C, called on every poll. */
export async function rewakeStep(input: RewakeStepInput): Promise<void> {
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<RewakeRecord["configChange"]> = { 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<RewakeRecord["sent"]> = { at: now, kind: rewake.kind, statusAtWake: sample.issueStatus ?? null, httpStatus: null, error: null };
try {
if (rewake.kind === "comment") {
const comment = await input.api.post<Json>(`/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<ChaosApi, "get">, issueId: string, record: TaskRecord): Promise<RewakeArtifacts> {
const runs = await api.get<Json[]>(`/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<TaskPlan, "workload" | "nonce">, 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<RewakeWorkload, WorkloadDefinition> = {
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),
};
+7 -5
View File
@@ -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<WaveOptions, "faults" | "stormMinutes" | "providerFaults" | "diskFullFaults" | "sessionFaults">, trigger: TriggerId): readonly TaskFaultKind[] {
if (!options.stormMinutes) return [...options.faults, ...(options.providerFaults ?? []), ...(options.diskFullFaults ?? []), ...(options.sessionFaults ?? [])];
function stormCellFaults(options: Pick<WaveOptions, "faults" | "stormMinutes" | "providerFaults" | "diskFullFaults" | "sessionFaults" | "baseline">, 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<WaveOptions, "seed" | "tasks" | "workloads" | "adapters" | "faults" | "triggers" | "stormMinutes" | "k4HoldMaxMs" | "k15HoldMs" | "tm1HoldMs" | "faultAfterMs" | "providerFaults" | "diskFullFaults" | "sessionFaults" | "rrGapMs">): TaskPlan[] {
export function planTasks(options: Pick<WaveOptions, "seed" | "tasks" | "workloads" | "adapters" | "faults" | "triggers" | "stormMinutes" | "k4HoldMaxMs" | "k15HoldMs" | "tm1HoldMs" | "faultAfterMs" | "providerFaults" | "diskFullFaults" | "sessionFaults" | "rrGapMs" | "baseline">): 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<WaveOptions, "seed" | "tasks" | "workloa
index,
...cellRest,
...(trigger === "time" ? {} : { trigger, triggerDelayMs: rng.int(...TRIGGER_DELAY_RANGE_MS[trigger]) }),
fireAfterMs: cell.fault === "K13" ? 0 : pinnedFireAfterMs(options.faultAfterMs, rng.int(fireMin, fireMax)),
fireAfterMs: cell.fault === "K13" || cell.fault === "K0" ? 0 : pinnedFireAfterMs(options.faultAfterMs, rng.int(fireMin, fireMax)),
holdMs: cell.fault === "K4" ? rng.int(...k4HoldRange(options.k4HoldMaxMs)) : isTimeFault(cell.fault) ? timeFaultHoldMs(cell.fault, rng.int, options.tm1HoldMs)
: isMultiServerFault(cell.fault) ? multiServerHoldMs(cell.fault, rng.int)
: cell.fault === "K15" ? k15HoldMs(options.k15HoldMs, rng.int) : 0,
@@ -154,7 +154,9 @@ function replayMasks(source: readonly string[] | undefined, added: readonly stri
export function planWave(waveId: string, options: WaveOptions, createdAt = new Date()): WavePlan {
return { schema: "paperclip.restart-chaos.wave-plan/v1", waveId, seed: options.seed,
createdAt: createdAt.toISOString(), options, tasks: withProviderFaultRules(planTasks(options), options),
createdAt: createdAt.toISOString(), options, tasks: withProviderFaultRules(planTasks(options), options)
// `--long-turn-minutes` is part of each task's plan, so a replay keeps it.
.map(task => options.longTurnMinutes ? { ...task, longTurnMinutes: options.longTurnMinutes } : task),
...(options.stormMinutes ? { storm: planStorm(options.seed, options.stormMinutes, options.faults, options.k4HoldMaxMs, options.k15HoldMs) } : {}) };
}
+21 -3
View File
@@ -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<string, string> {
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<ChaosApi, "patch">, agentId: string, taskIndex: number, now: number): Promise<SessionRotation> {
export async function rotateAgentSession(api: Pick<ChaosApi, "patch">, agentId: string, taskIndex: number, now: number,
fault: SessionFaultKind = "SR1"): Promise<SessionRotation> {
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;
+252
View File
@@ -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<TaskPlan>) {
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<T>(route: string) { return (route.endsWith("/interactions") ? interactions : []) as T; },
async post<T>(route: string, body?: unknown) { calls.push({ method: "post", route, body }); return { id: "c1" } as T; },
async patch<T>(route: string, body?: unknown) { calls.push({ method: "patch", route, body }); return {} as T; },
};
let interactions: Array<Record<string, unknown>> = [];
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<Record<string, unknown>>) => { 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> = {}): 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> = {}): 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<net.Server>(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<string>((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<void>(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();
}
});
});
+3 -2
View File
@@ -24,10 +24,11 @@ export function unexercisedFaults(kinds: readonly string[], injectedBy: Record<s
const hit = (prefixes: readonly string[]) => 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 {
+3 -1
View File
@@ -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) }];
}
}
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff. Show more