From 49165825a003ff8269117f56d11ee51380e799de Mon Sep 17 00:00:00 2001 From: paperclipbugbot Date: Wed, 2 Dec 2026 18:23:39 -0800 Subject: [PATCH] fix(native): restart an unclaimed continued-session follow-up instead of reattaching (#23434) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Native runs can execute in remote Daytona sandboxes. After a server restart, restart recovery decides how each interrupted run continues. > - Recovery can restart an incomplete bootstrap, or it can reattach to a live remote runner. > - A continued-session follow-up gets the previous turn's checkpoint and provider session (`sessionIdBefore`) at admission, before an executor claims it. > - The unclaimed-bootstrap check (#20214) refuses every run that has `sessionIdBefore`. Thus a real follow-up never matches it. Recovery falls through to the generic fallback and reattaches to a runner that never started. > - This pull request lets the unclaimed-bootstrap check accept such a follow-up when all of its session evidence is inherited. > - The benefit is that the run restarts cleanly. It does not fail, and it does not cause the next follow-up to fail. ## Linked Issues or Issue Description Refs #20214, #20153, #20642, #20979, #20226, #19373 **What happened?** A hard restart reached a continued-session follow-up on a new Daytona sandbox before any executor claimed it (coordinator attempt 0, controller generation 0). Recovery chose `reattach_remote_runner` from the inherited provider session ID only. The run failed with `remote_reattach_root_missing`. The next follow-up selected the failed run as its source and failed with `native_controller_recovery_unsupported:metadata_format`. **Steps to reproduce** 1. Admit a continued-session follow-up on a remote sandbox. Admission sets `sessionIdBefore` and rebinds the previous turn's checkpoint to the run. 2. Hard-restart the server before an executor claims the run. 3. Restart recovery claims the run with `reattach_remote_runner`, `providerAttempt: 0`, `controllerGeneration: 1`. **Expected behavior** Recovery restarts the bootstrap (`bootstrap_incomplete`, reason `remote_execution_never_claimed`), as it does for an unclaimed first run. **Environment** Staging, remote Daytona sandboxes, master that includes all of the linked fixes. ## What Changed - `native-restart-recovery.ts`: `unclaimedBootstrap` accepts `sessionIdBefore` when all of these are true: - `sessionIdBefore` equals the rebound checkpoint's `providerSessionId`. - The checkpoint is continued-session-only and inherited-only: no cursor, turns, active turn, result, terminal state, pending requests or provider events. - A settled earlier run of the same native session saved that exact provider session (`carriesSettledPredecessorSession`). - All other unclaimed-bootstrap guards stay the same: no execution-start evidence, no own runner identity, prepared remote workspace, preparation fencing. - `continuedSessionOnly` and `pendingInheritedRequests` move above `unclaimedBootstrap`. Their definitions do not change. - `native-runner-restart-recovery.integration.test.ts`: one new `it.each` with five cases. The rebound follow-up restarts. A session with no settled predecessor, a carried active turn, a projected provider event, and a `sessionIdBefore` that differs from the checkpoint all stay held. ## Verification - Red on master: the new `restarts an unclaimed continued-session follow-up` case received `reattach_remote_runner`, `providerAttempt: 0`, `controllerGeneration: 1`. These are the same values as the staging failure. - Green with this change: `npx vitest run src/services/native-runtime/native-runner-restart-recovery.integration.test.ts` (from `server/`) gives 232 passed and 22 skipped. The skipped tests need `PAPERCLIP_TEST_RUNNER_CONTAINER`, and they skip on master too. - Also passed locally: `heartbeat/recovery.test.ts`, `heartbeat/live-runner-adoption.test.ts`, `native-restart-recovery-isolation.test.ts`, `native-stop-accounting.integration.test.ts`, `native-warm-transition-restart.integration.test.ts`, `native-scheduled-resume-lock.test.ts`, `native-controller-identity.test.ts`, `__tests__/heartbeat-native-restart-suspension.test.ts`, `__tests__/heartbeat-native-early-hand-off.test.ts`. - Not run locally: `native-runner-restart-preparation.integration.test.ts`, `remote-workspace-migration.test.ts`, `heartbeat/workspace-preparation.test.ts`, typecheck and build. The local sandbox could not run `git`, and those fixtures need it. CI covers them. ## Risks - Low risk. The change only adds one more shape to an existing restart path. The shape needs a settled predecessor that saved the same provider session, and the run must have no evidence of its own work. - If the evidence is incomplete, recovery holds the run as before. It does not reattach or restart it. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used as an agent with tool use and code 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 - [ ] 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 - [ ] 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 --- .../native-runtime/native-restart-recovery.ts | 23 ++++++++--- ...unner-restart-recovery.integration.test.ts | 40 +++++++++++++++++++ 2 files changed, 57 insertions(+), 6 deletions(-) diff --git a/server/src/services/native-runtime/native-restart-recovery.ts b/server/src/services/native-runtime/native-restart-recovery.ts index d6454f9f533..0d379910cfe 100644 --- a/server/src/services/native-runtime/native-restart-recovery.ts +++ b/server/src/services/native-runtime/native-restart-recovery.ts @@ -1657,6 +1657,17 @@ export async function claimNativeRestartRecoveries(input: { && !durableAuthority && stagedAttachment === null && providerEvents.length === 0; const inheritedRunnerIdentity = inheritedCheckpointOnly && Boolean(row.run.processPid || row.run.processGroupId) && await carriesInheritedRunnerIdentity(tx, row.run); + const pendingInheritedRequests = Array.isArray(checkpointRecord.pendingRuntimeRequests) + && checkpointRecord.pendingRuntimeRequests.length > 0; + const continuedSessionOnly = hasCheckpoint && checkpointIdentityMatches && providerEvents.length === 0 + && !pendingInheritedRequests && checkpointRecord.activeTurnId == null && checkpointRecord.semanticResult == null + && checkpointRecord.terminal == null; + // Admission of a continued-session follow-up records the previous turn's + // provider session as sessionIdBefore and rebinds that turn's checkpoint + // to this run. Before any executor claims the run, both are inherited, + // not this run's provider work. + const unclaimedContinuedSessionCandidate = Boolean(row.run.sessionIdBefore) && continuedSessionOnly + && inheritedCheckpointOnly && checkpointRecord.providerSessionId === row.run.sessionIdBefore; let unclaimedBootstrap = remoteWorkspace?.state === "prepared" && row.run.runnerProfileJson?.nativePreparationFencingVersion === NATIVE_PREPARATION_FENCING_VERSION && @@ -1672,11 +1683,16 @@ export async function claimNativeRestartRecoveries(input: { (!row.coordinator.leaseExpiresAt || row.coordinator.leaseExpiresAt <= now) && !row.coordinator.failureDetail?.successorRunId && (inheritedRunnerIdentity || (!row.run.processPid && !row.run.processGroupId && !row.run.processStartedAt)) && - !row.run.sessionIdBefore && + (!row.run.sessionIdBefore || unclaimedContinuedSessionCandidate) && !row.run.sessionIdAfter && Boolean(row.run.nativeSessionId && row.run.runnerInstanceId) && (!hasCheckpoint || inheritedCheckpointOnly) && (!hasProviderEvidence || inheritedCheckpointOnly); + // Only a session that a settled earlier run of this session saved is + // inherited; any other carried session keeps its existing recovery decision. + if (unclaimedBootstrap && row.run.sessionIdBefore) { + unclaimedBootstrap = await carriesSettledPredecessorSession(tx, row.run, checkpointRecord.providerSessionId); + } if (unclaimedBootstrap) { if (activeNativeExecutionRunIds.has(row.run.id) && controller.bootId === (await currentNativeControllerIdentity()).bootId) { @@ -1690,11 +1706,6 @@ export async function claimNativeRestartRecoveries(input: { // backend may spawn a runner, and a remote runner exchanges commands only // through a Postgres controller checkpoint. With neither, nothing reached // a runner. The previous controller is gone (takeover was allowed above). - const pendingInheritedRequests = Array.isArray(checkpointRecord.pendingRuntimeRequests) - && checkpointRecord.pendingRuntimeRequests.length > 0; - const continuedSessionOnly = hasCheckpoint && checkpointIdentityMatches && providerEvents.length === 0 - && !pendingInheritedRequests && checkpointRecord.activeTurnId == null && checkpointRecord.semanticResult == null - && checkpointRecord.terminal == null; const portablePreparation = pluginTask?.unlaunchedPortable === true && row.run.status === "running" && row.coordinator.phase === "observed" && !durableAuthority && !row.run.sessionIdAfter && row.run.runnerProfileJson?.nativePreparationFencingVersion === NATIVE_PREPARATION_FENCING_VERSION && diff --git a/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts b/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts index 740a6b740ac..f4240b74e1a 100644 --- a/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts +++ b/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts @@ -3463,6 +3463,46 @@ process.on("SIGTERM", () => child.kill("SIGTERM")); expect(coordinator.recoveryHistory.at(-1)).toMatchObject({ reason: "remote_execution_never_claimed" }); }); + // A hard restart reached a continued-session follow-up on a new Daytona + // sandbox before any executor claimed it. Admission had + // already rebound the previous turn's checkpoint and recorded that provider + // session as sessionIdBefore. Reattaching found no runner state in the new + // sandbox (remote_reattach_root_missing), and the failed run then became the + // next follow-up's metadata_format source. + it.each([ + { label: "restarts", mode: "rebound" }, + { label: "keeps the reattach decision when no settled earlier run saved the provider session in", mode: "no_predecessor" }, + { label: "keeps the reattach decision for a carried active turn in", mode: "active_turn" }, + { label: "keeps the reattach decision for a projected provider event in", mode: "provider_event" }, + { label: "keeps the reattach decision when sessionIdBefore differs from the checkpoint in", mode: "other_session" }, + ] as const)("$label an unclaimed continued-session follow-up", async ({ mode }) => { + const fixture = await seedUnlaunchedRemoteClaim(`UNCLAIMED-CONTINUED-${mode}`); + await reboundFollowUpCheckpoint(fixture, mode === "active_turn" ? { activeTurnId: "turn-in-flight" } : {}, + mode !== "no_predecessor"); + if (mode === "other_session") await fixture.db.update(heartbeatRuns).set({ sessionIdBefore: "other-thread" }) + .where(eq(heartbeatRuns.id, fixture.runId)); + await fixture.db.update(nativeRunFinalizations).set({ attempt: 0, controllerGeneration: 0, controllerBootId: null, + controllerPid: null, controllerProcessStartedAt: null, leaseOwner: null, leaseExpiresAt: null }) + .where(eq(nativeRunFinalizations.runId, fixture.runId)); + if (mode === "provider_event") await fixture.db.insert(heartbeatRunEvents).values({ companyId, runId: fixture.runId, + agentId, seq: 901, stream: "system", level: "info", eventType: "session.started" }); + const [claim] = await claimNativeRestartRecoveries({ db: fixture.db, controller: successor, + restartKind: "hard", runIds: [fixture.runId] }); + const [coordinator] = await fixture.db.select().from(nativeRunFinalizations) + .where(eq(nativeRunFinalizations.runId, fixture.runId)); + if (mode !== "rebound") { + // Excluded shapes must reach the pre-existing reattach decision, not a + // recovery error that would also avoid bootstrap_incomplete. + expect(claim).toMatchObject({ kind: "reattach_remote_runner", runId: fixture.runId, providerAttempt: 0, + controllerGeneration: 1 }); + expect(coordinator.recoveryHistory.at(-1)).toMatchObject({ reason: "remote_runner_requires_sandbox_verification", + disposition: "reattach_remote_runner" }); + return; + } + expect(claim).toMatchObject({ kind: "bootstrap_incomplete", runId: fixture.runId, providerAttempt: 0, controllerGeneration: 1 }); + expect(coordinator.recoveryHistory.at(-1)).toMatchObject({ reason: "remote_execution_never_claimed" }); + }); + it.each([ { label: "bootstraps a follow-up carrying its predecessor's Runner identity", mode: "inherited", restarts: true }, { label: "bootstraps a follow-up that requested its warm Runner on its predecessor's identity", mode: "inherited_requested", restarts: true },