mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - OpenCode agents in remote sandboxes must have a saved, verified copy of their launch files before their first turn (#19622, #21287) > - The first runs of a company share one copy of these files per server. Other runs wait for it > - In a restart chaos wave, the shared copy out of one sandbox stalled for 330 s. Seven other runs waited silently for it. Two runs then failed before their first turn with the cause `unknown` > - The copy speed out of a sandbox differs from one sandbox to the next. When the first copy failed, the other sandboxes copied the same 314 MB in 15 to 24 s > - This pull request lets every waiting run use the first copy that any run saves, starts a second copy when the first one is slow, and names the cause of a stalled copy > - The benefit is a shorter cold start for the first runs of a company, no failed run when another run already saved the files, and a named cause instead of `unknown` ## Linked Issues or Issue Description Refs #19622 Refs #21287 **What happened?** A restart chaos wave started 15 OpenCode runs on new Daytona sandboxes (1 vCPU) in a new company. The first run (A) started the shared copy of the 314 MB launch files out of its sandbox. The copy did not finish. The plugin call timed out after 330 s, and run A failed before its first turn. The other runs waited for that copy without any run event, so the task looked dead for 284 to 343 s. When run A failed, every waiting run started its own copy at the same time. Five copies finished in 15 to 24 s. One copy (run B) stalled again and failed after 330 s, although a saved copy existed after 15 s. One copy (run C) took 5 min and started its turn 10 min after the run started, although it could have used the saved copy 5 min earlier. Both failures had the technical cause `unknown`. Each failure also logged "native result could not be marked workspace_failed; the reconciliation loop will retry persisted results", but the run had no result, so there was nothing to retry. **Expected behavior** A run uses the first saved copy as soon as one exists. A slow copy does not hold all first runs. A stalled copy out of the sandbox has a named cause. A run with no result does not log a result-finalization failure. **Steps to reproduce** 1. Use a company with remote OpenCode agents on Daytona sandboxes with durable storage and no saved launch-file copy. 2. Start 8 or more runs together on new sandboxes. 3. Make the copy out of the first sandbox stall (for example, a slow sandbox link). 4. See that all other runs wait for the full plugin timeout, and see the failures with the cause `unknown`. **Agent adapter(s) involved** OpenCode (native runtime, remote sandbox). ## What Changed - `shareNativeProviderArtifactCapture` (`native-provider-artifact-capture.ts`): - The first capture that saves a ready copy ends the wait for every run. A run whose own capture is still copying uses the saved copy and aborts its own copy. - A run whose own capture fails uses a saved copy when one exists, and fails only when none exists. - When the running capture is slower than 90 s, one waiting run starts one more capture from its own sandbox. At most two captures run at once. A capture keeps its slot until its copy out of the sandbox ends. - The start decision is owned by one `SharedArtifactCapture` coordinator (`tryStart()` returns a release lease). - When the shared capture fails, one waiting run starts the next capture. The other runs keep waiting for it. Before, every waiting run started its own copy at the same time. - The capture callback now gets its own abort signal, so a superseded copy stops before upload. - A failed copy out of the sandbox is now `NativeProviderArtifactExportError` with the code `native_provider_artifacts_export_timeout` (plugin call timed out) or `native_provider_artifacts_export_failed`. The run's technical cause shows this code instead of `unknown`. A timeout shows "Setting up the computer took too long ...". - `runtime-execution.ts`: do not try to mark the workspace as failed on a native result when the run has no result. Before, this always threw `native_finalization_missing` and logged a false "will retry" warning. - `doc/opencode-cold-recovery.md`: describe the new sharing, the second capture and the new cause codes. ## Verification - Red/green: with the old `native-provider-artifact-capture.ts`, these 5 new tests fail. With this change, they pass: - `native-provider-artifact-gate.test.ts`: "starts a run's turn from another run's saved artifact while its own capture is still copying", "uses a saved artifact when the run's own capture fails after another run saved one", "starts one more capture when the shared capture runs past the hedge delay, not one per waiting run", "does not start a capture per waiting run when the shared capture fails", "names a stalled copy out of the sandbox instead of an unknown cause". - Red/green: `heartbeat-native-predispatch-retry.test.ts` "continues on a fresh ... sandbox when the provider artifacts fail to save before any turn" now also asserts that no "could not be marked workspace_failed" warning is logged. It fails before the `runtime-execution.ts` change and passes after it. - `cd server && npx vitest run src/services/native-runtime/native-provider-artifact-gate.test.ts src/services/native-runtime/native-provider-artifact-capture-confinement.test.ts src/services/native-runtime/native-session-executor.test.ts src/services/native-runtime/native-harness-backup-storage.integration.test.ts src/services/native-runtime/native-provider-artifact-capture.test.ts src/services/heartbeat/runtime-execution.test.ts src/services/task-interruption-presentation.test.ts src/__tests__/heartbeat-native-predispatch-retry.test.ts`: all pass. - `npx tsc --noEmit -p server`: pass. ## Risks - A slow first capture can now cause one more 314 MB copy after 90 s. At most two copies run at once for one company and manifest. A run whose saved copy cannot be reused (for example, an ownership fence mismatch) starts its own copy at once. Before, a failed burst started one copy per waiting run at once, which was more. - A superseded copy never uploads, but the provider call that copies files out of the sandbox continues until it ends or times out. Its local temporary directory is removed when it ends. - Sharing is still per server. Two servers can still copy the same files. - No change to the rule from #19622: a verified saved copy still exists before the first turn. - No runner or image change. No migration. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude (Anthropic), model ID `claude-opus-5-5`, used through Claude Code with tool use (shell, file edit, test runs). Default context window; extended reasoning on. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
526 lines
37 KiB
TypeScript
526 lines
37 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import { and, eq, inArray } from "drizzle-orm";
|
|
import { activityLog, agents, authUsers, companyMemberships, createDb, environmentLeases, environments, heartbeatRuns, issueComments,
|
|
issueRecoveryActions, issueRelations, issues } from "@paperclipai/db";
|
|
import { NativePredecessorRetirementUnprovenError } from "../services/native-runtime/predecessor-retirement.js";
|
|
import { NativeProviderArtifactTransferTimeoutError } from "../services/native-runtime/native-provider-artifacts.js";
|
|
import { taskInterruptionPresentation } from "../services/task-interruption-presentation.js";
|
|
import type { NativeRunIdentity, NativeSession, NativeSessionBackend, PrpEvent } from "@paperclipai/paperclip-runner";
|
|
import type { ExecutionContinuationEnvelope } from "@paperclipai/shared";
|
|
import { renderPaperclipWakePrompt } from "@paperclipai/adapter-utils/server-utils";
|
|
import { describe, expect, it, vi } from "vitest";
|
|
import { logger } from "../middleware/logger.js";
|
|
import { heartbeatService, type HeartbeatServiceOptions } from "../services/heartbeat.js";
|
|
import { instanceSettingsService } from "../services/instance-settings.js";
|
|
import { closeIdleWarmNativeSessionsForRestart, scopedRunnerdStateRoot } from "../services/native-runtime/native-session-executor.js";
|
|
import { nativeRestartFixture, waitForCondition } from "./helpers/native-restart-fixture.js";
|
|
import { getRecoveryPostgresSupport } from "./helpers/recovery-postgres-fixture.js";
|
|
|
|
// Budget admission is the last database write before the dispatch gate enters
|
|
// the native executor. Exhausted serialization retries there fail the run with
|
|
// no provider work started.
|
|
const admissionFaults = vi.hoisted(() => ({ remaining: 0 }));
|
|
vi.mock("../services/budget-reservations.js", async importOriginal => {
|
|
const actual = await importOriginal<typeof import("../services/budget-reservations.js")>();
|
|
const { AccountingContentionError } = await import("../services/accounting-transaction.js");
|
|
return {
|
|
...actual,
|
|
reserveRunBudget: async (...args: Parameters<typeof actual.reserveRunBudget>) => {
|
|
if (admissionFaults.remaining > 0) {
|
|
admissionFaults.remaining -= 1;
|
|
throw new AccountingContentionError(Object.assign(new Error("could not serialize access due to concurrent update"),
|
|
{ name: "PostgresError", code: "40001" }), 4);
|
|
}
|
|
return actual.reserveRunBudget(...args);
|
|
},
|
|
};
|
|
});
|
|
|
|
const support = await getRecoveryPostgresSupport({});
|
|
|
|
type AdmissionFailure = { remaining: number; turnNeverIssued: boolean; environmentId: string; provider: string;
|
|
providerLeaseId: string; leasePolicy: "reuse_by_environment" | "reuse_by_execution_workspace"; failedRuns: string[];
|
|
sessionRoots: string[] };
|
|
|
|
function nativeBackend(db: ReturnType<typeof createDb>, options: { failDescriptorOnce?: { failed: boolean };
|
|
unretiredPredecessorOnce?: { failed: boolean; environmentId: string; taskBlocked?: boolean; repeat?: string[] }; turnMessages?: Map<string, string>;
|
|
admissionFailure?: AdmissionFailure } = {}):
|
|
NonNullable<HeartbeatServiceOptions["nativeSessionBackendFactory"]> {
|
|
return execution => {
|
|
let identity: NativeRunIdentity;
|
|
let sourceInstanceId = "";
|
|
let turn = Promise.withResolvers<string>();
|
|
const capabilities = { resume: true, typedEvents: true, steering: false, interruption: true, structuredResult: true };
|
|
const session: NativeSession = {
|
|
identity: () => identity,
|
|
capabilities: async () => capabilities,
|
|
attachRun: async input => { identity = input.identity; },
|
|
startTurn: async input => {
|
|
options.turnMessages?.set(identity.runId, JSON.stringify(input.message));
|
|
const turnId = randomUUID();
|
|
turn.resolve(turnId);
|
|
return { turnId };
|
|
},
|
|
async *events() {
|
|
const turnId = await turn.promise;
|
|
const event = (sourceSeq: number, eventType: PrpEvent["eventType"], payload: Record<string, unknown>): PrpEvent => ({
|
|
schema: "paperclip.prp.event.v1", sourceKind: "runner", sourceInstanceId,
|
|
sourceEventId: `${sourceInstanceId}:${identity.runId}:${sourceSeq}`, sourceSeq,
|
|
runId: identity.runId, normalizedSessionId: identity.sessionId, turnId,
|
|
schemaVersion: 1, priority: 0, emittedAt: new Date().toISOString(), eventType, payload,
|
|
});
|
|
yield event(1, "turn.started", {});
|
|
yield event(2, "item.completed", { kind: "agentMessage", channel: "final", text: "Done." });
|
|
turn = Promise.withResolvers<string>();
|
|
yield event(3, "turn.completed", { status: "completed" });
|
|
},
|
|
result: async () => null,
|
|
snapshot: async () => ({ backendKind: "mock", sessionId: "predispatch-session", identity,
|
|
providerSessionId: "predispatch-provider-session", cursor: null, activeTurnId: null, pendingRuntimeRequests: [], lineage: [] }),
|
|
close: async () => {},
|
|
};
|
|
const backend: NativeSessionBackend = {
|
|
descriptor: async () => {
|
|
if (options.failDescriptorOnce && !options.failDescriptorOnce.failed) {
|
|
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 || unretired.repeat)) {
|
|
unretired.repeat?.push(execution.binding.runId);
|
|
// 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;
|
|
if (unretired.taskBlocked) await db.update(issues).set({ status: "blocked" }).where(eq(issues.id, execution.binding.issueId));
|
|
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");
|
|
sourceInstanceId = run.runnerInstanceId;
|
|
return { kind: "mock", name: "native-predispatch-retry", version: "1", capabilities,
|
|
runtimeContextCapabilities: { instructions: "native", skills: "native", mcp: "native" } };
|
|
},
|
|
openSession: async input => { identity = input.identity; return session; },
|
|
recoverSession: async snapshot => { identity = snapshot.identity; return { recovered: true, session }; },
|
|
};
|
|
const failure = options.admissionFailure;
|
|
if (!failure) return backend;
|
|
return Object.assign(backend, {
|
|
providerTurnNeverIssued: () => failure.turnNeverIssued,
|
|
providerAdmissionPersisted: async () => {
|
|
if (failure.remaining <= 0) return;
|
|
failure.remaining -= 1;
|
|
const runId = execution.binding.runId;
|
|
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
await db.insert(environmentLeases).values({ companyId: run!.companyId, environmentId: failure.environmentId,
|
|
issueId: execution.binding.issueId, heartbeatRunId: runId, provider: failure.provider,
|
|
providerLeaseId: `${failure.providerLeaseId}-${failure.failedRuns.length}`, leasePolicy: failure.leasePolicy,
|
|
status: "active", metadata: { remoteCwd: "/workspace" } });
|
|
failure.failedRuns.push(runId);
|
|
const root = scopedRunnerdStateRoot(execution);
|
|
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
writeFileSync(join(root, "failed-attempt"), runId);
|
|
failure.sessionRoots.push(root);
|
|
throw new NativeProviderArtifactTransferTimeoutError("upload", 120_000, 512 * 1024 * 1024);
|
|
},
|
|
});
|
|
};
|
|
}
|
|
|
|
describe.skipIf(!support.supported)("heartbeat native pre-dispatch failure retry", () => {
|
|
const fixture = nativeRestartFixture({});
|
|
|
|
async function startTask(db: ReturnType<typeof createDb>, heartbeat: ReturnType<typeof heartbeatService>,
|
|
status: "in_progress" | "blocked" = "in_progress") {
|
|
const { companyId, agentId } = fixture.current;
|
|
const userId = randomUUID();
|
|
await db.insert(authUsers).values({ id: userId, name: "Task owner", email: `${userId}@example.invalid`,
|
|
createdAt: new Date(), updatedAt: new Date() });
|
|
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: userId, membershipRole: "owner" });
|
|
await db.update(agents).set({ status: "idle", adapterConfig: { provider: "codex" } }).where(eq(agents.id, agentId));
|
|
await instanceSettingsService(db).updateExperimental({ enableAgentChat: true, enableNativeRunner: true });
|
|
const [issue] = await db.insert(issues).values({ companyId, title: "Survive a database fault", status,
|
|
assigneeAgentId: agentId, responsibleUserId: userId, conversationAgentId: agentId, conversationUserId: userId,
|
|
conversationState: "active" }).returning();
|
|
if (status === "blocked") {
|
|
const [blocker] = await db.insert(issues).values({ companyId, title: "Open subtask", status: "todo" }).returning();
|
|
await db.insert(issueRelations).values({ companyId, issueId: blocker!.id, relatedIssueId: issue!.id, type: "blocks" });
|
|
}
|
|
const [message] = await db.insert(issueComments).values({ companyId, issueId: issue!.id,
|
|
authorType: "user", authorUserId: userId, body: "Start." }).returning();
|
|
const run = await heartbeat.wakeup(agentId, { source: "on_demand", triggerDetail: "manual", reason: "issue_commented",
|
|
requestedByActorType: "user", requestedByActorId: userId, manualUserWake: true,
|
|
payload: { issueId: issue!.id, commentId: message!.id },
|
|
contextSnapshot: { issueId: issue!.id, taskKey: issue!.id, wakeCommentId: message!.id } });
|
|
expect(run).not.toBeNull();
|
|
await waitForCondition("the first run to settle", () => heartbeat.getTaskDrainStatus().quiescent);
|
|
return { issueId: issue!.id, runId: run!.id };
|
|
}
|
|
|
|
it("re-queues a native run that failed at budget admission and completes it without a Retry", async () => {
|
|
const { companyId } = fixture.current;
|
|
const db = createDb(fixture.current.temporary.connectionString, { maxConnections: 4 });
|
|
const heartbeat = heartbeatService(db, { nativeSessionBackendFactory: nativeBackend(db) });
|
|
try {
|
|
admissionFaults.remaining = 1;
|
|
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: "40001",
|
|
nativePreDispatchFailure: { version: 1, providerWorkStarted: false } }) });
|
|
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);
|
|
|
|
// The first attempt is due at once; the scheduler promotes it and the
|
|
// queue starts it, exactly once.
|
|
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(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId),
|
|
eq(heartbeatRuns.retryOfRunId, runId)))).toHaveLength(1);
|
|
expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId))).toHaveLength(0);
|
|
} finally {
|
|
admissionFaults.remaining = 0;
|
|
await heartbeat.drainActiveRunExecutions();
|
|
await closeIdleWarmNativeSessionsForRestart();
|
|
await db.$client.end();
|
|
}
|
|
}, 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("stops retrying with a truthful failure when the next attempt met the same unretired sandbox instead of a fresh one", 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 attempts: string[] = [];
|
|
const heartbeat = heartbeatService(db, { nativeSessionBackendFactory: nativeBackend(db,
|
|
{ unretiredPredecessorOnce: { failed: false, environmentId: environment!.id, repeat: attempts } }) });
|
|
try {
|
|
const { issueId, runId } = await startTask(db, heartbeat);
|
|
const [first] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId),
|
|
eq(heartbeatRuns.retryOfRunId, runId)));
|
|
expect(first).toMatchObject({ scheduledRetryReason: "interrupted_preparation", scheduledRetryAttempt: 1 });
|
|
expect(await heartbeat.promoteDueScheduledRetries()).toMatchObject({ promoted: 1 });
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForCondition("the second attempt to end", async () =>
|
|
(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, first!.id)))[0]?.status === "failed");
|
|
await waitForCondition("the second attempt to settle", () => heartbeat.getTaskDrainStatus().quiescent);
|
|
expect(attempts).toEqual([runId, first!.id]);
|
|
const [second] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, first!.id));
|
|
expect(second?.resultJson ?? {}).not.toHaveProperty("predecessorRetirementFallback");
|
|
expect(second?.error ?? "").not.toMatch(/fresh sandbox/i);
|
|
expect(await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId),
|
|
eq(heartbeatRuns.retryOfRunId, first!.id)))).toHaveLength(0);
|
|
expect(await heartbeat.promoteDueScheduledRetries()).toMatchObject({ promoted: 0 });
|
|
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
expect(await taskInterruptionPresentation(db, issue!)).toMatchObject({ canRetry: true });
|
|
} finally {
|
|
await heartbeat.drainActiveRunExecutions();
|
|
await closeIdleWarmNativeSessionsForRestart();
|
|
await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date() }).where(and(
|
|
eq(heartbeatRuns.companyId, companyId), inArray(heartbeatRuns.status, ["queued", "scheduled_retry"])));
|
|
await db.$client.end();
|
|
}
|
|
}, 90_000);
|
|
|
|
it.each([
|
|
{ title: "continues a follow-up on a blocked task whose predecessor could not be retired", blockedAfter: false },
|
|
{ title: "does not continue a task that was blocked only after its run failed", blockedAfter: true },
|
|
])("$title", async ({ blockedAfter }) => {
|
|
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, taskBlocked: !blockedAfter } }) });
|
|
try {
|
|
const { issueId, runId } = await startTask(db, heartbeat, blockedAfter ? "in_progress" : "blocked");
|
|
const [failed] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(failed).toMatchObject({ status: "failed", resultJson: expect.objectContaining({
|
|
failureCause: "native_predecessor_retirement_unproven",
|
|
predecessorRetirementFallback: expect.objectContaining({ issueStatusAtFailure: blockedAfter ? "in_progress" : "blocked" }) }) });
|
|
if (blockedAfter) await db.update(issues).set({ status: "blocked" }).where(eq(issues.id, issueId));
|
|
const [task] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
expect(task?.status).toBe("blocked");
|
|
const successors = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId),
|
|
eq(heartbeatRuns.retryOfRunId, runId)));
|
|
expect(successors).toEqual([expect.objectContaining({ status: "scheduled_retry", scheduledRetryReason: "interrupted_preparation" })]);
|
|
expect(await taskInterruptionPresentation(db, task!)).toMatchObject({ state: "working", canRetry: false });
|
|
if (blockedAfter) {
|
|
await heartbeat.promoteDueScheduledRetries();
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForCondition("the stale retry to settle", () => heartbeat.getTaskDrainStatus().quiescent);
|
|
const [stale] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, successors[0]!.id));
|
|
expect(["cancelled", "scheduled_retry"]).toContain(stale?.status);
|
|
return;
|
|
}
|
|
expect(await heartbeat.promoteDueScheduledRetries()).toMatchObject({ promoted: 1 });
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForCondition("the retry to settle", () => heartbeat.getTaskDrainStatus().quiescent);
|
|
const [retried] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, successors[0]!.id));
|
|
expect({ status: retried?.status, errorCode: retried?.errorCode, error: retried?.error }).toEqual({ status: "succeeded", errorCode: null, error: null });
|
|
} finally {
|
|
await heartbeat.drainActiveRunExecutions();
|
|
await closeIdleWarmNativeSessionsForRestart();
|
|
await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date() }).where(and(
|
|
eq(heartbeatRuns.companyId, companyId), inArray(heartbeatRuns.status, ["queued", "scheduled_retry"])));
|
|
await db.$client.end();
|
|
}
|
|
}, 90_000);
|
|
|
|
it("delivers the monitor check to the automatic retry of a monitor run that failed before provider work", async () => {
|
|
const { companyId, agentId } = 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 turnMessages = new Map<string, string>();
|
|
const heartbeat = heartbeatService(db, { nativeSessionBackendFactory: nativeBackend(db,
|
|
{ unretiredPredecessorOnce: { failed: false, environmentId: environment!.id }, turnMessages }) });
|
|
try {
|
|
await db.update(agents).set({ status: "idle", adapterConfig: { provider: "codex" } }).where(eq(agents.id, agentId));
|
|
await instanceSettingsService(db).updateExperimental({ enableNativeRunner: true });
|
|
const userId = randomUUID();
|
|
await db.insert(authUsers).values({ id: userId, name: "Task owner", email: `${userId}@example.invalid`,
|
|
createdAt: new Date(), updatedAt: new Date() });
|
|
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: userId, membershipRole: "owner" });
|
|
const [issue] = await db.insert(issues).values({ companyId, title: "Phase 2 on the monitor check", status: "in_progress",
|
|
assigneeAgentId: agentId, responsibleUserId: userId, monitorNotes: "Phase 2 check" }).returning();
|
|
const run = await heartbeat.wakeup(agentId, { source: "automation", triggerDetail: "system", reason: "issue_monitor_due",
|
|
payload: { issueId: issue!.id }, contextSnapshot: { issueId: issue!.id, taskKey: issue!.id,
|
|
source: "issue.monitor", wakeReason: "issue_monitor_due", monitorNotes: "Phase 2 check" } });
|
|
expect(run).not.toBeNull();
|
|
await waitForCondition("the monitor run to settle", () => heartbeat.getTaskDrainStatus().quiescent);
|
|
const [failed] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run!.id));
|
|
expect(failed).toMatchObject({ status: "failed", resultJson: expect.objectContaining({
|
|
failureCause: "native_predecessor_retirement_unproven" }) });
|
|
const [successor] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId),
|
|
eq(heartbeatRuns.retryOfRunId, run!.id)));
|
|
expect(successor).toMatchObject({ scheduledRetryReason: "interrupted_preparation" });
|
|
|
|
expect(await heartbeat.promoteDueScheduledRetries()).toMatchObject({ promoted: 1 });
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForCondition("the retry to start its provider turn", () => turnMessages.has(successor!.id));
|
|
await waitForCondition("the retry to settle", () => heartbeat.getTaskDrainStatus().quiescent);
|
|
const [retried] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, successor!.id));
|
|
const continuation = retried!.contextSnapshot?.executionContinuation as ExecutionContinuationEnvelope;
|
|
expect(continuation.trigger).toMatchObject({ sourceRunId: run!.id, retriedReason: "issue_monitor_due" });
|
|
expect(renderPaperclipWakePrompt(retried!.contextSnapshot?.paperclipWake)).toContain("- retried wake: issue_monitor_due");
|
|
expect(turnMessages.get(successor!.id)).toContain("- retried wake: issue_monitor_due");
|
|
expect(turnMessages.has(run!.id)).toBe(false);
|
|
} finally {
|
|
await heartbeat.drainActiveRunExecutions();
|
|
await closeIdleWarmNativeSessionsForRestart();
|
|
await db.$client.end();
|
|
}
|
|
}, 90_000);
|
|
|
|
it.each([
|
|
{ target: "remote sandbox", provider: "e2b", leasePolicy: "reuse_by_execution_workspace" as const },
|
|
{ target: "plugin-task sandbox", provider: "daytona", leasePolicy: "reuse_by_environment" as const },
|
|
])("continues on a fresh $target when the provider artifacts fail to save before any turn", async ({ provider, leasePolicy }) => {
|
|
const { companyId } = fixture.current;
|
|
const db = createDb(fixture.current.temporary.connectionString, { maxConnections: 4 });
|
|
const [environment] = await db.insert(environments).values({ name: `capture-${randomUUID()}`, driver: "sandbox" }).returning();
|
|
const turnMessages = new Map<string, string>();
|
|
const failure: AdmissionFailure = { remaining: 1, turnNeverIssued: true, environmentId: environment!.id, provider,
|
|
providerLeaseId: `sandbox-${provider}`, leasePolicy, failedRuns: [], sessionRoots: [] };
|
|
const heartbeat = heartbeatService(db, { nativeSessionBackendFactory: nativeBackend(db, { admissionFailure: failure, turnMessages }) });
|
|
const warn = vi.spyOn(logger, "warn");
|
|
try {
|
|
const { issueId, runId } = await startTask(db, heartbeat);
|
|
expect(failure.failedRuns).toEqual([runId]);
|
|
expect(warn.mock.calls.filter(([, message]) => typeof message === "string" && message.includes("could not be marked workspace_failed")))
|
|
.toEqual([]);
|
|
expect(turnMessages.has(runId)).toBe(false);
|
|
expect(existsSync(failure.sessionRoots[0]!)).toBe(false);
|
|
const [failed] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(failed).toMatchObject({ status: "failed", runtimeMode: "native",
|
|
resultJson: expect.objectContaining({ failureCause: "native_failed_before_provider_turn",
|
|
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
|
predecessorRetirementFallback: expect.objectContaining({ version: 1, providerWorkStarted: false,
|
|
predecessorRunId: null, replacedProviderLeaseIds: [`sandbox-${provider}-0`] }) }) });
|
|
expect(failed!.error).toBe("Setting up the computer took too long, so the task is continuing on a fresh one.");
|
|
expect(failed!.error).not.toMatch(/[a-z0-9]+_[a-z0-9_]+|\d|\(|\)/i);
|
|
expect(failed!.runnerProfileJson).toMatchObject({ failedBeforeProviderTurn: {
|
|
cause: "native_failed_before_provider_turn", technicalCause: "native_provider_artifacts_transfer_timeout" } });
|
|
const [lease] = await db.select().from(environmentLeases).where(and(eq(environmentLeases.heartbeatRunId, runId),
|
|
eq(environmentLeases.providerLeaseId, `sandbox-${provider}-0`)));
|
|
expect(lease?.metadata).toMatchObject({ replaceBeforeReuse: { schema: "paperclip.replace-before-reuse.v1", runId } });
|
|
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 });
|
|
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
expect(issue!.status).not.toBe("blocked");
|
|
expect(await taskInterruptionPresentation(db, issue!)).toMatchObject({ state: "working", canRetry: false });
|
|
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 continuation to succeed", async () =>
|
|
(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, successors[0]!.id)))[0]?.status === "succeeded");
|
|
await waitForCondition("the continuation to settle", () => heartbeat.getTaskDrainStatus().quiescent);
|
|
expect(turnMessages.has(successors[0]!.id)).toBe(true);
|
|
expect(await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId),
|
|
eq(heartbeatRuns.retryOfRunId, runId)))).toHaveLength(1);
|
|
const [settled] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
expect(await taskInterruptionPresentation(db, settled!)).toMatchObject({ state: "resolved", canRetry: false });
|
|
} finally {
|
|
warn.mockRestore();
|
|
await heartbeat.drainActiveRunExecutions();
|
|
await closeIdleWarmNativeSessionsForRestart();
|
|
await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date() }).where(and(
|
|
eq(heartbeatRuns.companyId, companyId), inArray(heartbeatRuns.status, ["queued", "scheduled_retry"])));
|
|
await db.$client.end();
|
|
}
|
|
}, 90_000);
|
|
|
|
it("keeps today's ambiguous hold when the Runner ledger cannot prove no turn was sent", async () => {
|
|
const { companyId } = fixture.current;
|
|
const db = createDb(fixture.current.temporary.connectionString, { maxConnections: 4 });
|
|
const [environment] = await db.insert(environments).values({ name: `capture-${randomUUID()}`, driver: "sandbox" }).returning();
|
|
const failure: AdmissionFailure = { remaining: 1, turnNeverIssued: false, environmentId: environment!.id, provider: "daytona",
|
|
providerLeaseId: "sandbox-turn-maybe-sent", leasePolicy: "reuse_by_environment", failedRuns: [], sessionRoots: [] };
|
|
const heartbeat = heartbeatService(db, { nativeSessionBackendFactory: nativeBackend(db, { admissionFailure: failure }) });
|
|
try {
|
|
const { runId } = await startTask(db, heartbeat);
|
|
const [failed] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(failed?.status).toBe("failed");
|
|
expect(failed?.resultJson ?? {}).not.toHaveProperty("predecessorRetirementFallback");
|
|
expect(failed?.resultJson?.failureCause).not.toBe("native_failed_before_provider_turn");
|
|
const [lease] = await db.select().from(environmentLeases).where(and(eq(environmentLeases.heartbeatRunId, runId),
|
|
eq(environmentLeases.providerLeaseId, "sandbox-turn-maybe-sent-0")));
|
|
expect(lease?.metadata ?? {}).not.toHaveProperty("replaceBeforeReuse");
|
|
expect(await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId),
|
|
eq(heartbeatRuns.retryOfRunId, runId), eq(heartbeatRuns.scheduledRetryReason, "interrupted_preparation")))).toHaveLength(0);
|
|
} finally {
|
|
await heartbeat.drainActiveRunExecutions();
|
|
await closeIdleWarmNativeSessionsForRestart();
|
|
await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date() }).where(and(
|
|
eq(heartbeatRuns.companyId, companyId), inArray(heartbeatRuns.status, ["queued", "scheduled_retry"])));
|
|
await db.$client.end();
|
|
}
|
|
}, 90_000);
|
|
|
|
it("backs off a lasting pre-turn failure and stops at the shared lane cap without hammering", async () => {
|
|
const { companyId } = fixture.current;
|
|
const db = createDb(fixture.current.temporary.connectionString, { maxConnections: 4 });
|
|
const [environment] = await db.insert(environments).values({ name: `capture-${randomUUID()}`, driver: "sandbox" }).returning();
|
|
const failure: AdmissionFailure = { remaining: Number.POSITIVE_INFINITY, turnNeverIssued: true, environmentId: environment!.id,
|
|
provider: "daytona", providerLeaseId: "sandbox-lasting", leasePolicy: "reuse_by_environment", failedRuns: [], sessionRoots: [] };
|
|
const heartbeat = heartbeatService(db, { nativeSessionBackendFactory: nativeBackend(db, { admissionFailure: failure }) });
|
|
const successorOf = async (runId: string) => (await db.select().from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.retryOfRunId, runId))));
|
|
const runToEnd = async (runId: string) => {
|
|
await heartbeat.resumeQueuedRuns();
|
|
await waitForCondition("the attempt to end", async () =>
|
|
(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]?.status === "failed");
|
|
await waitForCondition("the attempt to settle", () => heartbeat.getTaskDrainStatus().quiescent);
|
|
};
|
|
try {
|
|
const { issueId, runId } = await startTask(db, heartbeat);
|
|
const [first] = await successorOf(runId);
|
|
expect(first).toMatchObject({ scheduledRetryReason: "interrupted_preparation", scheduledRetryAttempt: 1 });
|
|
expect((await heartbeat.promoteDueScheduledRetries()).runIds).toEqual([first!.id]);
|
|
const secondStartedAt = Date.now();
|
|
await runToEnd(first!.id);
|
|
const [second] = await successorOf(first!.id);
|
|
expect(second).toMatchObject({ scheduledRetryReason: "interrupted_preparation", scheduledRetryAttempt: 2 });
|
|
expect(second!.scheduledRetryAt!.getTime() - secondStartedAt).toBeGreaterThanOrEqual(15_000);
|
|
expect((await heartbeat.promoteDueScheduledRetries()).runIds).not.toContain(second!.id);
|
|
expect(failure.failedRuns).toHaveLength(2);
|
|
const [waiting] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
expect(await taskInterruptionPresentation(db, waiting!)).toMatchObject({ state: "working", canRetry: false });
|
|
|
|
await db.update(heartbeatRuns).set({ scheduledRetryAttempt: 12, scheduledRetryAt: new Date(Date.now() - 1_000),
|
|
contextSnapshot: { ...second!.contextSnapshot, executionRetryAccounting: {
|
|
...(second!.contextSnapshot?.executionRetryAccounting as Record<string, unknown>), interruptedPreparations: 12 } } })
|
|
.where(eq(heartbeatRuns.id, second!.id));
|
|
expect((await heartbeat.promoteDueScheduledRetries()).runIds).toEqual([second!.id]);
|
|
await runToEnd(second!.id);
|
|
expect(await successorOf(second!.id)).toHaveLength(0);
|
|
expect(failure.failedRuns).toHaveLength(3);
|
|
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
|
|
expect(await taskInterruptionPresentation(db, issue!)).toMatchObject({ state: "failed", canRetry: true });
|
|
} finally {
|
|
await heartbeat.drainActiveRunExecutions();
|
|
await closeIdleWarmNativeSessionsForRestart();
|
|
await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date() }).where(and(
|
|
eq(heartbeatRuns.companyId, companyId), inArray(heartbeatRuns.status, ["queued", "scheduled_retry"])));
|
|
await db.$client.end();
|
|
}
|
|
}, 120_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 });
|
|
const heartbeat = heartbeatService(db, { nativeSessionBackendFactory: nativeBackend(db, { failDescriptorOnce: { failed: false } }) });
|
|
try {
|
|
const { runId } = await startTask(db, heartbeat);
|
|
const [failed] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
|
expect(failed?.status).toBe("failed");
|
|
expect(failed?.resultJson ?? {}).not.toHaveProperty("nativePreDispatchFailure");
|
|
expect(await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId),
|
|
eq(heartbeatRuns.retryOfRunId, runId), eq(heartbeatRuns.scheduledRetryReason, "interrupted_preparation")))).toHaveLength(0);
|
|
} finally {
|
|
await heartbeat.drainActiveRunExecutions();
|
|
await closeIdleWarmNativeSessionsForRestart();
|
|
await db.$client.end();
|
|
}
|
|
}, 90_000);
|
|
});
|