mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-30 17:14:54 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - A remote per-turn follow-up inherits the previous run's session checkpoint at admission, rebound to its own identity. Its session root still holds the previous owner's remote marker until the follow-up rotates authority > - If a restart lands before the follow-up's controller ever claims execution, recovery should restart its bootstrap: nothing of this run reached any runner > - Recovery's unclaimed-bootstrap check required no checkpoint and no provider evidence. The inherited checkpoint failed both, so recovery claimed `reattach_remote_runner` > - Even under a bootstrap claim, the executor skipped the per-turn projection restore for every restart claim. It therefore never rehydrated the previous owner's external marker, and failed with `runner_state_identity_mismatch: durable_identity_unreadable` > - This pull request does not count the inherited checkpoint as evidence for an unclaimed remote run, and lets a bootstrap claim restore the previous owner's projection, as a fresh follow-up start does > - The benefit is that a follow-up drained in its first second on Daytona restarts on its own ## Linked Issues or Issue Description Refs #20153 **What happened?** Daytona per-turn restart-chaos K13 storm w-20261109T074128-s9503 (revision9046884811), t26 (codex C1): follow-up run `f1ddc43d` started at 07:54:18 and was drained by SIGTERM at 07:54:19, during workspace staging. - It had not requested a runner process, and its coordinator was never claimed (provider attempt 0). - Recovery claimed `reattach_remote_runner` (`hasCheckpoint: true`, `hasProviderEvidence: true`, both from the inherited checkpoint). - The executor failed with `runner_state_identity_mismatch: durable_identity_unreadable`, because the session root held the previous run's external marker. A Retry succeeded. **Expected behavior** An unclaimed remote run whose only checkpoint is the admission-rebound one, with no durable controller record and no provider events, restarts its bootstrap (`remote_execution_never_claimed`). The executor rehydrates the previous owner's projection and starts the follow-up from it. **Steps to reproduce** 1. Start a remote per-turn follow-up whose session root holds the previous owner's external marker. Drain the control plane before the follow-up's controller claims execution. 2. Restart. Before this change, recovery claims `reattach_remote_runner` and the executor fails with `durable_identity_unreadable`. **Paperclip version or commit**9046884811(wave). Branch rebased on current master. ## What Changed - `native-restart-recovery.ts`: - #20153's admission-rebound checkpoint test moves earlier. A new `inheritedCheckpointOnly` holds for a remote sandbox run (not a plugin task) with only that checkpoint, no durable controller record, no staged attachment and no provider events. - The unclaimed-bootstrap path and its classification then treat that checkpoint as neither a checkpoint nor provider evidence. - `native-inherited-runner-retry.ts` / `native-restart-recovery.ts`: a warm continuation carries its settled predecessor's runner process identity until it launches its own runner, and t26's row still held pid 596 at the restart. - The new `carriesInheritedRunnerIdentity` reuses the same-run retry path's proof (the exact pid, group and start time a settled predecessor recorded). - The restart classifier then ignores that inherited identity on the unclaimed path, for a run that carries only its inherited checkpoint. - A process identity that is the run's own still holds the run. - `native-session-executor.ts`: `restorePerTurnRunnerdController` now also runs for a `bootstrap_incomplete` claim, but only when the root's reference identity belongs to a previous run. A claim on the run's own root returns early, as before. - Tests: - `native-runner-restart-recovery.integration.test.ts`: an unclaimed remote follow-up with only its inherited checkpoint restarts, with no process identity and with its predecessor's runner identity. It stays held with its own runner identity, or when a provider event was projected; - `native-recovered-owner-followup.test.ts`: a bootstrap claim over the previous owner's external marker is admitted, rehydrating the marker, keeping the backup and quarantining nothing. ## Verification - Red/green: both new tests fail on master. The classifier test claims `reattach_remote_runner`, and the executor test fails with exactly `durable_identity_unreadable`. Both pass with the change, and the held case holds. - `vitest run` over the restart-recovery, bootstrap, recovered-owner and failed-workspace-recovery test files and `native-session-executor.test.ts`: 9 files, 1715 tests passed (14 skipped). After the inherited-identity change, the restart-recovery, bootstrap, recovered-owner, failed-workspace-recovery and inherited-runner test files: 8 files, 407 tests passed (14 skipped). Without the identity check, the inherited case is not restarted. - `PAPERCLIP_TYPECHECK_LOW_MEMORY=1 pnpm typecheck` (`server`): passed. ## Risks - Low risk: - The inherited checkpoint stops counting only when the database shows no controller record and no provider event for the run, and the existing unclaimed-bootstrap conditions all still hold. - The executor change runs the existing fresh-follow-up projection restore, with all of its own checks, only for a root that still belongs to the previous run. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use (shell, file edits, test execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
187 lines
12 KiB
TypeScript
187 lines
12 KiB
TypeScript
import { and, desc, eq, inArray, isNull, lt, ne, or, sql } from "drizzle-orm";
|
|
import { environmentLeases, heartbeatRuns, issues, nativeRunFinalizations, type Db } from "@paperclipai/db";
|
|
import { remoteWorkspaceRunReferenceSchema } from "@paperclipai/shared";
|
|
import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js";
|
|
import { notifyLiveRunRecovery } from "../live-run-recovery-notifications.js";
|
|
import { isNativeRunnerOwnershipHeld } from "./native-runner-ownership.js";
|
|
import { hasNativeRunnerCheckpoint } from "./native-runner-checkpoint.js";
|
|
import { nativeSessionProviderEvidence } from "./native-session-resume.js";
|
|
import { hasNativeExecutionStartEvidence } from "./native-restart-recovery.js";
|
|
import { readNativeWorkspaceSyncReference } from "./native-workspace-sync.js";
|
|
import { logger } from "../../middleware/logger.js";
|
|
|
|
/**
|
|
* A continuation run starts with its predecessor's saved provider session and,
|
|
* for a warm session, the predecessor's runner process identity. When such a
|
|
* run fails before it ever asks for its own runner (for example while staging
|
|
* its provider pack), the recorded process identity is the predecessor's, not
|
|
* its own. A due same-run retry used to reattach to "this run's" runner, which
|
|
* never existed, and always failed with `native_remote_recovery_lease_mismatch`.
|
|
*
|
|
* This module proves that shape from durable state and retires the inherited
|
|
* identity, so the retry takes the ordinary same-run resume: the same path the
|
|
* failed attempt took. It also records the run's own retained sandbox lease,
|
|
* so preparation resumes that exact sandbox instead of acquiring another one.
|
|
*/
|
|
export const NATIVE_INHERITED_RUNNER_RETIREMENT_KEY = "nativeInheritedRunnerRetirement";
|
|
const RETIREMENT_SCHEMA = "paperclip.native-inherited-runner-retirement.v1";
|
|
|
|
const TERMINAL_RUN_STATUSES = ["succeeded", "failed", "cancelled", "timed_out", "interrupted"];
|
|
|
|
export type InheritedRunnerRetainedSandbox = { leaseId: string; providerLeaseId: string; remoteCwd: string };
|
|
|
|
function record(value: unknown): Record<string, unknown> {
|
|
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
|
}
|
|
|
|
/** Lock unavailable, statement timeout, serialization failure, deadlock, shutdown, or a connection class error. */
|
|
const TRANSIENT_SQLSTATES = new Set(["55P03", "57014", "40001", "40P01", "57P01", "57P03"]);
|
|
|
|
function isTransientDatabaseError(error: unknown): boolean {
|
|
for (let current = error, depth = 0; current && typeof current === "object" && depth < 5;
|
|
current = (current as { cause?: unknown }).cause, depth++) {
|
|
const code = (current as { code?: unknown }).code;
|
|
if (typeof code === "string" && (TRANSIENT_SQLSTATES.has(code) || code.startsWith("08"))) return true;
|
|
if (typeof code === "string" && ["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "CONNECTION_CLOSED", "CONNECTION_ENDED"].includes(code)) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function sameTime(left: Date | null, right: Date | null) {
|
|
return (left?.getTime() ?? null) === (right?.getTime() ?? null);
|
|
}
|
|
|
|
/** The run's saved remote location: a native workspace sync or a remote workspace reference. */
|
|
function savedRemoteLocation(profile: Record<string, unknown>): InheritedRunnerRetainedSandbox | null {
|
|
const sync = readNativeWorkspaceSyncReference(profile.nativeWorkspaceSync);
|
|
if (sync) return { leaseId: sync.leaseId, providerLeaseId: sync.providerLeaseId, remoteCwd: sync.remoteCwd };
|
|
const remote = remoteWorkspaceRunReferenceSchema.safeParse(profile.remoteWorkspace);
|
|
return remote.success
|
|
? { leaseId: remote.data.leaseId, providerLeaseId: remote.data.providerLeaseId, remoteCwd: remote.data.remoteCwd }
|
|
: null;
|
|
}
|
|
|
|
/** The retained sandbox recorded when the inherited identity was retired, if it still matches the saved location. */
|
|
export function readInheritedRunnerRetainedSandbox(profile: Record<string, unknown> | null | undefined): InheritedRunnerRetainedSandbox | null {
|
|
const marker = record(profile?.[NATIVE_INHERITED_RUNNER_RETIREMENT_KEY]);
|
|
const sandbox = record(marker.retainedSandbox);
|
|
const location = savedRemoteLocation(record(profile));
|
|
if (marker.schema !== RETIREMENT_SCHEMA || !location || sandbox.leaseId !== location.leaseId
|
|
|| sandbox.providerLeaseId !== location.providerLeaseId || sandbox.remoteCwd !== location.remoteCwd) return null;
|
|
return location;
|
|
}
|
|
|
|
/**
|
|
* Retires the inherited remote runner identity of a due same-run retry when
|
|
* durable state proves all of these:
|
|
*
|
|
* - the failed attempt is a result-less exact-checkpoint retry that recorded
|
|
* `providerEventsExist: false`, and no controller owns it;
|
|
* - this run never requested or identified a runner, invoked the adapter,
|
|
* started a tool, or committed a runner event, has no controller checkpoint
|
|
* of its own, and has no provider event or provider session of its own;
|
|
* - its saved session has no active turn and no pending runtime request; and
|
|
* - its exact process identity is the one a settled predecessor of the same
|
|
* native session recorded.
|
|
*
|
|
* Anything else, including rows saved by a release that did not record these
|
|
* facts, keeps the existing verified reattachment path.
|
|
*/
|
|
export type InheritedRunnerRetirement = "retired" | "not_applicable" | "transient";
|
|
|
|
type RunnerIdentityRun = Pick<typeof heartbeatRuns.$inferSelect,
|
|
"id" | "companyId" | "agentId" | "nativeSessionId" | "createdAt" | "processPid" | "processGroupId" | "processStartedAt">;
|
|
|
|
/** The settled predecessor whose exact runner process identity this run carries. */
|
|
async function settledPredecessorWithRunnerIdentity(tx: Pick<Db, "select">, run: RunnerIdentityRun) {
|
|
if (!run.nativeSessionId || (run.processPid === null && run.processGroupId === null)) return null;
|
|
const [predecessor] = await tx.select({ id: heartbeatRuns.id, processStartedAt: heartbeatRuns.processStartedAt })
|
|
.from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, run.companyId), eq(heartbeatRuns.agentId, run.agentId),
|
|
eq(heartbeatRuns.nativeSessionId, run.nativeSessionId), ne(heartbeatRuns.id, run.id),
|
|
lt(heartbeatRuns.createdAt, run.createdAt), inArray(heartbeatRuns.status, TERMINAL_RUN_STATUSES),
|
|
run.processPid === null ? isNull(heartbeatRuns.processPid) : eq(heartbeatRuns.processPid, run.processPid),
|
|
run.processGroupId === null ? isNull(heartbeatRuns.processGroupId) : eq(heartbeatRuns.processGroupId, run.processGroupId),
|
|
)).orderBy(desc(heartbeatRuns.createdAt)).limit(1);
|
|
return predecessor && sameTime(predecessor.processStartedAt, run.processStartedAt) ? predecessor : null;
|
|
}
|
|
|
|
/** The run's recorded runner process identity is exactly a settled predecessor's, not its own. */
|
|
export async function carriesInheritedRunnerIdentity(tx: Pick<Db, "select">, run: RunnerIdentityRun): Promise<boolean> {
|
|
return (await settledPredecessorWithRunnerIdentity(tx, run)) !== null;
|
|
}
|
|
|
|
export async function retireInheritedRemoteRunnerIdentity(db: Db, runId: string): Promise<InheritedRunnerRetirement> {
|
|
return db.transaction(async transaction => {
|
|
const tx = transaction as unknown as Db;
|
|
await tx.execute(sql`select set_config('lock_timeout', '2000', true)`);
|
|
const [candidate] = await tx.select({ companyId: heartbeatRuns.companyId, issueId: heartbeatRuns.nativeIssueId })
|
|
.from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).limit(1);
|
|
if (!candidate?.issueId) return "not_applicable";
|
|
// Same lock order as same-run resumption: issue, coordinator, run.
|
|
const [issue] = await tx.select({ id: issues.id }).from(issues).where(and(
|
|
eq(issues.companyId, candidate.companyId), eq(issues.id, candidate.issueId))).for("update").limit(1);
|
|
if (!issue) return "not_applicable";
|
|
const [coordinator] = await tx.select().from(nativeRunFinalizations).where(and(
|
|
eq(nativeRunFinalizations.companyId, candidate.companyId), eq(nativeRunFinalizations.runId, runId),
|
|
eq(nativeRunFinalizations.issueId, issue.id))).for("update").limit(1);
|
|
const [run] = await tx.select().from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, candidate.companyId), eq(heartbeatRuns.id, runId))).for("update").limit(1);
|
|
// A concurrent sweep already retired it: route it to the same resume.
|
|
if (coordinator && run && run.processPid === null && run.processGroupId === null
|
|
&& record(record(run.runnerProfileJson)[NATIVE_INHERITED_RUNNER_RETIREMENT_KEY]).schema === RETIREMENT_SCHEMA
|
|
&& coordinator.phase === "retryable_failure" && coordinator.resultId === null) return "retired";
|
|
if (!coordinator || !run || run.runtimeMode !== "native" || isNativeRunnerOwnershipHeld(run)
|
|
|| !["running", "failed"].includes(run.status) || run.sessionIdAfter
|
|
|| (run.processPid === null && run.processGroupId === null) || !run.nativeSessionId) return "not_applicable";
|
|
const detail = record(coordinator.failureDetail);
|
|
if (coordinator.phase !== "retryable_failure" || coordinator.resultId !== null || coordinator.leaseOwner !== null
|
|
|| detail.recoveryMode !== "exact_checkpoint_resume" || detail.providerEventsExist !== false
|
|
|| typeof detail.successorRunId === "string") return "not_applicable";
|
|
|
|
const profile = record(run.runnerProfileJson);
|
|
const location = savedRemoteLocation(profile);
|
|
const checkpoint = record(profile.sessionCheckpoint);
|
|
const pending = checkpoint.pendingRuntimeRequests;
|
|
if (!location || checkpoint.activeTurnId != null
|
|
|| (pending !== undefined && pending !== null && (!Array.isArray(pending) || pending.length > 0))) return "not_applicable";
|
|
if (await hasNativeExecutionStartEvidence(tx, run)) return "not_applicable";
|
|
if ((await nativeSessionProviderEvidence(tx, [run.id])).has(run.id)) return "not_applicable";
|
|
if (await hasNativeRunnerCheckpoint(tx, { companyId: run.companyId, issueId: issue.id, runId: run.id })) return "not_applicable";
|
|
|
|
const predecessor = await settledPredecessorWithRunnerIdentity(tx, run);
|
|
if (!predecessor) return "not_applicable";
|
|
|
|
// Keep the run's own sandbox when its lease is still live.
|
|
const [lease] = await tx.select({ id: environmentLeases.id }).from(environmentLeases).where(and(
|
|
eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.id, location.leaseId),
|
|
eq(environmentLeases.heartbeatRunId, run.id), eq(environmentLeases.providerLeaseId, location.providerLeaseId),
|
|
eq(environmentLeases.status, "active"), isNull(environmentLeases.releasedAt), isNull(environmentLeases.cleanupStatus),
|
|
or(isNull(environmentLeases.expiresAt), sql`${environmentLeases.expiresAt} > now()`))).limit(1);
|
|
|
|
await notifyLiveRunRecovery(tx, { companyId: run.companyId, runId: run.id, agentId: run.agentId });
|
|
await tx.update(heartbeatRuns).set({
|
|
processPid: null, processGroupId: null, processStartedAt: null,
|
|
runnerProfileJson: { ...profile, [NATIVE_INHERITED_RUNNER_RETIREMENT_KEY]: {
|
|
schema: RETIREMENT_SCHEMA, predecessorRunId: predecessor.id,
|
|
...(lease ? { retainedSandbox: location } : {}),
|
|
} },
|
|
updatedAt: new Date(),
|
|
}).where(eq(heartbeatRuns.id, run.id));
|
|
await appendHeartbeatRunEvent(tx, {
|
|
companyId: run.companyId, runId: run.id, agentId: run.agentId,
|
|
eventType: "lifecycle", stream: "system", level: "info",
|
|
message: "Retrying this run in its own sandbox: it never started a runner, so there was nothing to reattach to.",
|
|
payload: { reason: "inherited_runner_never_launched", predecessorRunId: predecessor.id,
|
|
retainedSandbox: Boolean(lease) },
|
|
});
|
|
return "retired" as const;
|
|
}).catch((error): InheritedRunnerRetirement => {
|
|
logger.warn({ err: error, runId }, "failed to retire an inherited remote runner identity");
|
|
// A busy lock, a serialization conflict or a lost connection proves
|
|
// nothing: keep the run for the next sweep. Any other error keeps the
|
|
// existing recovery path, which reports its own cause.
|
|
return isTransientDatabaseError(error) ? "transient" : "not_applicable";
|
|
});
|
|
}
|