Skip to content

The open-source app everyone uses to manage agents at work

fix(runtime): preserve bounded retries after workspace reconstruction (#16696)

Dotta69ac928d2b06
diff --git a/doc/native-workspace-finalization-recovery.md b/doc/native-workspace-finalization-recovery.md
index 570c221d0e..8ba7717df6 100644
--- a/doc/native-workspace-finalization-recovery.md
+++ b/doc/native-workspace-finalization-recovery.md
@@ -383,3 +383,7 @@ The agent must verify the selected attachments before rebuilding files.
Queued successors recheck their exact reconstruction receipt, sources and current
execution gates when claimed and immediately before provider handoff. A later
human block cannot be overwritten by automatic checkout.
+Bounded retries keep the same reconstruction authority. Dispatch verifies the
+system wake and predecessor chain back to the approved first run. It rechecks
+the saved sources, remaining retry limits and current recovery obligations.
+Unrelated executions and uncertain predecessor outcomes still stop dispatch.
diff --git a/maps/feature-map/workspaces.md b/maps/feature-map/workspaces.md
index b1508f6778..71fd81b538 100644
--- a/maps/feature-map/workspaces.md
+++ b/maps/feature-map/workspaces.md
@@ -22,6 +22,8 @@ For a historical failed export whose exact sandbox was destroyed, the task recov
notice offers **Continue from saved sources** to an authorized board operator.
Select surviving task attachments, record lost work and external action outcomes,
then rebuild through fresh-session admission. The old failed run remains failed.
+Bounded bootstrap retries retain this decision and recheck their system wake,
+predecessors, saved files and current execution gates before provider startup.
Retained sandboxes keep their existing export recovery path. Automated coverage:
[reconstruction](../../server/src/services/native-runtime/native-workspace-reconstruction.test.ts).
Live staging acceptance remains separate from these regression tests.
diff --git a/server/src/services/native-runtime/native-workspace-reconstruction.test.ts b/server/src/services/native-runtime/native-workspace-reconstruction.test.ts
index 52a65d4b78..1c9df21bab 100644
--- a/server/src/services/native-runtime/native-workspace-reconstruction.test.ts
+++ b/server/src/services/native-runtime/native-workspace-reconstruction.test.ts
@@ -178,6 +178,102 @@ describe("reconstruction after confirmed native workspace loss", () => {
expect(dispatch).toHaveBeenCalledTimes(kind === "unchanged" ? 1 : 0);
if (!outcome.dispatched) expect(outcome.cancellation).toMatchObject({ outcome: "cancelled" });
});
+ it.each(["unchanged", "attachment", "blocked", "paused", "forged_wake", "foreign_parent", "unrelated_run", "uncertain_parent", "new_recovery"] as const)("keeps bounded reconstruction retries under current authority: %s", async kind => {
+ const f = await seed();
+ await db.update(heartbeatRuns).set({ scheduledRetryAttempt: 0 }).where(eq(heartbeatRuns.id, f.runId));
+ await reconstructNativeWorkspace(f);
+ await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running" });
+ const heartbeat = heartbeatService(db, { runtimeEnv: {} });
+ await deliverReconciledExecutions(db, heartbeat.wakeup);
+ const [action] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId));
+ const firstId = String(action.evidence.continuationRunId);
+ await db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date(), errorCode: "adapter_failed",
+ resultJson: { errorFamily: "transient_upstream", executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } }).where(eq(heartbeatRuns.id, firstId));
+ await db.update(issues).set({ status: "in_progress", executionRunId: firstId }).where(eq(issues.id, f.issueId));
+ const retry = await heartbeat.scheduleBoundedRetry(firstId, { now: new Date(), random: () => 0, delayMs: 0 });
+ expect(retry.outcome, JSON.stringify(retry)).toBe("scheduled");
+ if (retry.outcome !== "scheduled" || !retry.run) throw new Error("Expected a bounded bootstrap retry");
+ await db.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, retry.run.id));
+ await db.update(issues).set({ executionRunId: retry.run.id }).where(eq(issues.id, f.issueId));
+ if (kind === "attachment") await db.delete(issueAttachments).where(eq(issueAttachments.id, f.attachmentId));
+ if (kind === "blocked") await db.update(issues).set({ status: "blocked" }).where(eq(issues.id, f.issueId));
+ if (kind === "paused") await db.update(agents).set({ status: "paused" }).where(eq(agents.id, f.agentId));
+ if (kind === "forged_wake") await db.update(agentWakeupRequests).set({ requestedByActorType: "agent" }).where(eq(agentWakeupRequests.id, retry.run.wakeupRequestId!));
+ if (kind === "foreign_parent") {
+ const [other] = await db.insert(agents).values({ companyId: f.companyId, name: "Other", adapterType: "paperclip_runner" }).returning();
+ await db.update(heartbeatRuns).set({ agentId: other.id }).where(eq(heartbeatRuns.id, firstId));
+ }
+ if (kind === "unrelated_run") await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId,
+ scopeKind: "issue", issueId: f.issueId, contextSnapshot: { issueId: f.issueId }, status: "succeeded" });
+ if (kind === "uncertain_parent") await db.update(heartbeatRuns).set({ resultJson: {} }).where(eq(heartbeatRuns.id, firstId));
+ if (kind === "new_recovery") await db.insert(issueRecoveryActions).values({ companyId: f.companyId, sourceIssueId: f.issueId,
+ kind: "active_run_watchdog", ownerType: "board", returnOwnerAgentId: f.agentId, cause: "native_continuation_requires_reconciliation",
+ fingerprint: randomUUID(), evidence: { runId: firstId }, nextAction: "Reconcile the new execution", status: "active" });
+ const dispatch = vi.fn(async () => "provider entered");
+ const outcome = await createRunDispatch(db).dispatchResolvedInteractionIfCurrent({ companyId: f.companyId,
+ runId: retry.run.id, expectedStatus: "running", dispatch });
+ expect(outcome.dispatched).toBe(kind === "unchanged");
+ expect(dispatch).toHaveBeenCalledTimes(kind === "unchanged" ? 1 : 0);
+ if (kind === "unchanged") {
+ expect(retry.run.scheduledRetryAttempt).toBe(1);
+ await db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date(), errorCode: "adapter_failed",
+ resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } }).where(eq(heartbeatRuns.id, retry.run.id));
+ const second = await heartbeat.scheduleBoundedRetry(retry.run.id, { now: new Date(), random: () => 0, delayMs: 0 });
+ expect(second.outcome).toBe("scheduled");
+ if (second.outcome !== "scheduled" || !second.run) throw new Error("Expected the second bounded retry");
+ expect(second.run.scheduledRetryAttempt).toBe(2);
+ await db.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, second.run.id));
+ await db.update(issues).set({ executionRunId: second.run.id }).where(eq(issues.id, f.issueId));
+ expect(await createRunDispatch(db).dispatchResolvedInteractionIfCurrent({ companyId: f.companyId,
+ runId: second.run.id, expectedStatus: "running", dispatch })).toMatchObject({ dispatched: true });
+ await db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date(),
+ resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } }).where(eq(heartbeatRuns.id, second.run.id));
+ expect(await heartbeat.scheduleBoundedRetry(second.run.id)).toMatchObject({ outcome: "retry_exhausted" });
+ }
+ });
+ it.each([false, true])("dispatches the assembled bootstrap retry without overwriting a later block: %s", async blockAfterClaim => {
+ const f = await seed();
+ await db.update(agents).set({ adapterType: "codex_local" }).where(eq(agents.id, f.agentId));
+ await db.update(heartbeatRuns).set({ scheduledRetryAttempt: 0 }).where(eq(heartbeatRuns.id, f.runId));
+ await reconstructNativeWorkspace(f);
+ const [busy] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running" }).returning();
+ const heartbeat = runningHeartbeat = heartbeatService(db, { runtimeEnv: { PAPERCLIP_IN_WORKTREE: "false" } });
+ await deliverReconciledExecutions(db, heartbeat.wakeup);
+ const [action] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId));
+ const firstId = String(action.evidence.continuationRunId);
+ await db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date(), errorCode: "adapter_failed",
+ resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } }).where(eq(heartbeatRuns.id, firstId));
+ await db.update(issues).set({ status: "in_progress", executionRunId: firstId }).where(eq(issues.id, f.issueId));
+ const retry = await heartbeat.scheduleBoundedRetry(firstId, { now: new Date(), random: () => 0, delayMs: 0 });
+ if (retry.outcome !== "scheduled" || !retry.run) throw new Error(`Expected a bounded retry: ${JSON.stringify(retry)}`);
+ expect(await createRunDispatch(db).promoteScheduledRetry({ companyId: f.companyId, runId: retry.run.id }))
+ .toMatchObject({ outcome: "promoted" });
+ if (blockAfterClaim) await db.execute(sql.raw(`
+ create function block_retry_after_claim() returns trigger language plpgsql as $$ begin
+ if new.id = '${retry.run.id}' and old.status = 'queued' and new.status = 'running' then
+ update issues set status = 'blocked' where id = '${f.issueId}';
+ end if; return new; end $$;
+ create trigger block_retry_after_claim after update on heartbeat_runs
+ for each row execute function block_retry_after_claim();
+ `));
+ try {
+ await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, busy.id));
+ await heartbeat.resumeQueuedRuns();
+ const deadline = Date.now() + 15000;
+ let current;
+ do {
+ [current] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, retry.run.id));
+ if (["succeeded", "failed", "cancelled"].includes(current.status)) break;
+ await new Promise(resolve => setTimeout(resolve, 25));
+ } while (Date.now() < deadline);
+ expect(providerExecute).toHaveBeenCalledTimes(blockAfterClaim ? 0 : 1);
+ expect(current).toMatchObject({ status: blockAfterClaim ? "cancelled" : "succeeded" });
+ if (blockAfterClaim) expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0].status).toBe("blocked");
+ } finally {
+ if (blockAfterClaim) await db.execute(sql`drop trigger block_retry_after_claim on heartbeat_runs; drop function block_retry_after_claim()`);
+ await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.issueId));
+ }
+ }, 30_000);
it.each([false, true])("runs the assembled heartbeat without overwriting a block after claim: %s", async blockAfterClaim => {
const f = await seed();
await db.update(agents).set({ adapterType: "codex_local" }).where(eq(agents.id, f.agentId));
diff --git a/server/src/services/native-runtime/native-workspace-reconstruction.ts b/server/src/services/native-runtime/native-workspace-reconstruction.ts
index a238dd95b2..e83eb9bd53 100644
--- a/server/src/services/native-runtime/native-workspace-reconstruction.ts
+++ b/server/src/services/native-runtime/native-workspace-reconstruction.ts
@@ -1,11 +1,12 @@
-import { and, eq, gt, inArray, ne, or, sql } from "drizzle-orm";
-import { assets, environmentLeases, heartbeatRuns, issueAttachments, issueRecoveryActions, issues, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db";
+import { and, eq, gt, inArray, ne, notInArray, or, sql } from "drizzle-orm";
+import { agentWakeupRequests, assets, environmentLeases, heartbeatRuns, issueAttachments, issueRecoveryActions, issues, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db";
import { reconstructWorkspaceSchema, type ExecutionReconciliation } from "@paperclipai/shared";
import type { z } from "zod";
import { conflict } from "../../errors.js";
import { persistActivity, publishActivity } from "../activity-log.js";
import { markExecutionReconciliation } from "../execution-recovery-resolution.js";
import { hasRemoteTerminationReceipt } from "../remote-execution-termination.js";
+import { legacyExecutionNeedsReconciliationWithEvidence } from "../legacy-execution-recovery.js";
import { readNativeWorkspaceSyncReference } from "./native-workspace-sync.js";
import { nativeSha256 } from "./canonical.js";
@@ -36,6 +37,8 @@ export function unreconciledNativeExportPredicate() {
export async function validateNativeWorkspaceReconstruction(db: Db, input: {
companyId: string; issueId: string; runId: string; actionId: string;
successorRunId?: string;
+ continuationRootRunId?: string;
+ predecessorRunIds?: string[];
}) {
const [issue] = await db.select().from(issues).where(and(eq(issues.companyId, input.companyId), eq(issues.id, input.issueId))).for("update");
const [coordinator] = await db.select().from(nativeRunFinalizations).where(and(eq(nativeRunFinalizations.companyId, input.companyId), eq(nativeRunFinalizations.runId, input.runId))).for("update");
@@ -68,7 +71,7 @@ export async function validateNativeWorkspaceReconstruction(db: Db, input: {
)).limit(1);
const [newer] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, input.companyId), ne(heartbeatRuns.id, run.id),
- input.successorRunId ? ne(heartbeatRuns.id, input.successorRunId) : undefined,
+ input.successorRunId ? notInArray(heartbeatRuns.id, [input.successorRunId, ...(input.predecessorRunIds ?? [])]) : undefined,
or(eq(heartbeatRuns.nativeIssueId, issue.id), sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issue.id}`),
or(gt(heartbeatRuns.createdAt, run.createdAt), inArray(heartbeatRuns.status, ["queued", "running"])),
)).limit(1);
@@ -86,7 +89,7 @@ export async function validateNativeWorkspaceReconstruction(db: Db, input: {
if (decision?.workspaceReconstruction) {
const reconstruction = decision.workspaceReconstruction;
if ((!input.successorRunId && issue.status !== "todo") || decision.runId !== run.id || reconstruction.schema !== "paperclip.workspace-reconstruction.v1"
- || (input.successorRunId && (action.evidence.continuationRunId !== input.successorRunId || action.evidence.continuationDelivery !== "delivered"))
+ || (input.successorRunId && (action.evidence.continuationRunId !== (input.continuationRootRunId ?? input.successorRunId) || action.evidence.continuationDelivery !== "delivered"))
|| reconstruction.leaseId !== lease.id || reconstruction.resultId !== result.id
|| reconstruction.descriptorSha256 !== reference.descriptorSha256 || !reconstruction.sources?.length) throw changed();
const files = await db.select({ attachmentId: issueAttachments.id, sha256: assets.sha256 }).from(issueAttachments)
@@ -103,10 +106,32 @@ export async function validateReconstructedWorkspaceDispatch(db: Db, run: typeof
if (typeof context.workspaceReconstructionActionId !== "string") return;
const actionId = context.workspaceReconstructionActionId;
if (typeof context.issueId !== "string" || typeof context.previousRunId !== "string"
- || context.source !== "execution.reconciled" || context.recoveryActionId !== actionId || context.forceFreshSession !== true
- || run.retryOfRunId !== context.previousRunId) throw changed();
+ || context.source !== "execution.reconciled" || context.recoveryActionId !== actionId || context.forceFreshSession !== true) throw changed();
+ const predecessorRunIds: string[] = [];
+ let root = run;
+ while (root.retryOfRunId !== context.previousRunId) {
+ if (!root.retryOfRunId || predecessorRunIds.length >= 64 || predecessorRunIds.includes(root.retryOfRunId)
+ || root.invocationSource !== "automation" || root.triggerDetail !== "system" || !root.scheduledRetryReason
+ || object(root.contextSnapshot).retryOfRunId !== root.retryOfRunId) throw changed();
+ const [wake] = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, run.companyId),
+ eq(agentWakeupRequests.agentId, run.agentId), eq(agentWakeupRequests.id, root.wakeupRequestId ?? "00000000-0000-0000-0000-000000000000"))).for("share");
+ if (!wake || wake.runId !== root.id || wake.source !== "automation" || wake.triggerDetail !== "system"
+ || wake.requestedByActorType !== "system" || wake.payload?.retryOfRunId !== root.retryOfRunId
+ || wake.payload?.retryReason !== root.scheduledRetryReason || wake.payload?.scheduledRetryAttempt !== root.scheduledRetryAttempt) throw changed();
+ const [parent] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, run.companyId),
+ eq(heartbeatRuns.agentId, run.agentId), eq(heartbeatRuns.id, root.retryOfRunId))).for("update");
+ const parentContext = object(parent?.contextSnapshot);
+ if (!parent || !["succeeded", "failed", "timed_out", "cancelled", "interrupted"].includes(parent.status)
+ || parent.scopeKind !== "issue" || parent.issueId !== context.issueId || parent.createdAt > root.createdAt
+ || parentContext.issueId !== context.issueId || parentContext.previousRunId !== context.previousRunId
+ || parentContext.workspaceReconstructionActionId !== actionId || parentContext.recoveryActionId !== actionId
+ || parentContext.source !== "execution.reconciled" || parentContext.forceFreshSession !== true) throw changed();
+ if (await legacyExecutionNeedsReconciliationWithEvidence(db, parent)) throw changed();
+ predecessorRunIds.push(parent.id);
+ root = parent;
+ }
const source = await validateNativeWorkspaceReconstruction(db, { companyId: run.companyId, issueId: context.issueId,
- runId: context.previousRunId, actionId, successorRunId: run.id });
+ runId: context.previousRunId, actionId, successorRunId: run.id, continuationRootRunId: root.id, predecessorRunIds });
if (source.run.agentId !== run.agentId || !object(source.action.evidence.executionReconciliation).workspaceReconstruction) throw changed();
}