mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
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:
commit
bec8d35e7c
108 files changed
+4435
-306
No files matched your search
@@ -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();
|
||||
|
||||
@@ -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.";
|
||||
|
||||
@@ -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)}`,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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))
|
||||
|
||||
@@ -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"
|
||||
|
||||
+34
-3
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
@@ -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 })
|
||||
|
||||
@@ -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" })
|
||||
|
||||
Reference in new issue
Block a user