From 4363a3115a80a9f51585e9d89a11c95e475b9f83 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:34:34 -0600 Subject: [PATCH] fix(recovery): continue any unfinished run in a fresh run from saved work (#21135) 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 > - Agent runs are interrupted when a server restarts, a deploy swaps servers, a controller lease is lost, or a sandbox Runner cannot be reached again > - Exact recovery (resume the same session, replace, retry) refuses in many ways, and each refusal leaves the task blocked or idle for a person > - On staging, 577 of 1,000 runs in 11 hours failed or were interrupted, across 25 error codes. About 900 earlier PRs each fixed one refusal code, and the rate did not converge > - This pull request adds one universal fallback: when an unfinished run cannot be resumed exactly, for any reason that is not the person's, the task continues in a fresh run from its last saved workspace and its conversation > - The benefit is that a new failure code next week falls back without code changes, and tasks stop waiting on a person for infrastructure faults ## Linked Issues or Issue Description **What happened?** After a server restart or deploy swap, many runs end with codes such as `native_continuation_requires_reconciliation` (`runner_remote_process_identity_unavailable`), `controller_lease_lost`, `process_lost`, `server_shutdown_interrupted` and `native_session_interrupted` (including `runner_harness_state_mismatch: resumed_not_suspended` / `resumed_unavailable`). The disposition worker then settles the recovery hold as "blocked, no replay". The task stays Blocked until a person presses Retry or reconciles the run. **Expected behavior** A task waits on a person only for reasons that are the person's: an approval, a question, a credential to share, a budget stop, a provider usage limit, or a Stop they asked for. For every other failure, the system starts a new run for the same task from the last verified saved workspace, without a person. **Steps to reproduce** 1. Start a task on a sandbox agent. 2. Restart or swap the server while the run is in progress, so the new server cannot re-reach the Runner. 3. See that the run fails with `native_continuation_requires_reconciliation` and the task stays Blocked with no successor run. **Paperclip version or commit** `master` at 9e910ff9ae. ## What Changed - New module `server/src/services/fresh-continuation-fallback.ts`. One entry point, `ensureFreshContinuation` / `continueFreshInTransaction`, takes a run that ended without finishing and guarantees one of: something already follows it (a newer run, a linked replacement, an operator decision), exact recovery is still under way (checked again later), the cause is the person's, or one fresh continuation is recorded. - Classification, not an allowlist: `PERSON_OWNED_FAILURE_CODES` plus task-level waits (pending approval, pending question, paused or unavailable agent, paused company, review in progress, a Stop that a person asked for, a Blocked status that another decision owns). Every other code, including unknown future codes, falls back. - Idempotent per source run. The task row lock serializes callers on every server; the recorded `freshContinuation.sourceRunId` makes later calls a no-op. - Isolation, never waiting on proof. A local process still running on this host is settled by its own owner first. If the old local writer is proven gone, the task workspace is kept. Otherwise the continuation gets a new isolated workspace (`fresh_isolated_workspace`), so two runs never write one directory. The decision records the stop proof honestly (`providerStopProof: isolated`). - Claim admission no longer waits on the cleanup of a predecessor that a fresh continuation replaced (`heartbeat/queue.ts`, predecessor loop). Without this, the successor stayed queued behind the unreachable lease, which is the staging failure itself. - Only reconciliation holds that this decision owns are settled. Workspace restore holds that workspace recovery still owns, and resolved history, are untouched. - `continuation_user_authorization_missing` is the system's failure (a Retry's authorization was not carried forward), not the person's. - Safety: the old run keeps its fencing. When it still owns its remote workspace epoch, the epoch is abandoned (`abandonUnverifiedRemoteWorkspaceEpoch`), so the old writer can never publish and the next run restores the last committed save into a new root on a new allocation. The unverified files stay in the abandoned root, unapplied. The native coordinator records `replacementDenied: fresh_continuation`, so no exact replay also starts. - The replaced run loses its write authority. The fallback records `freshContinuationSupersededAt` on the old run. The agent-JWT middleware (`loadAgentRunAuthentication` reads one more field in its existing row read) and `assertAgentRunWriteAllowed` refuse every write of the old token with `agent_run_superseded`. Before this change, a failed or interrupted run's token could still write. So an agent that is still alive in an unreachable sandbox cannot act on the task next to its continuation. - The opening context (`recoveryOutcomes` in the execution continuation) says that the previous attempt was cut off and lists the actions with unverified outcomes, so the agent checks before it repeats a side effect. No copy asks a person to inspect or repair a sandbox, workspace or run. The hold text written at run end no longer says "Inspect the original failure and reconcile". - Delivery reuses the existing path: the settled hold gets an `executionReconciliation` decision and `continuationDelivery: pending`, and `deliverReconciledExecutions` starts the run (fresh session, `retryOfRunId` = source). - Budget per task, not per restart: at most 6 fresh continuations per task per rolling hour (the server-restart lane's cap). At the cap the hold stays with the system and is checked again when the window has room. The failure allowance is never charged. - Call sites: - `settleUnrecoverableExecutions` (execution-recovery-resolution.ts): every hold whose exact recovery is ruled out now goes through the fallback before it would block the task. Interrupted preparations keep their own replay lane first. - `continueHeldExecutions` (same worker): picks up holds saved by older releases (settled-but-blocked no-replay holds, finished or exhausted saved-work recoveries) for the task's latest unfinished run. - Wake admission (heartbeat/queue.ts): an ordinary system continuation wake (sweep, monitor, timer) that a hold would defer now calls the fallback in the same transaction and becomes the fresh continuation itself. This is the path the idle-task sweep uses. A person's Retry, message or queued send keeps its exact admission; the disposition worker settles the hold, and the saved input then continues. - `executionControlSchedule.disposition` wakes the worker for held tasks and for the next due recheck. ### Human gate versus system uncertainty One documented rule (`isHumanGate` plus `personOwnedTaskWait`) decides what the fallback never touches. The rule goes by cause, never by owner type: - Human gates: a pending approval, a pending question, a user-owned hold, an owner-gone attestation, a recorded explicit continuation, an operator reconciliation, a person's Stop. - System uncertainty: a no-replay record ("outcome unknown after an interruption"), a hold that is `board`-owned only by default, an unverifiable controller process space or host. For uncertainty the fallback starts a fresh run, never a replay. The interrupted turn is not re-sent. No tool call or write is re-executed. Governed actions go through their approval gate again. The earlier `automaticRecovery` decision is kept on the hold as `automaticRecoveryHistory`, beside the attributed `freshContinuationSettlement` and an activity entry. ### Restart recovery refused for an unverifiable controller The case is `controller_process_space_unverified`, its remote variant, or `controller_host_unrecorded` / `controller_host_unprovable`. Its lease has lapsed; a live, renewing lease is still waited for (server overlap). After `NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS` (2 minutes) the run ends (failed, `native_restart_recovery_blocked`). That frees the task's execution lock and the agent's slot, and a system-owned hold lets the fallback continue the task. Recording the stops is optional. The "a board operator must record both stops" text is replaced. Board/operator attention sites in native restart recovery: - `surfaceNativeControllerNamespaceAttention`: copy replaced; the run now ends after the bounded wait. - `requestNativeControllerStopConfirmation` (native-controller-host-recovery.ts): copy says confirmation is optional; the same bounded end applies. - The blocked restart-recovery hold (`nextAction` "Inspect the preserved checkpoint and reconcile…"): copy replaced; the fallback settles the hold by cause. - `owner-gone-attestation.ts` (generic resource records from older releases): unchanged. It is not a run-recovery path, and it is listed as a follow-up. ### Every wait and its bound | Wait | Owner that rechecks | Worst-case total before the fresh continuation | | --- | --- | --- | | `exact_recovery_pending` (execution settling, native finalizer, controller lease, interrupted-preparation lane, saved-work recovery, restore hold, retained-source fallback, live local process) | Disposition worker, woken at each deadline; rechecks at 1, 2, 3 and 4 minutes, then every 4 | About 10 minutes from the first pending check. Up to 15 while the owner shows progress (a new event, output, lease renewal or coordinator update since the last check). | | Saved-work (workspace) recovery that is `scheduled`, `awaiting_evidence`, or `running` without progress | Held-run scan, now selected and scheduled like the other holds | About 10 minutes; 15 at most | | Saved-work recovery that is `running` and advancing (revision, attempt, state or hold update since the last check) | Held-run scan | Its own 30-minute budget | | Unverifiable lapsed controller in restart recovery | Restart recovery (`retryAt`) | 2 minutes, then the run ends and the fallback continues it within one disposition pass | | Hourly cap (`backoff`) | Disposition worker, woken at the deadline | Until the rolling hour frees a slot, at most 1 hour. This is the deliberate restart-lane bound, not a stuck state. | | Person-owned or dependency wait | The person's own action wakes the task; rechecked hourly | Not bounded: it is the person's | Restart-recovery classifications (`claimNativeRestartRecoveries`, which `recoverNativeRunsAfterRestart` calls): | Classification | Who rechecks, when | Bound | | --- | --- | --- | | Claims: `reattach_existing_runner`, `reattach_remote_runner`, `resume_dead_runner`, `bootstrap_incomplete` | The claiming server resumes exactly | Exact resume; no fallback | | `already_finalized` | Nobody; it is terminal | None needed | | `blocked` | The run is terminal and its hold goes to the fallback (disposition worker) | Fallback bounds above | | `awaiting_evidence` / `current_controller_preparing` | This process's own executor | Ends with that executor | | `awaiting_evidence` / `recovery_rows_busy` | Restart dispatch after 1 second | Self-resolving: the row lock clears | | `awaiting_evidence` / a live lease (`controller_lease_held`, `controller_lease_grace`, `controller_still_alive`) | Restart dispatch at the lease-renew interval | Never ended while the old controller renews its lease | | `awaiting_evidence` / unverifiable lapsed controller (process space or host) | Restart dispatch every 2 minutes | Ends 2 minutes after the lease lapsed | | `awaiting_evidence` / any other reason (startup cleanup, finalizer or cleanup owner, recovery failure, routine busy, future reasons) | Restart dispatch at the owner's `retryAt`, or within 2 minutes when it has none | Ends 2 minutes after the lease lapsed, or after 10 minutes, whichever comes first. It never ends while a lease is live. | Ending a run sets it failed (`native_restart_recovery_blocked`), releases the task lock and the agent's slot, and records a system-owned hold. The fallback then continues the task once, isolated. No wait needs longer. Saved-work recovery and retained-source checks keep their own attempt budgets. After 10 to 15 minutes the fallback continues anyway in a new root, without the unverified files, which stay recorded and unapplied. ### When the fallback preempts saved-work recovery The unverified files are not destroyed. They stay where recovery found them: in the abandoned remote epoch's root, or in the old local workspace that the task is no longer bound to. They are recorded and never applied. Settling the hold records the decision on it, so the retained-workspace worker stops scheduling it (its query requires no `executionReconciliation` unless recovery already succeeded). If an attempt already in flight finishes later, it cannot publish into the fresh run's workspace. For a remote workspace, the epoch it targets is abandoned and the writer is cleared. For a local one, the task now points at a new workspace. Whenever a wait is preempted, the continuation is isolated: a fenced remote epoch or a new local workspace. ### What people see The task's interruption presentation shows "working" while the primary fresh-continuation record is pending and has not started (coalesced holds never count, and they follow the primary's final state), and a timed wait with no Retry while a check is scheduled. The Retry banner appears only when the system has given up or the cause is the person's. Holds settled together with the primary record are `coalesced`; they no longer show "closed or reassigned". A pending continuation is never a second run: if a person's Retry or saved input started a run after it was recorded, delivery links to that run instead. A task that finished before delivery gets no run. ### Readers of what the fallback writes - Recheck deadline (`freshContinuationCheck`): - `unresolvedExecutionDispositions` and `heldExecutionsAwaitingFreshContinuation` read it to skip work that is not due. - `nextFreshContinuationCheckAt` and `executionControlSchedule.disposition` read it to schedule the worker. - Tests: the cap deadline is scheduled, and a cancelled task goes quiet. - Isolation decision: - The task's workspace binding is cleared. Every path that starts the next run (system continuation, saved input, Retry, sweep wake) resolves the workspace from that binding at run start (heartbeat.ts `issueContext.executionWorkspaceId`). - `freshContinuationIsolation` in the run context is read by `readFreshWorkspaceReadiness` for the shared-directory case. - `freshContinuationSupersededAt` on the old run is read by the auth middleware, `assertAgentRunWriteAllowed` and the claim gate. ## Verification - `pnpm vitest run src/services/fresh-continuation-fallback.test.ts` (server): every test passes (it covers the cases below). - The continuation starts (leaves the queue) while the unreachable old lease is `active` or `pending_cleanup`. This was red before the claim-admission fix. - Isolation: a writer on another host gets a new isolated workspace; a process alive on this host waits for its owner; a proven-gone writer keeps the workspace. - Owned holds only: a restore hold and resolved history are untouched. - The recheck schedule goes quiet when the task is cancelled. - `continuation_user_authorization_missing` continues under the task's responsible user. - One test per top-five staging code (native and legacy hold shapes): the task gets exactly one fresh successor run from saved state. - `runner_harness_state_mismatch` (`resumed_not_suspended`, `resumed_unavailable`) falls back. - An unknown code falls back. - Two concurrent callers plus the disposition worker create one successor. - Old-saved/new-resumed: a settled-but-blocked hold from the previous release, with its coordinator in `awaiting_runner_reattach`, continues on the first pass. - An ordinary system continuation wake is admitted as the fresh continuation. - Fencing: after the continuation is recorded, the old run's token is refused for writes (`agent_run_superseded`) and the continuation's token is not. The old run's remote workspace epoch is abandoned: the writer is cleared, the location and provider root are cleared, and the epoch advances. So the next preparation restores the last save into a new root (`prepareRemoteWorkspace`: `sameAllocation` is false when the location is null, server/src/services/remote-workspaces.ts:437-470). - The opening context names the cut-off run and an unverified tool action. - Person-owned causes (pending approval, credential not shared, budget stop) are not continued. - The hourly cap backs off without blocking, then continues. - Red/green: with the wiring reverted to `master`, 9 of these tests fail (the task stays Blocked with no successor). - Affected suites pass locally: `execution-recovery-dead-controller`, `completed-turn-cleanup-hold-settle`, `execution-control-work`, `heartbeat-process-recovery`, `issue-recovery-actions`, `native-safe-replacement`, `native-failed-workspace-recovery`, `task-retry`, `runner-lost-mid-turn-continuation`, `workspace-recovery-fallback`, `explicit-native-continuation`, wake-queue `postgres`, `agent-conversations`, `native-startup-retry`, `governed-wait-runner-loss`, `native-preclaim-continuation`. - `pnpm verify --explain` selects the full suite (the wake queue is shared), so CI supplies full coverage. Existing expectations changed because they asserted the "wait for a person" behavior this PR replaces: - `issue-monitor-scheduler.test.ts`: "explains held monitor dispatch without replaying uncertain execution" is now "continues a held task in a fresh run when its monitor is due". A due monitor on a task held by a `process_lost` hold now starts one fresh run instead of deferring. - `agent-run-authentication.test.ts`: the auth row also reads `freshContinuationSupersededAt` (still under 512 bytes), and a superseded run is refused. - `assigned-work-invariant.test.ts` (#21139): "with the real wake queue, a hold that defers the continuation leaves a violation…" is now "…a hold reached by the sweep's wake becomes one pending fresh continuation". The sweep's wake now yields one pending fresh continuation, and the next sweep adds no attempt. - `heartbeat-native-restart-suspension.test.ts` and `native-runner-restart-recovery.integration.test.ts`: awaiting-evidence dispositions now carry a `retryAt`, because every wait is rechecked. A lapsed unverifiable controller no longer waits forever. - `native-remote-retry-admission.test.ts`: the blocked-hold text is now "This run stopped before it finished. Your saved work is kept." The old text asked people to reconcile. Holdless legacy runs: in the 1,000 staging runs, 0 tasks end on `controller_lease_lost` or `process_lost` (every one has a later run). 12 end on `server_shutdown_interrupted` with no retry scheduled (attempt 0). On staging now, 9 of those 12 sit `in_progress` with no run and no hold, 1 is done and 2 have a live run. Those 9 belong to the idle-task sweep (#21139). ## Risks - Speed: nothing is added to the normal path before `turn.start`. The fallback runs only on the disposition worker after exact recovery is ruled out, or at wake admission when a hold already defers the wake. The auth middleware reads one more JSON field in the row read it already does. - Behavior shift: tasks that today stay Blocked for a person after an infrastructure failure now continue automatically. A side effect with an unknown outcome is not replayed; the new run is told about it and must check first. - After deploy, the disposition worker continues tasks already blocked by these codes, at most 25 per pass and at most 6 per task per hour. No migration. No manual Retry is needed. - The old executor is not proven stopped before the successor starts. Fencing is: its API writes are refused, its workspace epoch is abandoned, the native `replacementDenied` marker is set, and the successor has a separate run identity. Known gaps (follow-ups): - No quarantine attachment: unverified files stay unapplied in the abandoned workspace root (recorded on the workspace in `remoteWorkspaceAbandonedEpochs`). They are not read into a task attachment, because the sandbox is usually unreachable in these failures. - Agent Chat conversations are excluded at wake admission. They keep their owner-bound continuation. - Under a `reuse_by_environment` lease policy the new allocation can be on the same provider sandbox. It always uses a new root and a new epoch, and the old run cannot publish or write. - Tasks left `in_progress` with no run and no hold (for example after `server_shutdown_interrupted` with no retry scheduled) belong to the idle-task sweep. That sweep's wake reaches this fallback when a hold exists. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits, test runs). ## 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 - [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 --- .../agent-run-authentication.test.ts | 6 +- .../__tests__/assigned-work-invariant.test.ts | 17 +- ...eartbeat-native-restart-suspension.test.ts | 17 +- .../__tests__/issue-monitor-scheduler.test.ts | 41 +- server/src/agent-run-cancellation.ts | 16 +- .../middleware/agent-run-authentication.ts | 3 +- server/src/middleware/auth.ts | 6 +- .../modules/wake-queue/adapters/postgres.ts | 5 +- server/src/services/execution-control-work.ts | 8 +- server/src/services/execution-projection.ts | 17 +- .../services/execution-recovery-resolution.ts | 45 + .../fresh-continuation-fallback.test.ts | 838 ++++++++++++++++++ .../services/fresh-continuation-fallback.ts | 741 ++++++++++++++++ .../services/fresh-workspace-continuation.ts | 6 + server/src/services/heartbeat/queue.ts | 58 +- .../native-controller-host-recovery.ts | 7 +- .../native-remote-retry-admission.test.ts | 2 +- .../native-runtime/native-restart-recovery.ts | 163 +++- ...unner-restart-recovery.integration.test.ts | 95 +- .../task-interruption-presentation.ts | 27 + 20 files changed, 2054 insertions(+), 64 deletions(-) create mode 100644 server/src/services/fresh-continuation-fallback.test.ts create mode 100644 server/src/services/fresh-continuation-fallback.ts diff --git a/server/src/__tests__/agent-run-authentication.test.ts b/server/src/__tests__/agent-run-authentication.test.ts index fe2da4eb363..40c6e79985d 100644 --- a/server/src/__tests__/agent-run-authentication.test.ts +++ b/server/src/__tests__/agent-run-authentication.test.ts @@ -78,12 +78,16 @@ const support = await getEmbeddedPostgresTestSupport(); contextSnapshot: { prompt: payload, conversationMode: true } }).where(eq(heartbeatRuns.id, runId)); const [row] = await loadAgentRunAuthentication(db, input); expect(contract(row)).toEqual(contract(await baseline())); - expect(row.resultJson).toEqual({ executionCancellation: { state: null } }); + expect(row.resultJson).toEqual({ executionCancellation: { state: null }, freshContinuationSupersededAt: null }); expect(row.contextSnapshot).toEqual({ conversationMode: true }); expect(Buffer.byteLength(JSON.stringify(row))).toBeLessThan(512); await db.update(heartbeatRuns).set({ resultJson: { executionCancellation: { state: "requested" } } }) .where(eq(heartbeatRuns.id, runId)); expect(agentRunWritesRevoked((await loadAgentRunAuthentication(db, input))[0])).toBe(true); + // A run that a fresh continuation replaced loses its writes too. + await db.update(heartbeatRuns).set({ status: "failed", resultJson: { freshContinuationSupersededAt: new Date().toISOString() } }) + .where(eq(heartbeatRuns.id, runId)); + expect(agentRunWritesRevoked((await loadAgentRunAuthentication(db, input))[0])).toBe(true); }); it("does not return another company, agent, or run", async () => { diff --git a/server/src/__tests__/assigned-work-invariant.test.ts b/server/src/__tests__/assigned-work-invariant.test.ts index 1f1d296eaed..5dca17b02fe 100644 --- a/server/src/__tests__/assigned-work-invariant.test.ts +++ b/server/src/__tests__/assigned-work-invariant.test.ts @@ -320,11 +320,11 @@ describePostgres("assigned-work invariant sweep", () => { expect(enqueueWakeup).toHaveBeenCalledTimes(3); }, 60_000); - it("with the real wake queue, a hold that defers the continuation leaves a violation that is retried no faster than the cap", async () => { - // Current master without a fresh-continuation fallback: the task's last - // run left a legacy reconciliation hold, so admission defers the ordinary - // continuation wake. Nothing pending is left behind, so it stays a - // violation, is retried with spacing, and never loops faster than the cap. + it("with the real wake queue, a hold reached by the sweep's wake becomes one pending fresh continuation", async () => { + // The task's last run left a legacy reconciliation hold. The sweep's + // ordinary continuation wake reaches the fresh-continuation fallback, + // which settles the hold and records one pending continuation (owned by + // the execution-continuation worker). The next sweep adds no attempt. const f = await seedCompany(); const issueId = await f.issue(); const run = await f.run(issueId, { status: "failed", errorCode: "process_lost", livenessState: "failed" }); @@ -344,9 +344,12 @@ describePostgres("assigned-work invariant sweep", () => { const [entry] = await db.select().from(activityLog).where(and(eq(activityLog.entityId, issueId), eq(activityLog.action, ASSIGNED_WORK_CONTINUED_ACTION))); expect(entry.details).toMatchObject({ outcome: "not_started" }); - // A second sweep right away is spaced, not another attempt. + const [record] = await db.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.sourceIssueId, issueId), + sqlTag`${issueRecoveryActions.evidence}->'freshContinuation' is not null`)); + expect(record!.evidence).toMatchObject({ continuationDelivery: "pending" }); + // A second sweep right away adds no attempt. expect(await heartbeat.checkAssignedWorkInvariant({ companyId: f.companyId, issueId })) - .toMatchObject({ outcome: "deferred_rate_limit", verdict: { kind: "violation" } }); + .not.toMatchObject({ outcome: "repaired" }); expect(await db.select().from(activityLog).where(and(eq(activityLog.entityId, issueId), eq(activityLog.action, ASSIGNED_WORK_CONTINUED_ACTION)))).toHaveLength(1); } finally { diff --git a/server/src/__tests__/heartbeat-native-restart-suspension.test.ts b/server/src/__tests__/heartbeat-native-restart-suspension.test.ts index 0790a358428..ce5753dea9e 100644 --- a/server/src/__tests__/heartbeat-native-restart-suspension.test.ts +++ b/server/src/__tests__/heartbeat-native-restart-suspension.test.ts @@ -934,7 +934,10 @@ describeEmbeddedPostgres("heartbeat native recovery interrupted by graceful shut try { const dispositions = await claimNativeRestartRecoveries({ db: f.db, restartKind: "hard", runIds: [f.runId], onClaim }); expect(probe.observed).toEqual([]); - expect(dispositions).toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_process_space_unverified" }]); + // Only a lapsed lease starts the bounded wait that ends the run. + expect(dispositions).toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_process_space_unverified", + // Every wait is rechecked; only a lapsed lease starts the bounded end. + retryAt: expect.any(Date) }]); expect(onClaim).not.toHaveBeenCalled(); const [after] = await f.db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)); expect(after).toMatchObject({ leaseOwner: before.leaseOwner, leaseExpiresAt: before.leaseExpiresAt, @@ -959,7 +962,7 @@ describeEmbeddedPostgres("heartbeat native recovery interrupted by graceful shut const probe = observeOwnerPid(), onClaim = vi.fn(); try { expect(await claimNativeRestartRecoveries({ db: f.db, restartKind: "hard", runIds: [f.runId], onClaim })) - .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_process_space_unverified" }]); + .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_process_space_unverified", retryAt: expect.any(Date) }]); expect(probe.observed).toEqual([]); expect(onClaim).not.toHaveBeenCalled(); const [after] = await f.db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)); @@ -1018,7 +1021,7 @@ describeEmbeddedPostgres("heartbeat native recovery interrupted by graceful shut controllerProcessStartedAt: current.processStartedAt }).where(eq(nativeRunFinalizations.runId, f.runId)); const onClaim = vi.fn(); const dispositions = await claimNativeRestartRecoveries({ db: f.db, restartKind: "hard", runIds: [f.runId], onClaim }); - expect(dispositions).toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_still_alive" }]); + expect(dispositions).toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_still_alive", retryAt: expect.any(Date) }]); expect(onClaim).not.toHaveBeenCalled(); }, 60_000); @@ -1146,7 +1149,7 @@ describeEmbeddedPostgres("heartbeat native recovery interrupted by graceful shut const probe = observeOwnerPid(); try { expect(await claimNativeRestartRecoveries({ db: f.db, restartKind: "hard", runIds: [f.runId] })) - .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "native_finalization_or_cleanup_owner" }]); + .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "native_finalization_or_cleanup_owner", retryAt: expect.any(Date) }]); expect(probe.observed).toEqual([]); expect(await f.db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId))).toEqual([]); } finally { probe.restore(); } @@ -1161,7 +1164,7 @@ describeEmbeddedPostgres("heartbeat native recovery interrupted by graceful shut const probe = observeOwnerPid(); try { expect(await claimNativeRestartRecoveries({ db: f.db, restartKind: "hard", runIds: [f.runId] })) - .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "remote_controller_process_space_unverified" }]); + .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "remote_controller_process_space_unverified", retryAt: expect.any(Date) }]); expect(probe.observed).toEqual([]); const [action] = await f.db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId)); expect(action.evidence.controllerAuthority).toBeUndefined(); @@ -1545,7 +1548,7 @@ describeEmbeddedPostgres("heartbeat native recovery interrupted by graceful shut const probe = observeOwnerPid(); try { expect(await claimNativeRestartRecoveries({ db: f.db, restartKind: "hard", runIds: [f.runId] })) - .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "remote_controller_process_space_unverified" }]); + .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "remote_controller_process_space_unverified", retryAt: expect.any(Date) }]); expect(probe.observed).toEqual([]); const [action] = await f.db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId)); expect(action.evidence.controllerAuthority).toBeUndefined(); @@ -1561,7 +1564,7 @@ describeEmbeddedPostgres("heartbeat native recovery interrupted by graceful shut const unreadable = vi.spyOn(controllerProcess, "currentProcessSpaceHash").mockReturnValue("unknown"); try { expect(await claimNativeRestartRecoveries({ db: f.db, restartKind: "hard", runIds: [f.runId] })) - .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_process_space_unverified" }]); + .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_process_space_unverified", retryAt: expect.any(Date) }]); } finally { unreadable.mockRestore(); } const [attention] = await f.db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId)); const probe = observeOwnerPid(); diff --git a/server/src/__tests__/issue-monitor-scheduler.test.ts b/server/src/__tests__/issue-monitor-scheduler.test.ts index 3915b80fcad..75b3973a6eb 100644 --- a/server/src/__tests__/issue-monitor-scheduler.test.ts +++ b/server/src/__tests__/issue-monitor-scheduler.test.ts @@ -28,6 +28,7 @@ import { startEmbeddedPostgresTestDatabase, } from "./helpers/embedded-postgres.js"; import { heartbeatService } from "../services/heartbeat.ts"; +import { deliverReconciledExecutions } from "../services/execution-recovery-resolution.ts"; import { normalizeIssueExecutionPolicy, parseIssueExecutionState } from "../services/issue-execution-policy.ts"; import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js"; @@ -329,8 +330,11 @@ describeEmbeddedPostgres("issue monitor scheduler", () => { expect((await db.select().from(agentWakeupRequests)).filter(wake => wake.reason === "issue_monitor_due")).toHaveLength(1); }); - it("explains held monitor dispatch without replaying uncertain execution", async () => { - const { companyId, issueId, agentId, nextCheckAt } = await seedFixture(); + // Before the fresh-continuation fallback this hold deferred the monitor for + // a person. The due monitor is an ordinary continuation: it now settles the + // hold and starts one fresh run, without replaying the interrupted execution. + it("continues a held task in a fresh run when its monitor is due, without replaying uncertain execution", async () => { + const { companyId, issueId, agentId } = await seedFixture(); const sourceRunId = randomUUID(); await db.insert(heartbeatRuns).values({ id: sourceRunId, companyId, agentId, runtimeMode: "legacy", status: "interrupted", errorCode: "process_lost", @@ -341,26 +345,19 @@ describeEmbeddedPostgres("issue monitor scheduler", () => { evidence: { runId: sourceRunId }, nextAction: "Inspect the interrupted execution before continuing." }).returning(); const heartbeat = heartbeatService(db); const tickAt = new Date("2026-04-11T12:31:00.000Z"); - expect((await heartbeat.tickTimers(tickAt)).enqueued).toBe(0); - expect((await heartbeat.tickTimers(new Date(tickAt.getTime() + 30_000))).enqueued).toBe(0); - const [waiting] = await db.select().from(issues).where(eq(issues.id, issueId)); - expect(waiting.monitorNextCheckAt).toEqual(nextCheckAt); - expect(waiting.monitorWakeRequestedAt).toBeNull(); - expect(waiting.monitorAttemptCount).toBe(0); - expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId))).toHaveLength(1); - const diagnostics = (await db.select().from(activityLog).where(eq(activityLog.entityId, issueId))) - .filter(row => row.action === "issue.monitor_deferred"); - expect(diagnostics).toHaveLength(1); - expect(diagnostics[0]?.details).toMatchObject({ nextCheckAt: nextCheckAt.toISOString(), - reason: "execution_reconciliation_required", blockerCause: "legacy_execution_requires_reconciliation", attemptCount: 0 }); - expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, hold!.id)))[0]?.status).toBe("active"); - await db.update(issueRecoveryActions).set({ status: "resolved", resolvedAt: new Date(), - evidence: { runId: sourceRunId, executionReconciliation: { action: "continue" } } }).where(eq(issueRecoveryActions.id, hold!.id)); - expect((await heartbeat.tickTimers(new Date(tickAt.getTime() + 60_000))).enqueued).toBe(1); - expect((await heartbeat.tickTimers(new Date(tickAt.getTime() + 90_000))).enqueued).toBe(0); - const [triggered] = await db.select().from(issues).where(eq(issues.id, issueId)); - expect(triggered.monitorAttemptCount).toBe(1); - expect(triggered.monitorNextCheckAt).toBeNull(); + // The due monitor reaches the fallback, which records one pending fresh + // continuation and coalesces the monitor wake into it. + await heartbeat.tickTimers(tickAt); + const [settled] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, hold!.id)); + expect(settled).toMatchObject({ status: "resolved", outcome: "restored" }); + expect(settled!.evidence).toMatchObject({ continuationDelivery: "pending", + freshContinuation: { sourceRunId, trigger: "continuation_wake" } }); + // The continuation worker starts it once, as a fresh session. + await deliverReconciledExecutions(db, heartbeat.wakeup); + await deliverReconciledExecutions(db, heartbeat.wakeup); + const successors = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, sourceRunId)); + expect(successors).toHaveLength(1); + expect(successors[0]!.contextSnapshot).toMatchObject({ forceFreshSession: true, previousRunId: sourceRunId }); }); it("recovers a rejected native monitor call and delivers the corrected schedule once", async () => { diff --git a/server/src/agent-run-cancellation.ts b/server/src/agent-run-cancellation.ts index b49e7155848..6d65bae980f 100644 --- a/server/src/agent-run-cancellation.ts +++ b/server/src/agent-run-cancellation.ts @@ -2,16 +2,25 @@ import { and, eq, inArray } from "drizzle-orm"; import { caseHandoffs, heartbeatRuns, type Db } from "@paperclipai/db"; import { forbidden } from "./errors.js"; -/** Stop revokes write authority before waiting for the executor to settle. */ +/** Stop revokes write authority before waiting for the executor to settle. + * A run that a fresh continuation replaced loses it too: its agent may still + * be alive in an unreachable sandbox, and only the new run acts on the task. */ export function agentRunWritesRevoked(run: { status: string; resultJson?: Record | null; } | null | undefined): boolean { const cancellation = run?.resultJson?.executionCancellation; - return run?.status === "cancelled" || Boolean(cancellation && typeof cancellation === "object" + return run?.status === "cancelled" || agentRunSupersededByFreshContinuation(run) || Boolean(cancellation && typeof cancellation === "object" && "state" in cancellation && cancellation.state === "requested"); } +/** Recorded by the fresh-continuation fallback on the run it replaced. */ +export const FRESH_CONTINUATION_SUPERSEDED_KEY = "freshContinuationSupersededAt"; + +export function agentRunSupersededByFreshContinuation(run: { resultJson?: Record | null } | null | undefined) { + return typeof run?.resultJson?.[FRESH_CONTINUATION_SUPERSEDED_KEY] === "string"; +} + /** The caller must supply its write transaction, so Stop and commit serialize. */ export async function assertAgentRunWriteAllowed(tx: Db, companyId: string, actor: { agentId?: string | null; @@ -27,6 +36,9 @@ export async function assertAgentRunWriteAllowed(tx: Db, companyId: string, acto .for("share"); const stoppedForThisMutation = run?.status === "cancelled" && actor.stopId && run.resultJson?.issueMutationStopId === actor.stopId; + if (agentRunSupersededByFreshContinuation(run)) { + throw forbidden("A newer run continues this task. End the turn.", { code: "agent_run_superseded" }); + } if (agentRunWritesRevoked(run) && !stoppedForThisMutation) { throw forbidden("This run was cancelled", { code: "agent_run_cancelled" }); } diff --git a/server/src/middleware/agent-run-authentication.ts b/server/src/middleware/agent-run-authentication.ts index d130e9e706b..58634b3702b 100644 --- a/server/src/middleware/agent-run-authentication.ts +++ b/server/src/middleware/agent-run-authentication.ts @@ -13,7 +13,8 @@ export function loadAgentRunAuthentication(db: Db, input: { resultJson: sql>`jsonb_build_object( 'executionCancellation', jsonb_build_object( 'state', ${heartbeatRuns.resultJson}->'executionCancellation'->'state' - ) + ), + 'freshContinuationSupersededAt', ${heartbeatRuns.resultJson}->'freshContinuationSupersededAt' )`, contextSnapshot: sql>`jsonb_build_object( 'conversationMode', ${heartbeatRuns.contextSnapshot}->'conversationMode' diff --git a/server/src/middleware/auth.ts b/server/src/middleware/auth.ts index 60ca593d153..c55103703b2 100644 --- a/server/src/middleware/auth.ts +++ b/server/src/middleware/auth.ts @@ -23,7 +23,7 @@ import { rekeyCompanyIssueIdentifiers, } from "../services/issue-prefix.js"; import { verifyLocalAgentJwt } from "../agent-auth-jwt.js"; -import { agentRunWritesRevoked } from "../agent-run-cancellation.js"; +import { agentRunSupersededByFreshContinuation, agentRunWritesRevoked } from "../agent-run-cancellation.js"; import { loadAgentRunAuthentication } from "./agent-run-authentication.js"; import { isUuidLike, normalizeAgentApiKeyScope, type DeploymentMode } from "@paperclipai/shared"; import type { BetterAuthSessionResult } from "../auth/better-auth.js"; @@ -405,6 +405,10 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa if (agentRunWritesRevoked(identityRun) && !["GET", "HEAD", "OPTIONS"].includes(req.method)) { const conversation = identityRun?.contextSnapshot?.conversationMode === true; + if (agentRunSupersededByFreshContinuation(identityRun)) { + _res.status(403).json({ error: "A newer run continues this task. End the turn.", code: "agent_run_superseded" }); + return; + } _res.status(403).json({ error: conversation ? "This conversation turn was cancelled" : "This run was cancelled", code: conversation ? "conversation_turn_cancelled" : "agent_run_cancelled" }); return; diff --git a/server/src/modules/wake-queue/adapters/postgres.ts b/server/src/modules/wake-queue/adapters/postgres.ts index 59dce5b560f..95341f6bf18 100644 --- a/server/src/modules/wake-queue/adapters/postgres.ts +++ b/server/src/modules/wake-queue/adapters/postgres.ts @@ -927,8 +927,9 @@ async function recordNativeTerminalRecoveryIfNeeded(tx: Db, run: ReleaseRun, iss cause: "native_continuation_requires_reconciliation", fingerprint: `native-continuation:${run.id}`, evidence: { runId: run.id, originalFailureCode: run.errorCode, ...(nativeFailureBlock ? { nativeFailureBlock } : {}) }, - nextAction: - "Inspect the original failure and reconcile the previous execution before continuing. Automatic recovery cannot start another incident.", + // The fresh-continuation fallback settles this hold unless its cause is + // the person's; the text never asks anyone to repair the run. + nextAction: "The run stopped before it finished. Paperclip continues the task from its last saved work.", maxAttempts: 3, wakePolicy: null, supersedeOnIdentityChange: true, diff --git a/server/src/services/execution-control-work.ts b/server/src/services/execution-control-work.ts index b0c7ca75ce7..69981ba1647 100644 --- a/server/src/services/execution-control-work.ts +++ b/server/src/services/execution-control-work.ts @@ -5,6 +5,7 @@ import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator. import { type DeliveryQueue } from "./delivery-work-notifications.js"; import { EXECUTION_RECONCILIATION_INTERVAL_MS } from "./execution-control-deadline.js"; import { obsoleteExecutionConversationHold, unresolvedExecutionDispositions } from "./execution-recovery-resolution.js"; +import { heldExecutionsAwaitingFreshContinuation, nextFreshContinuationCheckAt } from "./fresh-continuation-fallback.js"; import { hasPendingNativeReplacements } from "./native-runtime/native-safe-replacement.js"; import { nextAbandonedNativeOwnerReleaseAt } from "./native-runtime/native-failed-run-owner-release.js"; import { hasPendingPauseResume } from "./issue-tree-resume.js"; @@ -103,11 +104,14 @@ export function executionControlSchedule(db: Db) { return rows.length ? retry() : null; }, async disposition() { - const [conversation, execution] = await Promise.all([ + const now = new Date(); + const [conversation, execution, held, nextCheck] = await Promise.all([ db.select({ id: issueRecoveryActions.id }).from(issueRecoveryActions).where(obsoleteExecutionConversationHold()).limit(1), unresolvedExecutionDispositions(db, 1), + heldExecutionsAwaitingFreshContinuation(db, now, 1), + nextFreshContinuationCheckAt(db), ]); - return conversation.length || execution.length ? retry() : null; + return conversation.length || execution.length || held.length ? retry() : deadline([nextCheck ? new Date(nextCheck) : null]); }, async localLogin() { const rows = await db.select({ at: adapterAuthSessions.expiresAt }).from(adapterAuthSessions).where(and( diff --git a/server/src/services/execution-projection.ts b/server/src/services/execution-projection.ts index 8eb8ad22eac..06a351c7162 100644 --- a/server/src/services/execution-projection.ts +++ b/server/src/services/execution-projection.ts @@ -360,10 +360,16 @@ export function projectExecution( ) { if (recoveryAction.evidence.continuationDelivery === "invalidated") { projection.cause = "continuation_ownership_changed"; - projection.nextAction = - "The task was closed or reassigned before delivery. Inspect the current task owner and status."; + projection.nextAction = "The task changed before this continuation started, so it was not started."; return set("failed", "Continuation cancelled"); } + // A hold the fresh-continuation fallback settled together with another: + // the task continues through that record. + if (recoveryAction.evidence.continuationDelivery === "coalesced") { + projection.cause = null; + projection.nextAction = "Paperclip continues the task in a fresh run from its saved work."; + return set("queued", "Continuing automatically"); + } const reconciliation = recoveryAction.evidence.executionReconciliation; if (recoveryAction.cause === "native_restart_recovery_blocked" && recoveryAction.evidence.reason === "controller_process_space_unverified" @@ -390,10 +396,13 @@ export function projectExecution( projection.cause = null; projection.nextAction = deliveredRunId ? null - : "The previous execution is reconciled. Its continuation is queued for delivery."; + : recoveryAction.evidence.freshContinuationSettlement + ? "Paperclip continues the task in a fresh run from its saved work." + : "The previous execution is reconciled. Its continuation is queued for delivery."; return set( deliveredRunId ? "completed" : "queued", - deliveredRunId ? "Continued in another run" : "Continuation queued", + deliveredRunId ? "Continued in another run" + : recoveryAction.evidence.freshContinuationSettlement ? "Continuing automatically" : "Continuation queued", ); } if ( diff --git a/server/src/services/execution-recovery-resolution.ts b/server/src/services/execution-recovery-resolution.ts index e59f05c18f5..5002ee9c15f 100644 --- a/server/src/services/execution-recovery-resolution.ts +++ b/server/src/services/execution-recovery-resolution.ts @@ -36,6 +36,8 @@ import { hasRequiredWorkspaceRecovery } from "./workspace-restore-recovery-state import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js"; import { readSystemRecovery } from "./system-recovery-state.js"; import { provenGoneLegacyControllerBootId } from "./legacy-controller-lease.js"; +import { continueFreshInTransaction, continueHeldExecutions, freshContinuationCheckDue, recordFreshContinuationCheck, + settleCoalescedFreshContinuationHolds } from "./fresh-continuation-fallback.js"; import { alias } from "drizzle-orm/pg-core"; /** An operator records observed outcomes; this is not permission to blindly retry. */ @@ -397,8 +399,28 @@ export async function deliverReconciledExecutions( evidence: sql`${issueRecoveryActions.evidence} || '{"continuationDelivery":"invalidated"}'::jsonb`, }) .where(pendingDecision); + await settleCoalescedFreshContinuationHolds(db, { companyId: action.companyId, primaryId: action.id, delivery: "invalidated" }); continue; } + // A fresh continuation is the task's next run only while nothing else + // started one: a person's Retry or saved input that ran since it was + // recorded already continues the task, so it is never a second run. + const fresh = action.evidence.freshContinuation as { recordedAt?: unknown } | undefined; + if (fresh && typeof fresh.recordedAt === "string") { + const [newer] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, action.companyId), sql`${heartbeatRuns.id}::text <> ${decision.runId}`, + or(eq(heartbeatRuns.nativeIssueId, task.id), eq(heartbeatRuns.issueId, task.id), + sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${task.id}::text`), + sql`${heartbeatRuns.createdAt} >= ${fresh.recordedAt}::timestamptz`)).limit(1); + if (newer) { + await db.update(issueRecoveryActions).set({ evidence: sql`${issueRecoveryActions.evidence} || ${JSON.stringify( + { continuationDelivery: "delivered", continuationRunId: newer.id, continuationSupersededByRun: true })}::jsonb` }) + .where(pendingDecision); + await settleCoalescedFreshContinuationHolds(db, { companyId: action.companyId, primaryId: action.id, + delivery: "delivered", continuationRunId: newer.id }); + continue; + } + } const run = await wake(action.returnOwnerAgentId, { source: "automation", triggerDetail: "system", @@ -416,6 +438,8 @@ export async function deliverReconciledExecutions( forceFreshSession: true, wakeReason: "issue_recovery_action_restored", source: "execution.reconciled", + ...((action.evidence.freshContinuation as { isolation?: unknown } | undefined)?.isolation === "fresh_isolated_workspace" + ? { freshContinuationIsolation: action.id } : {}), }, }); if (run) @@ -443,6 +467,8 @@ export async function deliverReconciledExecutions( )}::jsonb`, }) .where(pendingDecision); + await settleCoalescedFreshContinuationHolds(tx as unknown as Db, { companyId: action.companyId, primaryId: action.id, + delivery: "delivered", continuationRunId: run.id }); }); } catch { logger.warn( @@ -499,6 +525,8 @@ export function unresolvedExecutionDispositions(db: Db, limit: number) { sql`not (${issueRecoveryActions.evidence} ? 'systemRecovery')`, inArray(issueRecoveryActions.status, ["active", "escalated"]), eq(issueRecoveryActions.kind, "active_run_watchdog"), + // A fresh continuation that backed off is checked again when due. + freshContinuationCheckDue(new Date()), or(inArray(issueRecoveryActions.cause, [...EXECUTION_RECONCILIATION_CAUSES]), and( eq(heartbeatRuns.runtimeMode, "native"), eq(heartbeatRuns.nativePhase, "terminal_failure"), eq(nativeRunFinalizations.phase, "terminal_failure"), isNull(nativeRunFinalizations.nextAttemptAt), @@ -700,6 +728,20 @@ export async function settleUnrecoverableExecutions( !["done", "cancelled"].includes(task.status) && (!task.executionRunId || task.executionRunId === run.id) && (!task.checkoutRunId || task.checkoutRunId === run.id); + // Exact recovery is ruled out. Unless the cause is the person's, the + // task continues in a fresh run from its last saved work instead of + // waiting for a person. + // A preparation that never started provider work keeps its own replay + // lane, which takes over the settled hold; the held sweep follows it. + if (current && !isInterruptedNativePreparationCandidate(run)) { + const fresh = await continueFreshInTransaction(tx as unknown as Db, { companyId: task.companyId, runId: run.id, + trigger: "recovery_refused", now }); + if (["continued", "already_continued", "successor_exists"].includes(fresh.kind)) return; + if (fresh.kind === "backoff" || fresh.kind === "exact_recovery_pending") { + await recordFreshContinuationCheck(tx as unknown as Db, { companyId: task.companyId, actionId: action.id }, fresh, now); + return; + } + } const note = executionRecoverySettlementNote({ current, cause: action.cause, workspaceRestoreFailed: hasWorkspaceRestoreFailure(run.resultJson), trigger: action.evidence.trigger }); await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: task.companyId, issueId: task.id }); @@ -803,4 +845,7 @@ export async function settleUnrecoverableExecutions( ); } } + // Tasks already held by settled records (including those older releases + // saved) continue from their saved work on this worker too. + await continueHeldExecutions(db, now); } diff --git a/server/src/services/fresh-continuation-fallback.test.ts b/server/src/services/fresh-continuation-fallback.test.ts new file mode 100644 index 00000000000..21a67499d96 --- /dev/null +++ b/server/src/services/fresh-continuation-fallback.test.ts @@ -0,0 +1,838 @@ +import { randomUUID } from "node:crypto"; +import { and, eq, sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { + activityLog, agentWakeupRequests, agents, approvals, authUsers, companies, createDb, environmentLeases, environments, executionWorkspaces, heartbeatRuns, issueApprovals, issueRecoveryActions, issueThreadInteractions, + issues, nativeRunFinalizations, toolInvocations, +} from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; +import { deliverReconciledExecutions, settleUnrecoverableExecutions } from "./execution-recovery-resolution.js"; +import { getExecutionBlocker } from "./execution-blocker.js"; +import { + FRESH_CONTINUATIONS_PER_HOUR, FRESH_CONTINUATION_SCHEMA, PERSON_OWNED_FAILURE_CODES, continueHeldExecutions, ensureFreshContinuation, + freshContinuationNote, heldExecutionsAwaitingFreshContinuation, nextFreshContinuationCheckAt, recordFreshContinuationCheck, FRESH_CONTINUATION_PENDING_BOUND_MS, FRESH_CONTINUATION_PROGRESS_BOUND_MS, FRESH_CONTINUATION_SAVED_WORK_BOUND_MS, +} from "./fresh-continuation-fallback.js"; +import { heartbeatService } from "./heartbeat.js"; +import { buildExecutionContinuation } from "./execution-continuation.js"; +import { currentProcessSpaceHash } from "./controller-process-identity.js"; +import { executionControlSchedule } from "./execution-control-work.js"; +import { readFreshWorkspaceReadiness } from "./fresh-workspace-continuation.js"; +import { taskInterruptionPresentation } from "./task-interruption-presentation.js"; +import { agentRunWritesRevoked, assertAgentRunWriteAllowed } from "../agent-run-cancellation.js"; +import { loadAgentRunAuthentication } from "../middleware/agent-run-authentication.js"; +import { SERVER_RESTART_RETRY_MAX_ATTEMPTS, SERVER_RESTART_RETRY_WINDOW_MS } from "./execution-recovery-attempt.js"; +import { FRESH_CONTINUATION_WINDOW_MS } from "./fresh-continuation-fallback.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const suite = support.supported ? describe : describe.skip; + +// Copy shown to people never asks them to inspect or repair a sandbox, workspace or run. +const adminText = /sandbox|inspect|repair|administrator|reconcile/i; + +type Seed = { + runtime: "native" | "legacy"; status?: "failed" | "interrupted" | "timed_out" | "cancelled"; + errorCode: string; error?: string; + /** How today's code leaves the run: an active hold (before disposition) or a settled-but-blocked hold (older releases). */ + hold?: "active" | "settled_blocked" | "none"; + coordinatorState?: string; +}; + +suite("fresh-continuation fallback", () => { + let db!: ReturnType; + let temporary: Awaited> | null = null; + let companyId = "", agentId = "", userId = ""; + + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("paperclip-fresh-continuation-"); + db = createDb(temporary.connectionString); + companyId = randomUUID(); agentId = randomUUID(); userId = randomUUID(); + await db.insert(authUsers).values({ id: userId, name: "Board", email: `${userId}@example.test`, + emailVerified: true, createdAt: new Date(), updatedAt: new Date() }); + await db.insert(companies).values({ id: companyId, name: "Paperclip", issuePrefix: "FCF", + requireBoardApprovalForNewAgents: false, defaultResponsibleUserId: userId }); + await db.insert(agents).values({ id: agentId, companyId, name: "Coder", role: "engineer", status: "idle", + adapterType: "paperclip_runner", adapterConfig: {}, runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } }, permissions: {} }); + }, 60_000); + + afterEach(async () => { + await db.execute(sql`truncate table issue_recovery_actions, native_run_finalizations, tool_invocations, + issue_approvals, approvals, issue_thread_interactions, activity_log, agent_wakeup_requests, environment_leases, execution_workspaces, heartbeat_runs, issues cascade`); + }); + + afterAll(async () => { await db?.$client.end(); await temporary?.cleanup(); }); + + /** A run that ended without finishing, in the shape today's release leaves it. */ + async function unfinishedRun(seed: Seed) { + const issueId = randomUUID(), runId = randomUUID(); + const finishedAt = new Date(Date.now() - 60_000); + await db.insert(issues).values({ id: issueId, companyId, title: "Ship the release notes", status: "blocked", + assigneeAgentId: agentId, statusVersion: 4, blockedTransitionAt: finishedAt }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "assignment", issueId, + nativeIssueId: seed.runtime === "native" ? issueId : null, runtimeMode: seed.runtime, + status: seed.status ?? "failed", errorCode: seed.errorCode, error: seed.error ?? seed.errorCode, + startedAt: new Date(finishedAt.getTime() - 10 * 60_000), finishedAt, createdAt: new Date(finishedAt.getTime() - 11 * 60_000), + responsibleUserId: userId, contextSnapshot: { issueId, wakeReason: "issue_assigned" }, + ...(seed.runtime === "native" ? { nativePhase: "terminal_failure" } + : { runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner" } } }) }); + if (seed.runtime === "native") { + await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "terminal_failure", + recoveryState: seed.coordinatorState ?? "blocked", failureCode: "native_continuation_requires_reconciliation", leaseOwner: null }); + } + let actionId: string | null = null; + if ((seed.hold ?? "active") !== "none") { + const native = seed.runtime === "native"; + const settled = seed.hold === "settled_blocked"; + const [action] = await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issueId, kind: "active_run_watchdog", + status: settled ? "resolved" : "active", outcome: settled ? "blocked" : null, resolvedAt: settled ? finishedAt : null, + ownerType: "board", returnOwnerAgentId: agentId, + cause: native ? "native_continuation_requires_reconciliation" : "legacy_execution_requires_reconciliation", + fingerprint: native ? `native-continuation:${runId}` : `legacy-execution:${runId}`, + nextAction: "Inspect the original failure and reconcile the previous execution before continuing. Automatic recovery cannot start another incident.", + maxAttempts: 3, createdAt: finishedAt, + evidence: { runId, originalFailureCode: seed.errorCode, nativeFailureBlock: { runId, statusVersion: 4 }, + ...(settled ? { automaticRecovery: { policy: "preserve_without_replay_v1", runId, replay: "blocked", + actionOutcome: "unknown", recordedAt: finishedAt.toISOString() } } : {}) } }).returning(); + actionId = action!.id; + } + return { issueId, runId, actionId }; + } + + const issue = async (id: string) => (await db.select().from(issues).where(eq(issues.id, id)))[0]!; + const successors = async (runId: string) => db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId)); + /** Keeps the agent's only slot busy, so a delivered continuation stays observable as queued. */ + async function occupySlot() { + const [other] = await db.insert(issues).values({ companyId, title: "Other work", status: "in_progress", assigneeAgentId: agentId }).returning(); + await db.insert(heartbeatRuns).values({ companyId, agentId, issueId: other!.id, status: "running", contextSnapshot: { issueId: other!.id } }); + } + async function deliver() { + const heartbeat = heartbeatService(db); + await deliverReconciledExecutions(db, heartbeat.wakeup); + await deliverReconciledExecutions(db, heartbeat.wakeup); + } + + async function expectOneFreshSuccessor(f: { issueId: string; runId: string }) { + expect(await getExecutionBlocker(db, companyId, f.issueId)).toBeNull(); + expect(await issue(f.issueId)).toMatchObject({ status: "todo" }); + await occupySlot(); + await deliver(); + const next = await successors(f.runId); + expect(next).toHaveLength(1); + expect(next[0]!.contextSnapshot).toMatchObject({ issueId: f.issueId, previousRunId: f.runId, forceFreshSession: true, + wakeReason: "issue_recovery_action_restored" }); + const [record] = await db.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.sourceIssueId, f.issueId), + sql`${issueRecoveryActions.evidence}->'freshContinuation' is not null`)); + expect(record!.evidence).toMatchObject({ continuationDelivery: "delivered", continuationRunId: next[0]!.id, + freshContinuation: { schema: FRESH_CONTINUATION_SCHEMA, sourceRunId: f.runId }, + executionReconciliation: { runId: f.runId, providerStopped: true, actionOutcome: "mixed" } }); + expect(record!.nextAction).not.toMatch(adminText); + expect(record!.ownerType).toBe("system"); + return next[0]!; + } + + // The five most frequent endings on staging (2026-11-12): each left the task + // Blocked for a person with no successor run. + it.each([ + { errorCode: "native_continuation_requires_reconciliation", error: "runner_remote_process_identity_unavailable", runtime: "native" as const }, + { errorCode: "controller_lease_lost", error: "Legacy controller lease lost", runtime: "legacy" as const }, + { errorCode: "process_lost", error: "Process lost -- server may have restarted; retrying once", runtime: "legacy" as const }, + { errorCode: "server_shutdown_interrupted", error: "Interrupted by graceful server shutdown (SIGTERM)", runtime: "legacy" as const, + status: "interrupted" as const }, + { errorCode: "native_session_interrupted", error: "runner_ingress_auth_failed: Runner ingress did not complete PRP authentication", + runtime: "native" as const }, + ])("continues a task whose run ended with $errorCode in exactly one fresh run from saved work", async seed => { + const f = await unfinishedRun(seed); + await settleUnrecoverableExecutions(db); + const hold = (await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)))[0]!; + expect(hold).toMatchObject({ status: "resolved", outcome: "restored" }); + expect(hold.evidence.automaticRecovery).toBeUndefined(); + await expectOneFreshSuccessor(f); + }, 60_000); + + // The only native swap failure left on a later staging swap: the Runner + // resumed a harness that was not suspended or was gone. + // Exact resume is fixed elsewhere; whatever still fails must fall back. + it.each([ + { errorCode: "native_session_interrupted", + error: "runner_ingress_unavailable: runnerd process failed: runner_harness_state_mismatch: resumed_not_suspended" }, + { errorCode: "native_session_interrupted", + error: "runner_ingress_unavailable: runnerd process failed: runner_harness_state_mismatch: resumed_unavailable" }, + { errorCode: "runner_harness_state_mismatch", error: "runner_harness_state_mismatch: resumed_unavailable" }, + ])("continues a task whose resumed Runner harness was in the wrong state ($error)", async seed => { + const f = await unfinishedRun({ runtime: "native", ...seed }); + await settleUnrecoverableExecutions(db); + await expectOneFreshSuccessor(f); + }, 60_000); + + // Staging: the person had already pressed Retry, and the automatic successor + // could not carry that authorization forward. That is the system's failure, + // not the person's: the task continues under its responsible user. + it("continues a task whose automatic retry lost the person's continuation authorization", async () => { + expect(PERSON_OWNED_FAILURE_CODES).not.toContain("continuation_user_authorization_missing"); + const f = await unfinishedRun({ runtime: "legacy", errorCode: "continuation_user_authorization_missing", + error: "The automatic retry could not revalidate the original user continuation" }); + await settleUnrecoverableExecutions(db); + const next = await expectOneFreshSuccessor(f); + expect(next.responsibleUserId).toBe(userId); + }, 60_000); + + it("falls back for a failure code nobody has classified yet", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "runner_new_failure_added_next_week" }); + await settleUnrecoverableExecutions(db); + await expectOneFreshSuccessor(f); + }, 60_000); + + it("creates one successor when two servers call it at once", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_continuation_requires_reconciliation", + error: "runner_remote_process_identity_unavailable" }); + const results = await Promise.all([ + ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" }), + ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" }), + settleUnrecoverableExecutions(db).then(() => null), + ]); + expect(results.filter(result => result?.kind === "continued")).toHaveLength(1); + expect(results.filter(result => result && result.kind !== "continued").map(result => result!.kind)) + .toEqual([expect.stringMatching(/already_continued|successor_exists/)]); + await expectOneFreshSuccessor(f); + // A later call, from either server or a sweep, adds nothing. + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "held_recovery" })) + .toMatchObject({ kind: expect.stringMatching(/already_continued|successor_exists/) }); + await deliver(); + expect(await successors(f.runId)).toHaveLength(1); + }, 60_000); + + // Upgrade safety: rows saved by the previous release (a settled-but-blocked + // no-replay hold, its coordinator still awaiting a runner reattach) and a + // task already Blocked continue on the first pass after deploy, without Retry. + it("continues tasks that older releases left blocked by these codes", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_continuation_requires_reconciliation", + error: "runner_remote_process_identity_unavailable", hold: "settled_blocked", coordinatorState: "awaiting_runner_reattach" }); + expect(await getExecutionBlocker(db, companyId, f.issueId)).toMatchObject({ recoveryActionId: f.actionId }); + await settleUnrecoverableExecutions(db); + await expectOneFreshSuccessor(f); + }, 60_000); + + const sweepWake = (issueId: string) => heartbeatService(db).wakeup(agentId, { source: "automation", triggerDetail: "system", + reason: "issue_continuation_needed", payload: { issueId }, requestedByActorType: "system", + requestedByActorId: "idle-task-sweep", contextSnapshot: { issueId, taskId: issueId, wakeReason: "issue_continuation_needed" } }); + const pendingRecord = async (issueId: string) => (await db.select().from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.sourceIssueId, issueId), sql`${issueRecoveryActions.evidence}->'freshContinuation' is not null`)))[0]; + + // An ordinary system wake (the idle-task sweep's) reaches the fallback. The + // continuation is recorded pending and counts as delivered only once a run + // for it exists. + it("records a pending continuation for an ordinary continuation wake and delivers it once", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_continuation_requires_reconciliation", + error: "runner_remote_process_identity_unavailable", hold: "settled_blocked" }); + await occupySlot(); + expect(await sweepWake(f.issueId)).toBeNull(); + expect(await getExecutionBlocker(db, companyId, f.issueId)).toBeNull(); + expect((await pendingRecord(f.issueId))!.evidence).toMatchObject({ continuationDelivery: "pending", + freshContinuation: { sourceRunId: f.runId, trigger: "continuation_wake", delivery: "recorded" } }); + // A second sweep wake adds nothing. + expect(await sweepWake(f.issueId)).toBeNull(); + await deliver(); + expect(await successors(f.runId)).toHaveLength(1); + expect((await pendingRecord(f.issueId))!.evidence.continuationDelivery).toBe("delivered"); + }, 60_000); + + // A gate after the hook must never consume the recovery: it stays pending + // and is delivered once the gate clears. + it("keeps the continuation pending while the agent's daily run limit declines it, then delivers it", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_session_interrupted", hold: "settled_blocked" }); + await db.update(agents).set({ runtimeConfig: { heartbeat: { maxConcurrentRuns: 1, maxDailyRuns: 1 } } }).where(eq(agents.id, agentId)); + try { + // The source run already used today's single run. + expect(await sweepWake(f.issueId)).toBeNull(); + await deliver(); + expect(await successors(f.runId)).toHaveLength(0); + expect((await pendingRecord(f.issueId))!.evidence.continuationDelivery).toBe("pending"); + // The limit clears: the next pass delivers it. + await db.update(agents).set({ runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } } }).where(eq(agents.id, agentId)); + await occupySlot(); + await deliver(); + expect(await successors(f.runId)).toHaveLength(1); + } finally { + await db.update(agents).set({ runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } } }).where(eq(agents.id, agentId)); + } + }, 60_000); + + it("leaves a paused agent's task waiting with that reason, not idle and not consumed", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_session_interrupted", hold: "settled_blocked" }); + await db.update(agents).set({ status: "paused" }).where(eq(agents.id, agentId)); + try { + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "continuation_wake" })) + .toEqual({ kind: "person_owned", reason: "agent_not_available" }); + expect(await pendingRecord(f.issueId)).toBeUndefined(); + expect(await getExecutionBlocker(db, companyId, f.issueId)).toMatchObject({ recoveryActionId: f.actionId }); + } finally { + await db.update(agents).set({ status: "idle" }).where(eq(agents.id, agentId)); + } + }, 60_000); + + // The chaos repro: the agent's only slot is held. The delivered continuation + // waits queued (never lost) and starts as soon as the slot frees. + it("leaves the delivered continuation queued while the agent's slot is full and starts it when the slot frees", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "process_lost" }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + const [other] = await db.insert(issues).values({ companyId, title: "Holds the slot", status: "in_progress", assigneeAgentId: agentId }).returning(); + const [holder] = await db.insert(heartbeatRuns).values({ companyId, agentId, issueId: other!.id, status: "running", + contextSnapshot: { issueId: other!.id } }).returning(); + await deliver(); + const [next] = await successors(f.runId); + expect(next).toMatchObject({ status: "queued" }); + expect((await pendingRecord(f.issueId))!.evidence).toMatchObject({ continuationDelivery: "delivered", continuationRunId: next!.id }); + // The slot frees: the queued continuation is dispatched. + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, holder!.id)); + await heartbeatService(db).resumeQueuedRuns(); + await vi.waitFor(async () => { + const [current] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, next!.id)); + expect(current!.status).not.toBe("queued"); + }, { timeout: 20_000, interval: 100 }); + }, 60_000); + + // The Retry banner never shows while Paperclip is continuing the task itself. + it("presents a task whose continuation is recorded or scheduled as continuing, with no Retry", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_restart_recovery_blocked" }); + const presentation = async () => { + const task = await issue(f.issueId); + return taskInterruptionPresentation(db, { id: task.id, companyId, status: task.status, + assigneeAgentId: task.assigneeAgentId, projectId: task.projectId }); + }; + // A scheduled check (exact recovery still has its chance): a timed wait, no Retry. + await recordFreshContinuationCheck(db, { companyId, actionId: f.actionId! }, + { kind: "exact_recovery_pending", reason: "native_finalizer_active", retryAt: new Date(Date.now() + 60_000) }); + expect(await presentation()).toMatchObject({ state: "retry_scheduled", canRetry: false }); + // Recorded, not yet started: continuing, no Retry. + await db.update(issueRecoveryActions).set({ evidence: sql`${issueRecoveryActions.evidence} - 'freshContinuationCheck'` }) + .where(eq(issueRecoveryActions.id, f.actionId!)); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + expect(await presentation()).toMatchObject({ state: "working", canRetry: false }); + }, 60_000); + + it("never starts a second run when a person's Retry already continued the task", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "process_lost" }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + // A person's Retry started a run before the continuation was delivered. + const [retry] = await db.insert(heartbeatRuns).values({ companyId, agentId, issueId: f.issueId, nativeIssueId: f.issueId, + status: "queued", contextSnapshot: { issueId: f.issueId, wakeReason: "task_retry" } }).returning(); + await deliver(); + expect(await successors(f.runId)).toHaveLength(0); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.issueId, f.issueId))).toHaveLength(2); + expect((await pendingRecord(f.issueId))!.evidence).toMatchObject({ continuationDelivery: "delivered", continuationRunId: retry!.id }); + }, 60_000); + + /** The continuation's own wake, exactly as the delivery worker sends it, without its pre-check. */ + async function deliveryWake(f: { issueId: string; runId: string }) { + const record = (await pendingRecord(f.issueId))!; + return heartbeatService(db).wakeup(agentId, { source: "automation", triggerDetail: "system", + reason: "issue_recovery_action_restored", idempotencyKey: `execution-reconciliation:${record.id}`, + payload: { issueId: f.issueId, recoveryActionId: record.id }, requestedByActorType: "system", requestedByActorId: "execution-recovery", + contextSnapshot: { issueId: f.issueId, taskId: f.issueId, recoveryActionId: record.id, previousRunId: f.runId, + retryOfRunId: f.runId, forceFreshSession: true, wakeReason: "issue_recovery_action_restored", source: "execution.reconciled" } }); + } + + it("lets a run that started and finished in the delivery window consume the continuation under the task lock", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "process_lost" }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + // Between the worker's pre-check and admission, saved input ran and finished. + const [intervening] = await db.insert(heartbeatRuns).values({ companyId, agentId, issueId: f.issueId, nativeIssueId: f.issueId, + status: "succeeded", finishedAt: new Date(), contextSnapshot: { issueId: f.issueId, wakeReason: "issue_commented" } }).returning(); + await occupySlot(); + expect(await deliveryWake(f)).toBeNull(); + expect(await successors(f.runId)).toHaveLength(0); + expect((await pendingRecord(f.issueId))!.evidence).toMatchObject({ continuationDelivery: "delivered", continuationRunId: intervening!.id }); + }, 60_000); + + it("starts no run for a task that moved to review in the delivery window", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "process_lost" }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + await db.update(issues).set({ status: "in_review" }).where(eq(issues.id, f.issueId)); + await occupySlot(); + expect(await deliveryWake(f)).toBeNull(); + expect(await successors(f.runId)).toHaveLength(0); + expect((await pendingRecord(f.issueId))!.evidence.continuationDelivery).toBe("invalidated"); + }, 60_000); + + it("settles coalesced holds with their primary, so a task back in todo is not shown as working and the sweep sees it", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_session_interrupted" }); + // A second no-replay hold of the same run, settled together with the first. + const [sibling] = await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: f.issueId, kind: "active_run_watchdog", + status: "resolved", outcome: "blocked", ownerType: "board", cause: "native_restart_recovery_blocked", + fingerprint: `native-restart:${f.runId}`, nextAction: "held", resolvedAt: new Date(), + evidence: { runId: f.runId, automaticRecovery: { policy: "preserve_without_replay_v1", runId: f.runId, replay: "blocked" } } }).returning(); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, sibling!.id)))[0]!.evidence.continuationDelivery) + .toBe("coalesced"); + // The task moves to review before delivery: the primary is cancelled, and so is its sibling. + await db.update(issues).set({ status: "in_review" }).where(eq(issues.id, f.issueId)); + await occupySlot(); + expect(await deliveryWake(f)).toBeNull(); + expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, sibling!.id)))[0]!.evidence.continuationDelivery) + .toBe("invalidated"); + // Back to todo with nothing pending: a failed attempt with Retry, not "working". + await db.update(issues).set({ status: "todo" }).where(eq(issues.id, f.issueId)); + const task = await issue(f.issueId); + expect(await taskInterruptionPresentation(db, { id: task.id, companyId, status: task.status, + assigneeAgentId: task.assigneeAgentId, projectId: task.projectId })).toMatchObject({ state: "failed", canRetry: true }); + // The assigned-work sweep sees it as left with nothing pending: inside its + // settle window after the recent change it schedules the recheck, never "ok". + const check = await heartbeatService(db).checkAssignedWorkInvariant({ companyId, issueId: f.issueId }); + expect(["violation", "settling"]).toContain(check?.verdict.kind); + }, 60_000); + + // The agent is told to check, redo what is missing, and ask only through the + // normal approval step; never that someone must restore the previous attempt. + it("guides the agent to check and redo, never to wait for an operator to recover the previous attempt", async () => { + for (const unverified of [[], ["github.merge_pull_request"]]) { + const note = freshContinuationNote({ runId: randomUUID(), unverified, workspace: "restored_last_save" }); + if (unverified.length) expect(note).toContain("first check whether it took effect"); + expect(note).toContain("do it again and continue the task"); + // It does not contradict "do not repeat completed actions": it scopes itself to unknown outcomes. + expect(note).toContain("Completed actions with recorded results are still not repeated"); + expect(note).toContain("request it through the normal approval step"); + expect(note).not.toMatch(/operator|recover its result|execution state|authorize rerunning/i); + } + // The same holds for the continuation context the agent actually receives. + const f = await unfinishedRun({ runtime: "native", errorCode: "native_session_interrupted" }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + const continuation = await buildExecutionContinuation({ db, companyId, issueId: f.issueId, agentId, + context: { previousRunId: f.runId }, summary: null, exposeLowTrustRaw: false }); + const text = JSON.stringify(continuation); + expect(text).toContain("was cut off before it finished"); + expect(text).not.toMatch(/operator must|recover its result|recover .*execution state|authorize rerunning/i); + }, 60_000); + + // A task whose run completes normally gets no fallback activity at all, even + // with an older hold on the task (a run queued across a swap that then ran). + it("leaves a task that completes normally alone, even with an older run's hold", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_continuation_requires_reconciliation", hold: "settled_blocked" }); + const [later] = await db.insert(heartbeatRuns).values({ companyId, agentId, issueId: f.issueId, nativeIssueId: f.issueId, + status: "succeeded", startedAt: new Date(), finishedAt: new Date(), contextSnapshot: { issueId: f.issueId } }).returning(); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "held_recovery" })).toEqual({ kind: "successor_exists" }); + expect(await ensureFreshContinuation(db, { companyId, runId: later!.id, trigger: "held_recovery" })) + .toEqual({ kind: "not_applicable", reason: "run_not_unfinished" }); + await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.issueId)); + await settleUnrecoverableExecutions(db); + await occupySlot(); + expect(await sweepWake(f.issueId)).toBeNull(); + await deliver(); + expect(await pendingRecord(f.issueId)).toBeUndefined(); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.issueId, f.issueId))).toHaveLength(2); + }, 60_000); + + it("starts no run for a task that finished while its continuation was pending", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "process_lost" }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.issueId)); + await deliver(); + expect(await successors(f.runId)).toHaveLength(0); + expect((await pendingRecord(f.issueId))!.evidence.continuationDelivery).toBe("invalidated"); + }, 60_000); + + // Crash between writes: the decision committed, the process died before any + // run was created. Nothing is lost: the next delivery pass starts it. + it("delivers a committed continuation after a crash before its run was created", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "process_lost" }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + expect(await successors(f.runId)).toHaveLength(0); + // A new process: a fresh service instance and worker pass. + await occupySlot(); + await deliver(); + expect(await successors(f.runId)).toHaveLength(1); + }, 60_000); + + // The cut-off run's agent may still be alive in its old, unreachable sandbox. + // Once the continuation is recorded it can neither write to the task through + // the API nor publish its workspace, and the next run restores the last save + // into a new root on a new allocation. + it("fences the cut-off run: its API writes are refused and its workspace epoch is abandoned", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_continuation_requires_reconciliation", + error: "runner_remote_process_identity_unavailable" }); + const workspaceId = randomUUID(), snapshotId = null, leaseId = randomUUID(), environmentId = randomUUID(); + const location = { environmentId, leaseId, providerLeaseId: "sandbox-1", remoteCwd: "/home/daytona/.paperclip-workspaces/a" }; + await db.insert(executionWorkspaces).values({ id: workspaceId, companyId, sourceIssueId: f.issueId, mode: "isolated", + strategyType: "remote", name: "Task workspace", providerType: "remote", providerRef: location.remoteCwd, + metadata: { remoteWorkspace: { schema: "paperclip.remote-workspace.v1", epoch: 3, snapshotId, + source: { kind: "empty" }, location, writerRunId: f.runId, dirty: true } } }); + await db.update(heartbeatRuns).set({ runnerProfileJson: { remoteWorkspace: { schema: "paperclip.remote-workspace-run.v1", + workspaceId, leaseId, providerLeaseId: location.providerLeaseId, remoteCwd: location.remoteCwd, epoch: 3, + state: "prepared", snapshotId } } }).where(eq(heartbeatRuns.id, f.runId)); + // Today a failed run's token still writes. + const [before] = await loadAgentRunAuthentication(db, { runId: f.runId, companyId, agentId }); + expect(agentRunWritesRevoked(before)).toBe(false); + + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + + // The auth middleware's own row read refuses every write of the old token. + const [after] = await loadAgentRunAuthentication(db, { runId: f.runId, companyId, agentId }); + expect(agentRunWritesRevoked(after)).toBe(true); + await expect(db.transaction(tx => assertAgentRunWriteAllowed(tx as unknown as typeof db, companyId, { agentId, runId: f.runId }))) + .rejects.toMatchObject({ status: 403, details: { code: "agent_run_superseded" } }); + // The workspace writer is fenced out and the next preparation starts from the last save in a new root. + const [workspace] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, workspaceId)); + expect(workspace!.metadata!.remoteWorkspace).toMatchObject({ epoch: 4, writerRunId: null, dirty: false, location: null }); + expect(workspace!.providerRef).toBeNull(); + expect(workspace!.metadata!.remoteWorkspaceAbandonedEpochs).toEqual([expect.objectContaining({ epoch: 3, runId: f.runId, location })]); + // The continuation's own token is unaffected. + await occupySlot(); + await deliver(); + const [next] = await successors(f.runId); + await expect(db.transaction(tx => assertAgentRunWriteAllowed(tx as unknown as typeof db, companyId, { agentId, runId: next!.id }))) + .resolves.toBeTruthy(); + }, 60_000); + + // The staging shape: the new server cannot re-reach the old Runner, so the old + // run's sandbox lease is still active (or its cleanup is pending) with no stop + // receipt. The continuation must still start, not wait behind that cleanup. + it.each(["active", "pending_cleanup"] as const)("starts the continuation while the unreachable old lease is %s", async leaseStatus => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_continuation_requires_reconciliation", + error: "runner_remote_process_identity_unavailable" }); + const [environment] = await db.insert(environments).values({ name: `sandbox-${f.runId}`, driver: "sandbox" }).returning(); + await db.insert(environmentLeases).values({ companyId, issueId: f.issueId, heartbeatRunId: f.runId, + environmentId: environment!.id, provider: "daytona", providerLeaseId: `sandbox-${f.runId}`, status: leaseStatus, + leasePolicy: "retain_on_failure", metadata: { remoteCwd: "/home/daytona/work", driver: "sandbox" } }); + await settleUnrecoverableExecutions(db); + await deliver(); + const [next] = await successors(f.runId); + expect(next).toBeTruthy(); + // Admission claims it: it leaves the queue instead of being declined for the old run's cleanup. + await vi.waitFor(async () => { + const [current] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, next!.id)); + expect(current!.status).not.toBe("queued"); + }, { timeout: 20_000, interval: 100 }); + // The abandoned allocation stays fenced: the old run still cannot write. + const [old] = await loadAgentRunAuthentication(db, { runId: f.runId, companyId, agentId }); + expect(agentRunWritesRevoked(old)).toBe(true); + }, 60_000); + + // A legacy run whose local process may still be alive: the continuation must + // never write the same directory. It gets a new isolated workspace and the + // decision records the stop as unproven. + it("gives the continuation a new isolated workspace while the old local writer may be alive", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "controller_lease_lost", error: "Legacy controller lease lost" }); + // Its controller ran on another host (the replaced server), so no probe from here can prove it gone. + await db.update(heartbeatRuns).set({ processPid: 4242, processHostHash: "replaced-server", processStartedAt: new Date(Date.now() - 600_000) }) + .where(eq(heartbeatRuns.id, f.runId)); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued", isolation: "fresh_isolated_workspace" }); + const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)); + expect(hold!.evidence).toMatchObject({ freshContinuation: { isolation: "fresh_isolated_workspace", stopProof: "unproven_isolated" }, + executionReconciliation: { providerStopProof: "isolated" } }); + await occupySlot(); + await deliver(); + const [next] = await successors(f.runId); + expect(next!.contextSnapshot).toMatchObject({ freshContinuationIsolation: f.actionId }); + // Workspace selection gives it a new isolated workspace, never the old directory. + expect(await readFreshWorkspaceReadiness(db, next!)).toEqual({ mode: "fresh_isolated_workspace", retryIntentId: f.actionId, + sourceRunId: f.runId, retainedSourceIds: [] }); + }, 60_000); + + // The recorded process identity (host, PID space, start time) of this process. + const liveIdentity = () => ({ processPid: process.pid, processHostHash: currentProcessSpaceHash(), + processStartedAt: new Date(Date.now() - process.uptime() * 1_000) }); + + /** Moves the recorded start of the pending wait into the past. */ + async function waitedFor(actionId: string, ms: number) { + await db.update(issueRecoveryActions).set({ evidence: sql`jsonb_set(${issueRecoveryActions.evidence}, + '{freshContinuationCheck,firstPendingAt}', to_jsonb(${Date.now() - ms}::bigint))` }).where(eq(issueRecoveryActions.id, actionId)); + } + + it("lets a previous process still running on this host settle first, for about ten minutes at most", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "process_lost" }); + await db.update(heartbeatRuns).set(liveIdentity()).where(eq(heartbeatRuns.id, f.runId)); + const first = await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" }); + expect(first).toMatchObject({ kind: "exact_recovery_pending", reason: "previous_process_running" }); + // Rechecks back off from one minute. + expect((first as { retryAt: Date }).retryAt.getTime()).toBeLessThanOrEqual(Date.now() + 61_000); + await recordFreshContinuationCheck(db, { companyId, actionId: f.actionId! }, first); + const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)); + expect(hold!.evidence.freshContinuationCheck).toMatchObject({ checks: 1, firstPendingAt: expect.any(Number) }); + // Past the bound it stops waiting and continues in a new isolated workspace. + await waitedFor(f.actionId!, FRESH_CONTINUATION_PENDING_BOUND_MS + 1_000); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued", isolation: "fresh_isolated_workspace" }); + }, 60_000); + + it("keeps waiting up to fifteen minutes while the exact-recovery owner shows progress", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "controller_lease_lost" }); + await db.update(heartbeatRuns).set({ controllerLeaseExpiresAt: new Date(Date.now() + 365 * 86_400_000) }) + .where(eq(heartbeatRuns.id, f.runId)); + const waiting = await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" }); + await recordFreshContinuationCheck(db, { companyId, actionId: f.actionId! }, waiting); + await waitedFor(f.actionId!, FRESH_CONTINUATION_PENDING_BOUND_MS + 1_000); + // The owner renewed its lease since the last check: progress. + await db.update(heartbeatRuns).set({ lastOutputAt: new Date(Date.now() + 1_000) }).where(eq(heartbeatRuns.id, f.runId)); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "exact_recovery_pending", reason: "controller_lease_live" }); + await waitedFor(f.actionId!, FRESH_CONTINUATION_PROGRESS_BOUND_MS + 1_000); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued", isolation: "fresh_isolated_workspace" }); + }, 60_000); + + it("does not mistake a recycled PID for the old writer", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "process_lost" }); + // The PID is alive now, but it belongs to a process that started after the old one was recorded. + await db.update(heartbeatRuns).set({ ...liveIdentity(), processStartedAt: new Date("2020-01-01T00:00:00Z") }) + .where(eq(heartbeatRuns.id, f.runId)); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued" }); + }, 60_000); + + /** A saved-work (workspace) recovery generation on the run's hold, as workspace recovery records it. */ + async function savedWorkRecovery(f: { runId: string; actionId: string | null }, state: "awaiting_evidence" | "running") { + const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)); + await db.update(issueRecoveryActions).set({ evidence: { ...hold!.evidence, + systemRecovery: { schema: "paperclip.system-recovery.v1", policyVersion: 1, phase: "reconcile_effects", state, + sourceRunId: f.runId, attempts: 1, retriesUsed: 0, revision: 2, failure: null, intentId: null, deadlineAt: null, + nextAttemptAt: null, firstFailureAt: null, freshAttemptRunId: null, providerCooldownAt: null, + attemptId: randomUUID(), generationId: randomUUID(), preservationOperationIds: [] } } }) + .where(eq(issueRecoveryActions.id, f.actionId!)); + } + + it("bounds a saved-work recovery that is waiting with no progress, on a scheduled deadline", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "server_shutdown_interrupted", status: "interrupted" }); + await savedWorkRecovery(f, "awaiting_evidence"); + // The held-run scan selects it: exact recovery keeps its first chance. + expect(await continueHeldExecutions(db)).toMatchObject({ continued: 0 }); + const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)); + expect(hold!.evidence.freshContinuationCheck).toMatchObject({ kind: "exact_recovery_pending", reason: "saved_work_recovery_running" }); + // With no other event, the worker is scheduled for the next check. + expect(await nextFreshContinuationCheckAt(db)).toBe((hold!.evidence.freshContinuationCheck as { nextCheckAt: number }).nextCheckAt); + // No progress by the bound: the task continues fresh in a new root, and the + // preempted recovery is no longer scheduled (its hold carries the decision), + // so a late result cannot reach the new workspace. + await waitedFor(f.actionId!, FRESH_CONTINUATION_PENDING_BOUND_MS + 1_000); + await db.update(issueRecoveryActions).set({ evidence: sql`jsonb_set(${issueRecoveryActions.evidence}, + '{freshContinuationCheck,nextCheckAt}', to_jsonb(${Date.now() - 1_000}::bigint))` }).where(eq(issueRecoveryActions.id, f.actionId!)); + expect(await continueHeldExecutions(db)).toMatchObject({ continued: 1 }); + const [settled] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)); + expect(settled!.evidence).toMatchObject({ executionReconciliation: { runId: f.runId }, + freshContinuation: { isolation: "fresh_isolated_workspace" } }); + }, 60_000); + + it("lets a running saved-work recovery that keeps advancing use its own budget", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "server_shutdown_interrupted", status: "interrupted" }); + await savedWorkRecovery(f, "running"); + const first = await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "held_recovery" }); + await recordFreshContinuationCheck(db, { companyId, actionId: f.actionId! }, first); + await waitedFor(f.actionId!, FRESH_CONTINUATION_PROGRESS_BOUND_MS + 1_000); + // The recovery advanced (a new attempt) since the last check: it keeps going past 15 minutes. + await db.update(issueRecoveryActions).set({ updatedAt: new Date(Date.now() + 1_000), + evidence: sql`jsonb_set(${issueRecoveryActions.evidence}, '{systemRecovery,attempts}', '2'::jsonb)` }) + .where(eq(issueRecoveryActions.id, f.actionId!)); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "held_recovery" })) + .toMatchObject({ kind: "exact_recovery_pending", reason: "saved_work_recovery_running" }); + // Its 30-minute budget is the cap. + await waitedFor(f.actionId!, FRESH_CONTINUATION_SAVED_WORK_BOUND_MS + 1_000); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "held_recovery" })) + .toMatchObject({ kind: "continued", isolation: "fresh_isolated_workspace" }); + }, 60_000); + + it("bounds every exact-recovery wait, here a controller lease that never lapses", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "controller_lease_lost" }); + await db.update(heartbeatRuns).set({ controllerLeaseExpiresAt: new Date(Date.now() + 365 * 86_400_000) }) + .where(eq(heartbeatRuns.id, f.runId)); + const waiting = await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" }); + expect(waiting).toMatchObject({ kind: "exact_recovery_pending", reason: "controller_lease_live" }); + await recordFreshContinuationCheck(db, { companyId, actionId: f.actionId! }, waiting); + await waitedFor(f.actionId!, FRESH_CONTINUATION_PENDING_BOUND_MS + 1_000); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued", isolation: "fresh_isolated_workspace" }); + }, 60_000); + + it("keeps the task workspace when the old local writer is proven gone", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "process_lost" }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued", isolation: "writer_ended" }); + }, 60_000); + + it("settles only the reconciliation holds it owns and leaves restore holds and history alone", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_session_interrupted" }); + const [history] = await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: f.issueId, kind: "active_run_watchdog", + status: "cancelled", outcome: "cancelled", ownerType: "board", cause: "native_restart_recovery_blocked", + fingerprint: `history:${f.runId}`, nextAction: "Old note", resolutionNote: "kept", resolvedAt: new Date(), + evidence: { runId: f.runId } }).returning(); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + const [untouched] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, history!.id)); + expect(untouched).toMatchObject({ status: "cancelled", nextAction: "Old note", resolutionNote: "kept", ownerType: "board" }); + expect(untouched!.evidence).toEqual({ runId: f.runId }); + + // A restore hold that workspace recovery has not finished keeps the task with it. + const g = await unfinishedRun({ runtime: "native", errorCode: "native_session_interrupted" }); + const [restore] = await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: g.issueId, kind: "active_run_watchdog", + status: "resolved", outcome: "blocked", ownerType: "system", cause: "native_continuation_requires_reconciliation", + fingerprint: `native-workspace:${g.runId}`, nextAction: "Recovering saved work", resolvedAt: new Date(), + evidence: { runId: g.runId, workspaceRestoreFailure: "restore_unsafe_archive", + automaticRecovery: { policy: "preserve_without_replay_v1", runId: g.runId, replay: "blocked" } } }).returning(); + expect(await ensureFreshContinuation(db, { companyId, runId: g.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "exact_recovery_pending", reason: "workspace_recovery_owns_restore" }); + const [kept] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, restore!.id)); + expect(kept!.evidence).toMatchObject({ workspaceRestoreFailure: "restore_unsafe_archive", automaticRecovery: { replay: "blocked" } }); + expect(kept!.evidence.executionReconciliation).toBeUndefined(); + }, 60_000); + + it("schedules no recheck for a held task nothing would act on", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_session_interrupted", hold: "settled_blocked" }); + await db.update(issueRecoveryActions).set({ evidence: sql`${issueRecoveryActions.evidence} || ${JSON.stringify({ + freshContinuationCheck: { kind: "person_owned", reason: "approval_pending", checkedAt: Date.now() - 7_200_000, + nextCheckAt: Date.now() - 3_600_000 } })}::jsonb` }).where(eq(issueRecoveryActions.id, f.actionId!)); + expect(await nextFreshContinuationCheckAt(db)).not.toBeNull(); + // The task was cancelled after that check: the schedule goes quiet. + await db.update(issues).set({ status: "cancelled" }).where(eq(issues.id, f.issueId)); + expect(await nextFreshContinuationCheckAt(db)).toBeNull(); + expect(await heldExecutionsAwaitingFreshContinuation(db, new Date(), 10)).toEqual([]); + expect(await executionControlSchedule(db).disposition()).toBeNull(); + }, 60_000); + + it("tells the agent the previous attempt was cut off and which actions are unverified", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_session_interrupted" }); + await db.insert(toolInvocations).values({ companyId, agentId, issueId: f.issueId, runId: f.runId, toolName: "github.create_pull_request", + riskLevel: "write", status: "executing", startedAt: new Date() } as typeof toolInvocations.$inferInsert); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })).toMatchObject({ kind: "continued" }); + const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)); + const decision = hold!.evidence.executionReconciliation as Record; + expect(decision.outcomeEvidence).toContain(`run ${f.runId}) was cut off`); + expect(decision.outcomeEvidence).toContain("github.create_pull_request"); + expect(decision.outcomeEvidence).not.toMatch(adminText); + }, 60_000); + + it.each([ + { title: "a pending approval", setup: "approval" as const, errorCode: "native_continuation_requires_reconciliation" }, + { title: "a credential the person has not shared", setup: "none" as const, errorCode: "configuration_incomplete" }, + { title: "a budget stop", setup: "none" as const, errorCode: "budget_blocked" }, + ])("leaves a task waiting on $title for the person", async ({ setup, errorCode }) => { + expect(PERSON_OWNED_FAILURE_CODES).toContain("configuration_incomplete"); + const f = await unfinishedRun({ runtime: "native", errorCode }); + if (setup === "approval") { + const [approval] = await db.insert(approvals).values({ companyId, type: "approve_ceo_strategy", status: "pending", + payload: {} } as typeof approvals.$inferInsert).returning(); + await db.insert(issueApprovals).values({ companyId, issueId: f.issueId, approvalId: approval!.id } as typeof issueApprovals.$inferInsert); + } + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "person_owned" }); + await settleUnrecoverableExecutions(db); + expect(await issue(f.issueId)).toMatchObject({ status: "blocked" }); + await deliver(); + expect(await successors(f.runId)).toHaveLength(0); + }, 60_000); + + it("bounds continuations with the server-restart lane's hourly cap", () => { + expect(FRESH_CONTINUATIONS_PER_HOUR).toBe(SERVER_RESTART_RETRY_MAX_ATTEMPTS); + expect(FRESH_CONTINUATION_WINDOW_MS).toBe(SERVER_RESTART_RETRY_WINDOW_MS); + }); + + // Governance gates are never retired or bypassed by the fallback. + it.each(["question_pending", "user_owned_hold", "operator_continuation_recorded", "owner_gone_attestation"] as const)( + "leaves a task behind a real governance gate (%s) for the person", async gate => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_continuation_requires_reconciliation" }); + if (gate === "question_pending") await db.insert(issueThreadInteractions).values({ companyId, issueId: f.issueId, + kind: "ask_user_questions", status: "pending", payload: { questions: [] } } as unknown as typeof issueThreadInteractions.$inferInsert); + if (gate === "user_owned_hold") await db.update(issueRecoveryActions).set({ ownerType: "user", ownerUserId: userId }) + .where(eq(issueRecoveryActions.id, f.actionId!)); + if (gate === "operator_continuation_recorded" || gate === "owner_gone_attestation") { + const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)); + await db.update(issueRecoveryActions).set({ evidence: { ...hold!.evidence, + ...(gate === "owner_gone_attestation" ? { ownerGoneAttestation: { actorId: userId } } : { explicitUserContinuation: { actorId: userId } }) } }) + .where(eq(issueRecoveryActions.id, f.actionId!)); + } + const before = (await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)))[0]!; + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "person_owned" }); + const after = (await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)))[0]!; + expect(after.evidence).toEqual(before.evidence); + expect(after.status).toBe(before.status); + await deliver(); + expect(await successors(f.runId)).toHaveLength(0); + }, 60_000); + + // Interruption with an unknown outcome is not a governance gate: the task + // continues, but as a fresh run, never a replay, and with an audit trail. + it("continues an interrupted governed action as a fresh run, never a replay, and keeps the audit trail", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "native_continuation_requires_reconciliation", + error: "runner_remote_process_identity_unavailable", hold: "settled_blocked" }); + const [inFlight] = await db.insert(toolInvocations).values({ companyId, agentId, issueId: f.issueId, runId: f.runId, + toolName: "github.merge_pull_request", riskLevel: "write", status: "executing", startedAt: new Date() } as typeof toolInvocations.$inferInsert) + .returning(); + const original = (await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)))[0]!.evidence.automaticRecovery; + await settleUnrecoverableExecutions(db); + const next = await expectOneFreshSuccessor(f); + // A fresh session: the interrupted turn is not re-sent. + expect(next.contextSnapshot).toMatchObject({ forceFreshSession: true }); + expect(next.sessionIdBefore).toBeNull(); + // The cut-off tool call is not re-executed: it stays as recorded and no new invocation exists. + const invocations = await db.select().from(toolInvocations).where(eq(toolInvocations.issueId, f.issueId)); + expect(invocations).toEqual([expect.objectContaining({ id: inFlight!.id, runId: f.runId, status: "executing" })]); + // The earlier no-replay decision stays as history beside the attributed fallback decision. + const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)); + expect(hold!.evidence.automaticRecoveryHistory).toEqual(original); + expect(hold!.evidence.freshContinuationSettlement).toMatchObject({ actorType: "system", actorId: "fresh-continuation", + decision: "continue_in_fresh_run", replay: "none", reason: "exact_resumption_unavailable", + unverifiedActions: ["github.merge_pull_request"], recordedAt: expect.any(String) }); + expect((hold!.evidence.executionReconciliation as Record).outcomeEvidence).toContain("github.merge_pull_request"); + expect(await db.select().from(activityLog).where(and(eq(activityLog.entityId, f.issueId), + eq(activityLog.action, "issue.continued_from_saved_work")))).toHaveLength(1); + }, 60_000); + + // The isolation decision is a property of the task's next run, whatever path starts it. + it("moves the task off the old writer's workspace for every next run, saved input included", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "controller_lease_lost", error: "Legacy controller lease lost" }); + const [workspace] = await db.insert(executionWorkspaces).values({ companyId, sourceIssueId: f.issueId, mode: "isolated", + strategyType: "git_worktree", name: "Task workspace", cwd: "/tmp/old-writer" }).returning(); + await db.update(issues).set({ executionWorkspaceId: workspace!.id, workspaceBindingRevision: 2 }).where(eq(issues.id, f.issueId)); + await db.update(heartbeatRuns).set({ processPid: 4242, processHostHash: "replaced-server", processStartedAt: new Date(Date.now() - 600_000), + contextSnapshot: { issueId: f.issueId, executionWorkspaceId: workspace!.id } }).where(eq(heartbeatRuns.id, f.runId)); + // A person's saved message is waiting: it continues the task itself. + await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "on_demand", status: "deferred_issue_execution", + requestedByActorType: "user", requestedByActorId: userId, payload: { issueId: f.issueId } }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued", isolation: "fresh_isolated_workspace", delivery: "saved_input" }); + // No delivery path can reach the old directory: the task is no longer bound to it. + expect(await issue(f.issueId)).toMatchObject({ executionWorkspaceId: null, workspaceBindingRevision: 3 }); + const [kept] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, workspace!.id)); + expect(kept!.cwd).toBe("/tmp/old-writer"); + }, 60_000); + + it("records its own isolated continuation when saved input could not avoid a shared directory", async () => { + const f = await unfinishedRun({ runtime: "legacy", errorCode: "controller_lease_lost" }); + await db.update(heartbeatRuns).set({ processPid: 4242, processHostHash: "replaced-server", processStartedAt: new Date(Date.now() - 600_000) }) + .where(eq(heartbeatRuns.id, f.runId)); + await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "on_demand", status: "deferred_issue_execution", + requestedByActorType: "user", requestedByActorId: userId, payload: { issueId: f.issueId } }); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued", isolation: "fresh_isolated_workspace", delivery: "recorded" }); + }, 60_000); + + it("backs off instead of blocking once a task used its hourly continuations", async () => { + const f = await unfinishedRun({ runtime: "native", errorCode: "process_lost" }); + for (let index = 0; index < FRESH_CONTINUATIONS_PER_HOUR; index++) { + await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: f.issueId, kind: "active_run_watchdog", status: "resolved", + outcome: "restored", ownerType: "system", cause: "fresh_continuation", fingerprint: `fresh-continuation:${randomUUID()}`, + nextAction: "continued", evidence: { runId: randomUUID(), continuationDelivery: "delivered", + freshContinuation: { schema: FRESH_CONTINUATION_SCHEMA, sourceRunId: randomUUID(), + recordedAt: new Date(Date.now() - (index + 1) * 60_000).toISOString() } } }); + } + await settleUnrecoverableExecutions(db); + const [hold] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId!)); + // Not blocked for a person: the hold stays with the system and is checked again when the window frees a slot. + expect(hold).toMatchObject({ status: "active" }); + expect(hold!.evidence.freshContinuationCheck).toMatchObject({ kind: "backoff", nextCheckAt: expect.any(Number) }); + expect(await continueHeldExecutions(db)).toMatchObject({ continued: 0 }); + // With no other event, the disposition worker is scheduled for exactly the + // moment the window has room again. + const retryAt = (hold!.evidence.freshContinuationCheck as { nextCheckAt: number }).nextCheckAt; + expect(retryAt).toBeGreaterThan(Date.now()); + expect(await nextFreshContinuationCheckAt(db)).toBe(retryAt); + expect(await executionControlSchedule(db).disposition()).toBe(retryAt); + // The hour passes (the window's records age out and the check falls due); + // the scheduled pass alone continues the task. + await db.execute(sql`update issue_recovery_actions set evidence = jsonb_set(evidence, '{freshContinuation,recordedAt}', + to_jsonb((now() - interval '2 hours')::text)) where evidence ? 'freshContinuation'`); + await db.update(issueRecoveryActions).set({ evidence: sql`jsonb_set(${issueRecoveryActions.evidence}, + '{freshContinuationCheck,nextCheckAt}', to_jsonb(${Date.now() - 1_000}::bigint))` }).where(eq(issueRecoveryActions.id, f.actionId!)); + expect(await executionControlSchedule(db).disposition()).toBeLessThanOrEqual(Date.now() + 60_000); + await settleUnrecoverableExecutions(db); + expect(await ensureFreshContinuation(db, { companyId, runId: f.runId, trigger: "held_recovery" })) + .toMatchObject({ kind: "already_continued" }); + expect(await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests)).toHaveLength(0); + }, 60_000); +}); diff --git a/server/src/services/fresh-continuation-fallback.ts b/server/src/services/fresh-continuation-fallback.ts new file mode 100644 index 00000000000..092084af912 --- /dev/null +++ b/server/src/services/fresh-continuation-fallback.ts @@ -0,0 +1,741 @@ +import { and, asc, desc, eq, gt, inArray, isNull, or, sql } from "drizzle-orm"; +import { + agentWakeupRequests, agents, approvals, companies, executionWorkspaces, heartbeatRuns, issueApprovals, issueRecoveryActions, + issueThreadInteractions, issues, nativeRunFinalizations, toolInvocations, type Db, +} from "@paperclipai/db"; +import { + EXECUTION_RECONCILIATION_CAUSES, readRemoteWorkspaceAuthority, remoteWorkspaceRunReferenceSchema, type ExecutionReconciliation, +} from "@paperclipai/shared"; +import { logger } from "../middleware/logger.js"; +import { logActivity } from "./activity-log.js"; +import { FRESH_CONTINUATION_SUPERSEDED_KEY } from "../agent-run-cancellation.js"; +import { isAcknowledgedNativeReassignmentStop, isAcknowledgedNativeStop } from "./acknowledged-native-stop.js"; +import { adapterExecutionControls } from "./adapter-execution-control.js"; +import { isInterruptedNativePreparationCandidate } from "./cancelled-native-startup.js"; +import { notifyDeferredWakesForIssue } from "./deferred-execution-notifications.js"; +import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; +import { issueService } from "./issues.js"; +import { holdOwnsBlockedStatus } from "./recovery-hold-blocked-status.js"; +import { proveRunProcessGone } from "./run-process-owner.js"; +import { hasPendingRunCleanup } from "./execution-blocker.js"; +import { abandonUnverifiedRemoteWorkspaceEpoch } from "./remote-workspace-epoch-abandonment.js"; +import { notifyRoutineExecutionStatus } from "./routine-execution-status-notifications.js"; +import { notifyStatusCardIssueChange } from "./status-card-notifications.js"; +import { readRunCancellation } from "./run-cancellation.js"; +import { readSystemRecovery } from "./system-recovery-state.js"; + +/** + * Fresh-continuation fallback: exact resumption of an unfinished run is an + * optimization, never a requirement. + * + * When a run ended without finishing its work and nothing exact follows it + * (no resumed session, no replacement, no scheduled retry, no saved input), + * `ensureFreshContinuation` starts the task again in a fresh session from its + * last verified saved workspace and its conversation. It needs no person and + * no proof that the old executor stopped: + * + * - The old run keeps its own fencing. Its remote workspace epoch is abandoned + * when it still owns it, so its writer can never publish again and the next + * run restores the last committed save into a new root on a new allocation. + * The unverified files stay in the abandoned root (recorded on the + * workspace), unapplied. + * - The opening context of the continuation names the cut-off run and every + * action whose outcome is unknown, so the agent checks before repeating a + * side effect. + * + * Eligibility is by classification, not by an allowlist: every failure is + * eligible except the causes a person must resolve (`PERSON_OWNED_FAILURE_CODES` + * and the task-level waits in `personOwnedTaskWait`). A failure code added + * later falls back without a change here. + * + * Idempotent per source run: the task row lock serializes callers on every + * server, and the recorded `freshContinuation.sourceRunId` (or any newer run of + * the task) makes later calls a no-op. Bounded per task, not per failure: at + * most `FRESH_CONTINUATIONS_PER_HOUR` continuations in a rolling hour, then it + * backs off and is checked again; it never charges the task's failure budget. + */ + +export const FRESH_CONTINUATION_SCHEMA = "paperclip.fresh-continuation.v1" as const; +export const FRESH_CONTINUATION_ACTOR = "fresh-continuation" as const; +/** Cause of the record written when the run left no hold of its own. Not an execution blocker. */ +export const FRESH_CONTINUATION_CAUSE = "fresh_continuation" as const; +/** Evidence key for the last check that did not continue (and when to check again). */ +export const FRESH_CONTINUATION_CHECK_KEY = "freshContinuationCheck" as const; +/** The restart lane's bound, reused: continuations per task per rolling hour. */ +// Literal values (an import would be undefined under the heartbeat module's +// import cycle); a test pins them to SERVER_RESTART_RETRY_MAX_ATTEMPTS/_WINDOW_MS. +export const FRESH_CONTINUATIONS_PER_HOUR = 6; +export const FRESH_CONTINUATION_WINDOW_MS = 60 * 60_000; +const PERSON_RECHECK_MS = 60 * 60_000; +/** Consecutive pending checks (about 12 minutes) before the fallback stops waiting. */ +/** Worst case from the first pending check to the fresh continuation. */ +export const FRESH_CONTINUATION_PENDING_BOUND_MS = 10 * 60_000; +/** Longer cap while the exact-recovery owner shows progress (a new event or a renewed lease). */ +export const FRESH_CONTINUATION_PROGRESS_BOUND_MS = 15 * 60_000; +/** Saved-work recovery that is running and advancing keeps its own budget. */ +export const FRESH_CONTINUATION_SAVED_WORK_BOUND_MS = 30 * 60_000; +const EXACT_RECOVERY_RECHECK_MS = 60_000; + +/** + * Run failure codes that only a person can resolve (the test for each: did a + * person fail to do something, or did the system fail to carry it forward? Only + * the first belongs here; e.g. a lost carry-over of a Retry's authorization, + * `continuation_user_authorization_missing`, is the system's): they stopped the work, a + * credential or access they must share, a configuration choice they must make, + * a budget stop, or a provider usage limit that is waiting as designed. Every + * other code, including codes that do not exist yet, gets the fallback. + */ +export const PERSON_OWNED_FAILURE_CODES = [ + // A person stopped or paused the work. + "cancelled", "operator_cancelled", "operator_interrupted", "issue_cancelled", "issue_paused", "agent_paused", + // A credential, secret or access the person must share. + "configuration_incomplete", "slack_configuration_incomplete", "signing_secret_unconfigured", + "user_secret_missing", "user_secret_definition_missing", "user_secret_definition_inactive", + "github_access_denied", "github_repo_not_accessible", "github_auth_required", "project_access_denied", + "permission_denied", "responsible_user_unauthorized", "oauth_access_projection_disabled", + "acpx_auth_required", "codex_auth_required", "claude_auth_required", "provider_auth_failed", "hermes_gateway_auth_failed", + // A configuration choice the person must change. + "native_provider_model_rejected", "provider_tool_definition_invalid", "turn_limit_exhausted", + // Budget stops. + "budget_blocked", "budget_hard_stop", "budget_exceeded", + // Provider usage limits that wait (and resume) as designed. + "provider_quota", "provider_limit_wait", "native_provider_usage_limit", + // An approval the person must give. + "approval_required", "formal_approval_unavailable", +] as const; + +export function isPersonOwnedFailureCode(code: string | null | undefined): boolean { + return typeof code === "string" && (PERSON_OWNED_FAILURE_CODES as readonly string[]).includes(code); +} + +const UNFINISHED_STATUSES = ["failed", "timed_out", "interrupted", "cancelled"]; +const LIVE_RUN_STATUSES = ["queued", "running", "scheduled_retry"]; +const EXACT_RECOVERY_STATES = ["scheduled", "running", "awaiting_evidence"]; + +/** + * How the continuation is kept apart from the old executor: + * - `remote_epoch`: the old run's remote workspace epoch is fenced (abandoned, or + * already taken from it), so it can never publish; the next preparation + * restores the last committed save into a new root. + * - `writer_ended`: the old local writer is proven gone (no process, no + * unsettled allocation), so the task workspace is safe to reuse. + * - `fresh_isolated_workspace`: the old local writer is not proven gone, so the + * continuation gets a new isolated workspace and never writes the old + * directory. Nothing waits for that proof. + */ +export type FreshContinuationIsolation = "remote_epoch" | "writer_ended" | "fresh_isolated_workspace"; + +export type FreshContinuationTrigger = "recovery_refused" | "held_recovery" | "continuation_wake"; + +export type FreshContinuationResult = + | { kind: "continued"; recoveryActionId: string; delivery: "recorded" | "caller_owns" | "saved_input"; isolation: FreshContinuationIsolation } + | { kind: "already_continued"; recoveryActionId: string } + | { kind: "successor_exists" } + | { kind: "dependency_wait" } + | { kind: "person_owned"; reason: string } + | { kind: "backoff"; retryAt: Date } + | { kind: "exact_recovery_pending"; reason: string; retryAt: Date; progressAt?: number; savedWorkSignature?: string } + | { kind: "not_applicable"; reason: string }; + +type Input = { + companyId: string; + runId: string; + trigger: FreshContinuationTrigger; + now?: Date; + /** + * `record`: record one durable continuation that the execution-continuation + * worker delivers. `caller_owns`: the caller is admitting a wake for this + * task in the same transaction, and that wake is the continuation. + */ + delivery?: "record" | "caller_owns"; +}; + +const object = (value: unknown): Record => + value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; + +function holdRunId(evidence: Record): string | null { + const value = evidence.runId ?? evidence.sourceRunId; + return typeof value === "string" ? value : null; +} + +/** Task-level waits that belong to a person. Read under the task lock. */ +async function personOwnedTaskWait(tx: Db, input: { companyId: string; issue: typeof issues.$inferSelect; + run: typeof heartbeatRuns.$inferSelect }): Promise { + const { companyId, issue, run } = input; + const [approval] = await tx.select({ id: approvals.id }).from(issueApprovals).innerJoin(approvals, and( + eq(approvals.id, issueApprovals.approvalId), eq(approvals.companyId, companyId), + )).where(and(eq(issueApprovals.companyId, companyId), eq(issueApprovals.issueId, issue.id), + inArray(approvals.status, ["pending", "revision_requested"]))).limit(1); + if (approval) return "approval_pending"; + const [question] = await tx.select({ id: issueThreadInteractions.id }).from(issueThreadInteractions).where(and( + eq(issueThreadInteractions.companyId, companyId), eq(issueThreadInteractions.issueId, issue.id), + eq(issueThreadInteractions.status, "pending"))).limit(1); + if (question) return "question_pending"; + const [agent] = await tx.select({ status: agents.status, lifecycleState: agents.lifecycleState }).from(agents) + .where(and(eq(agents.companyId, companyId), eq(agents.id, run.agentId))); + if (!agent || ["paused", "terminated", "pending_approval"].includes(agent.status) || agent.lifecycleState !== "ready") + return "agent_not_available"; + const [company] = await tx.select({ status: companies.status }).from(companies).where(eq(companies.id, companyId)); + if (company && company.status !== "active") return "company_paused"; + return null; +} + +/** Actions of the source run that ended with an unknown outcome. */ +async function unverifiedActions(tx: Db, run: typeof heartbeatRuns.$inferSelect): Promise { + const names = new Set(); + for (const receipt of Object.values(object(object(run.resultJson).apiToolReceipts)).map(object)) { + if (receipt.state !== "completed" || object(receipt.result).outcome === "unknown") + names.add(typeof receipt.toolName === "string" ? receipt.toolName : "a Paperclip API call"); + } + const rows = await tx.select({ toolName: toolInvocations.toolName }).from(toolInvocations).where(and( + eq(toolInvocations.companyId, run.companyId), eq(toolInvocations.runId, run.id), + sql`${toolInvocations.riskLevel} is distinct from 'read'`, + inArray(toolInvocations.status, ["executing", "failed", "timed_out"]))).limit(20); + for (const row of rows) names.add(row.toolName); + return [...names].slice(0, 20); +} + +/** The opening context of the continuation. It names no person who must act. */ +export function freshContinuationNote(input: { runId: string; unverified: string[]; workspace: "restored_last_save" | "kept" }) { + const actions = input.unverified.length + ? `These actions of that run have unverified outcomes: ${input.unverified.join(", ")}. For each one, first check whether it took effect.` + : "No action of that run is recorded with an unknown outcome; check the task's recent history before repeating any side effect."; + const files = input.workspace === "restored_last_save" + ? "Its unsaved file changes could not be verified, so this run starts from the last saved version of the workspace; those changes were not applied." + : "This run starts from the task's saved workspace."; + // How to proceed. Nobody has to restore the previous attempt: the agent + // checks, redoes what is missing, and asks only through the normal approval. + const guidance = "Completed actions with recorded results are still not repeated; this applies only to the actions above, whose outcome is unknown. " + + "If an action did not take effect, or repeating it is safe, do it again and continue the task. " + + "If repeating it would be a governed or irreversible action, request it through the normal approval step. " + + "Nothing about the previous attempt needs to be restored before you continue."; + return `The previous attempt (run ${input.runId}) was cut off before it finished. ${files} ${actions} ${guidance}`; +} + +const USER_TEXT = "The previous run was cut off. Paperclip continues the task in a fresh run from its last saved work."; + +/** Abandons the source run's remote workspace epoch when it still owns it. */ +async function fenceSourceWorkspace(tx: Db, run: typeof heartbeatRuns.$inferSelect) { + const parsed = remoteWorkspaceRunReferenceSchema.safeParse(object(run.runnerProfileJson).remoteWorkspace); + if (!parsed.success || parsed.data.state !== "prepared") return null; + const reference = parsed.data; + const [workspace] = await tx.select({ metadata: executionWorkspaces.metadata }).from(executionWorkspaces).where(and( + eq(executionWorkspaces.companyId, run.companyId), eq(executionWorkspaces.id, reference.workspaceId))); + let authority; + try { authority = readRemoteWorkspaceAuthority(workspace?.metadata); } catch { return null; } + if (!authority?.location || authority.writerRunId !== run.id || authority.epoch !== reference.epoch) return null; + try { + const abandoned = await tx.transaction(savepoint => abandonUnverifiedRemoteWorkspaceEpoch(savepoint, { + companyId: run.companyId, workspaceId: reference.workspaceId, runId: run.id, epoch: authority.epoch, + snapshotId: authority.snapshotId, location: authority.location! })); + return { workspaceId: reference.workspaceId, abandonedEpoch: authority.epoch, epoch: abandoned.authority.epoch, + snapshotId: authority.snapshotId, + quarantine: { state: "retained_unapplied" as const, remoteCwd: authority.location.remoteCwd, + providerLeaseId: authority.location.providerLeaseId } }; + } catch (error) { + if (error instanceof Error && error.message === "remote_workspace_authority_changed") return null; + throw error; + } +} + +/** + * The one distinction this module turns on: a real human gate versus system + * uncertainty. + * + * A human gate is a decision a person actually made or still owes: a pending + * approval or question (`personOwnedTaskWait`), a hold a user owns, or an + * operator decision recorded on the hold (an owner-gone attestation, an + * explicit continuation, a reconciliation). The fallback never retires or + * bypasses one. + * + * Everything else is system uncertainty, however it is labelled: a + * no-replay record (`automaticRecovery.replay: blocked`, "outcome unknown after + * an interruption"), a hold whose owner type is `board` because nobody else was + * assigned, or a controller whose process space cannot be verified. Owner type + * alone never proves that a person must act. For these the fallback starts a + * fresh run, never a replay: the interrupted turn is not re-sent, no tool call + * or write is re-executed, and any governed action goes through its approval + * gate again. + */ +export function isHumanGate(hold: Pick): boolean { + return Boolean(hold.ownerUserId || hold.evidence.ownerGoneAttestation || hold.evidence.explicitUserContinuation + || hold.evidence.executionReconciliation); +} + +const isRestoreHold = (hold: typeof issueRecoveryActions.$inferSelect) => + hold.evidence.workspaceRestoreFailure !== undefined || hold.evidence.workspaceRestoreRecovery !== undefined; +const blocksExecution = (hold: typeof issueRecoveryActions.$inferSelect) => + ["active", "escalated"].includes(hold.status) || object(hold.evidence.automaticRecovery).replay === "blocked"; + +/** A reconciliation hold that blocks the task and that this decision settles. */ +function isOwnedReconciliationHold(hold: typeof issueRecoveryActions.$inferSelect) { + if (!(EXECUTION_RECONCILIATION_CAUSES as readonly string[]).includes(hold.cause) || !blocksExecution(hold)) return false; + if (isHumanGate(hold)) return false; + // A restore hold is owned only once its saved-work recovery completed. + return !isRestoreHold(hold) || readSystemRecovery(hold.evidence)?.state === "complete"; +} + +/** + * The old local writer's state. `alive`: its process is running on this host, + * so it is still executing and is settled by its own owner (stop, reaper) + * first. `ended`: no process this host can see and no allocation or workspace + * finalization left unsettled. `unproven`: anything else (another host, an + * unsettled allocation); the continuation is isolated from it, never waits. + */ +async function localWriterState(tx: Db, run: typeof heartbeatRuns.$inferSelect): Promise<"alive" | "ended" | "unproven"> { + // The shared owner proof compares the recorded process identity (host, PID + // space, start time), so a recycled PID is never mistaken for the old writer. + const proof = await proveRunProcessGone(run, "fresh_continuation"); + if (proof?.verdict === "alive") return "alive"; + if (proof?.verdict === "unprovable" || await hasPendingRunCleanup(tx, run.companyId, run.id)) return "unproven"; + return "ended"; +} + +/** The workspace selection a delivered continuation carries (read only when its context names it). */ +export async function readFreshContinuationReadiness(db: Db, run: Pick, issueId: string) { + const recordId = object(run.contextSnapshot).freshContinuationIsolation; + if (typeof recordId !== "string" || !/^[0-9a-f-]{36}$/i.test(recordId)) return null; + const [record] = await db.select({ evidence: issueRecoveryActions.evidence }).from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.companyId, run.companyId), eq(issueRecoveryActions.sourceIssueId, issueId), + sql`${issueRecoveryActions.id}::text = ${recordId}`, + sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,isolation}' = 'fresh_isolated_workspace'`)).limit(1); + const sourceRunId = object(record?.evidence.freshContinuation).sourceRunId; + if (typeof sourceRunId !== "string") return null; + return { mode: "fresh_isolated_workspace" as const, retryIntentId: recordId, sourceRunId, retainedSourceIds: [] as string[] }; +} + +export async function ensureFreshContinuation(db: Db, input: Input): Promise { + return db.transaction(tx => continueFreshInTransaction(tx as unknown as Db, input)); +} + +/** + * The fallback inside the caller's transaction. Locks in the shared order + * (task, coordinator, run, recovery actions, workspace); rows the caller + * already locked are locked again harmlessly. + */ +export async function continueFreshInTransaction(tx: Db, input: Input): Promise { + const now = input.now && Number.isFinite(input.now.getTime()) ? input.now : new Date(); + const { companyId } = input; + const [peek] = await tx.select({ issueId: heartbeatRuns.issueId, nativeIssueId: heartbeatRuns.nativeIssueId, + contextSnapshot: heartbeatRuns.contextSnapshot }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, input.runId))); + if (!peek) return { kind: "not_applicable", reason: "run_missing" }; + const contextIssueId = object(peek.contextSnapshot).issueId; + const issueId = peek.nativeIssueId ?? peek.issueId ?? (typeof contextIssueId === "string" ? contextIssueId : null); + if (!issueId) return { kind: "not_applicable", reason: "run_has_no_task" }; + const [issue] = await tx.select().from(issues).where(and(eq(issues.companyId, companyId), eq(issues.id, issueId))).for("update"); + const [coordinator] = await tx.select().from(nativeRunFinalizations).where(and( + eq(nativeRunFinalizations.companyId, companyId), eq(nativeRunFinalizations.runId, input.runId))).for("update"); + const [run] = await tx.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), + eq(heartbeatRuns.id, input.runId))).for("update"); + if (!issue || !run) return { kind: "not_applicable", reason: "run_missing" }; + if (!UNFINISHED_STATUSES.includes(run.status) || !run.finishedAt) return { kind: "not_applicable", reason: "run_not_unfinished" }; + if (!issue.assigneeAgentId || issue.assigneeAgentId !== run.agentId || issue.assigneeUserId + || ["done", "cancelled"].includes(issue.status)) return { kind: "not_applicable", reason: "task_changed" }; + + const holds = await tx.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, companyId), + eq(issueRecoveryActions.sourceIssueId, issue.id), + or(sql`${issueRecoveryActions.evidence}->>'runId' = ${run.id}`, sql`${issueRecoveryActions.evidence}->>'sourceRunId' = ${run.id}`))) + .orderBy(asc(issueRecoveryActions.createdAt), asc(issueRecoveryActions.id)).for("update"); + const prior = holds.find(hold => object(hold.evidence.freshContinuation).sourceRunId === run.id); + if (prior) return { kind: "already_continued", recoveryActionId: prior.id }; + // The holds this decision owns: reconciliation holds that still block the + // task. Workspace restore/repair holds stay with workspace recovery, and + // resolved history is never rewritten. + const ownedHolds = holds.filter(isOwnedReconciliationHold); + + // Every wait is bounded in time: about 10 minutes from the first pending + // check, or 15 while the exact-recovery owner shows progress (a new run + // event, output or lease renewal since the last check). Then the fallback + // stops waiting and continues in isolation (writes revoked, new root). + const pendingMarker = holds.map(hold => object(hold.evidence[FRESH_CONTINUATION_CHECK_KEY])) + .filter(check => check.kind === "exact_recovery_pending" && typeof check.firstPendingAt === "number") + .sort((a, b) => Number(a.firstPendingAt) - Number(b.firstPendingAt))[0]; + // Saved-work recovery shows progress when its generation advances (revision + // or attempt) or its hold is updated; the run and coordinator when they + // emit output, renew a lease or update. + const savedWork = holds.map(hold => readSystemRecovery(hold.evidence)).filter(recovery => recovery !== null); + const progressAt = Math.max(run.updatedAt?.getTime() ?? 0, run.lastOutputAt?.getTime() ?? 0, + coordinator?.updatedAt?.getTime() ?? 0, coordinator?.leaseExpiresAt?.getTime() ?? 0, + ...holds.filter(hold => readSystemRecovery(hold.evidence)).map(hold => hold.updatedAt.getTime())); + const savedWorkSignature = savedWork.map(recovery => `${recovery!.generationId}:${recovery!.revision}:${recovery!.attempts}:${recovery!.state}`) + .sort().join("|"); + const waitedMs = pendingMarker ? now.getTime() - Number(pendingMarker.firstPendingAt) : 0; + const progressing = Boolean(pendingMarker && ((typeof pendingMarker.progressAt === "number" && progressAt > pendingMarker.progressAt) + || (typeof pendingMarker.savedWorkSignature === "string" && savedWorkSignature !== pendingMarker.savedWorkSignature))); + // Saved-work recovery that is running and advancing keeps its own 30-minute + // budget: it may still rescue unsaved files. Anything idle gets the normal bound. + const savedWorkAdvancing = progressing && savedWork.some(recovery => recovery!.state === "running"); + const waitBounded = savedWorkAdvancing ? waitedMs >= FRESH_CONTINUATION_SAVED_WORK_BOUND_MS + : waitedMs >= FRESH_CONTINUATION_PROGRESS_BOUND_MS || (waitedMs >= FRESH_CONTINUATION_PENDING_BOUND_MS && !progressing); + // Rechecks back off 1, 2, 3, 4 minutes, so the bound is reached on time. + const step = Math.min(4, (typeof pendingMarker?.checks === "number" ? pendingMarker.checks : 0) + 1) * EXACT_RECOVERY_RECHECK_MS; + const pending = (reason: string, retryAt: Date): FreshContinuationResult | null => waitBounded ? null + : { kind: "exact_recovery_pending", reason, progressAt, savedWorkSignature, + retryAt: new Date(Math.min(retryAt.getTime(), now.getTime() + step)) }; + + // (a) Something already follows this run: a newer run of the task, a linked + // replacement, or an operator's continuation. + const [newer] = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, companyId), sql`${heartbeatRuns.id} <> ${run.id}`, + or(eq(heartbeatRuns.nativeIssueId, issue.id), eq(heartbeatRuns.issueId, issue.id), + sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issue.id}`), + or(inArray(heartbeatRuns.status, LIVE_RUN_STATUSES), + sql`(${heartbeatRuns.createdAt}, ${heartbeatRuns.id}) > (${run.createdAt.toISOString()}::timestamptz, ${run.id}::uuid)`))).limit(1); + if (newer || typeof object(coordinator?.failureDetail).successorRunId === "string" + || holds.some(hold => hold.evidence.executionReconciliation && ["pending", "delivered", "delegated"] + .includes(String(hold.evidence.continuationDelivery)))) return { kind: "successor_exists" }; + + // Exact recovery that is still under way keeps its chance, for a bounded + // number of checks; each owner below also bounds itself. + const recheck = new Date(now.getTime() + EXACT_RECOVERY_RECHECK_MS); + const waits: Array = []; + if (adapterExecutionControls.has(run.id)) waits.push(pending("execution_settling", recheck)); + if (coordinator?.leaseOwner || (coordinator?.resultId && coordinator.phase !== "committed") + || (coordinator?.nextAttemptAt && coordinator.nextAttemptAt > now)) + waits.push(pending("native_finalizer_active", + coordinator?.nextAttemptAt && coordinator.nextAttemptAt > now ? coordinator.nextAttemptAt : recheck)); + if (run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > now) + waits.push(pending("controller_lease_live", run.controllerLeaseExpiresAt)); + // A preparation that never started provider work has its own bounded retry + // lane (the ownership pass). It gets the first chance; the fallback follows. + if (isInterruptedNativePreparationCandidate(run) && !holds.some(hold => hold.evidence[FRESH_CONTINUATION_CHECK_KEY])) + waits.push(pending("interrupted_preparation_lane", recheck)); + for (const hold of holds) { + const recovery = readSystemRecovery(hold.evidence); + if (recovery && EXACT_RECOVERY_STATES.includes(recovery.state)) + waits.push(pending("saved_work_recovery_running", + new Date(Math.max(recheck.getTime(), recovery.nextAttemptAt ?? 0)))); + if (!isOwnedReconciliationHold(hold) && isRestoreHold(hold) && blocksExecution(hold) && recovery?.state !== "complete") + waits.push(pending("workspace_recovery_owns_restore", recheck)); + const retainedCheck = object(hold.evidence.retainedSourceFallbackCheck); + if (recovery?.state === "exhausted" && typeof retainedCheck.nextCheckAt === "number" && retainedCheck.nextCheckAt > now.getTime()) + waits.push(pending("retained_source_fallback_pending", new Date(retainedCheck.nextCheckAt))); + } + const firstWait = waits.find(wait => wait !== null); + if (firstWait) return firstWait; + // Past the bound, a hold that workspace recovery still owns is settled too: + // the continuation never uses that workspace (isolation below). + const owned = waitBounded ? holds.filter(hold => isOwnedReconciliationHold(hold) + || (isRestoreHold(hold) && blocksExecution(hold) && !isHumanGate(hold))) : ownedHolds; + + // (b) Causes that are the person's. + if (isPersonOwnedFailureCode(run.errorCode)) return { kind: "person_owned", reason: run.errorCode! }; + // A Stop a person (or an agent acting on the task) asked for is never undone. + const cancellation = readRunCancellation(run.resultJson); + if ((cancellation && ["user", "agent"].includes(cancellation.initiator.type)) + || object(run.resultJson).operatorInterrupted === true + || (run.status === "cancelled" && (isAcknowledgedNativeStop(run) || isAcknowledgedNativeReassignmentStop(run) + // A cancellation that recorded neither its cause nor a system initiator may + // be a person's Stop saved by an older release; it is never undone. + || (!cancellation && !run.errorCode)))) + return { kind: "person_owned", reason: "stopped_on_request" }; + // A task in review waits for its reviewer. + if (issue.status === "in_review") return { kind: "person_owned", reason: "in_review" }; + // A recorded operator reconciliation that already delivered a continuation + // was handled above (successor_exists); any other human gate stays. + if (holds.some(hold => blocksExecution(hold) && isHumanGate(hold) && !hold.evidence.executionReconciliation) + || holds.some(hold => hold.ownerUserId || hold.evidence.ownerGoneAttestation || hold.evidence.explicitUserContinuation)) + return { kind: "person_owned", reason: "operator_decision_recorded" }; + const taskWait = await personOwnedTaskWait(tx, { companyId, issue, run }); + if (taskWait) return { kind: "person_owned", reason: taskWait }; + let ownsBlock = false; + if (issue.status === "blocked") { + const receipts = holds.filter(hold => hold.evidence.nativeFailureBlock !== undefined || hold.evidence.legacyCancellationBlock !== undefined + || hold.evidence.nativeBootstrapFailureBlock !== undefined); + ownsBlock = (receipts.length ? receipts : holds).some(hold => holdOwnsBlockedStatus(hold, issue, run)) + || receipts.some(hold => [hold.evidence.legacyCancellationBlock, hold.evidence.nativeBootstrapFailureBlock] + .some(block => object(block).runId === run.id && object(block).statusVersion === Number(issue.statusVersion))) + // A run that left no hold: its terminal failure set the block and nothing changed it since. + || (!holds.length && issue.lastStatusDecisionId === null && issue.blockedTransitionAt !== null + && issue.blockedTransitionAt.getTime() >= run.finishedAt.getTime() - 1_000); + if (!ownsBlock) return { kind: "person_owned", reason: "blocked_by_another_decision" }; + const readiness = await issueService(tx).listDependencyReadiness(companyId, [issue.id], tx); + if (readiness.get(issue.id)?.isDependencyReady === false) return { kind: "dependency_wait" }; + } + + // (c) Bounded per task: the restart lane's hourly cap, then back off. + const windowStart = new Date(now.getTime() - FRESH_CONTINUATION_WINDOW_MS).toISOString(); + const recent = await tx.select({ recordedAt: sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,recordedAt}'` }) + .from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, companyId), + eq(issueRecoveryActions.sourceIssueId, issue.id), + sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,schema}' = ${FRESH_CONTINUATION_SCHEMA}`, + sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,recordedAt}' > ${windowStart}`)) + .orderBy(asc(sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,recordedAt}'`)); + if (recent.length >= FRESH_CONTINUATIONS_PER_HOUR) { + const oldest = new Date(recent[0]!.recordedAt).getTime(); + return { kind: "backoff", retryAt: new Date(oldest + FRESH_CONTINUATION_WINDOW_MS) }; + } + + // Saved user input (a message or a Retry the person pressed) continues the + // task through normal admission once nothing blocks it; a second, automatic + // continuation would run after it. + const [savedInput] = await tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.status, "deferred_issue_execution"), + eq(agentWakeupRequests.requestedByActorType, "user"), sql`${agentWakeupRequests.payload}->>'issueId' = ${issue.id}`)).limit(1); + let delivery: "recorded" | "caller_owns" | "saved_input" = input.delivery === "caller_owns" ? "caller_owns" + : savedInput ? "saved_input" : "recorded"; + + // (d) Continue: fence the old workspace epoch, settle every hold of the run, + // release the Blocked status this failure owns, and record one continuation. + const remoteSource = remoteWorkspaceRunReferenceSchema.safeParse(object(run.runnerProfileJson).remoteWorkspace).success; + const writer = remoteSource ? null : await localWriterState(tx, run); + // A local process still running on this host is executing: its own owner + // (the reaper or a Stop) settles it first, then the fallback continues. + const aliveWait = writer === "alive" ? pending("previous_process_running", new Date(now.getTime() + step)) : null; + if (aliveWait) return aliveWait; + const fenced = await fenceSourceWorkspace(tx, run); + // Never claim a stop that was not proven: record what isolates the successor. + const isolation: FreshContinuationIsolation = fenced || remoteSource ? "remote_epoch" + : writer === "ended" && !waitBounded ? "writer_ended" : "fresh_isolated_workspace"; + // With no task workspace binding to move, only a run that carries the + // isolation in its context can avoid the shared directory: the recorded + // continuation runs first, and saved input follows it. + if (isolation === "fresh_isolated_workspace" && !issue.executionWorkspaceId && delivery === "saved_input") delivery = "recorded"; + const unverified = await unverifiedActions(tx, run); + const note = freshContinuationNote({ runId: run.id, unverified, + workspace: isolation === "writer_ended" ? "kept" : "restored_last_save" }); + const decision: ExecutionReconciliation & { providerStopProof: "writer_ended" | "isolated" } = { runId: run.id, providerStopped: true, + // Only a proven end is a stop. `isolated` means exactly: the old run's agent + // token is refused for writes, and the continuation runs in a new workspace + // root (a fenced remote epoch or a new local workspace). Nothing more. + providerStopProof: isolation === "writer_ended" ? "writer_ended" : "isolated", + actionOutcome: "mixed", outcomeEvidence: note, + workspaceRepairEvidence: fenced + ? `Paperclip abandoned unverified workspace epoch ${fenced.abandonedEpoch} of run ${run.id}; the continuation restores ` + + `${fenced.snapshotId ? `committed snapshot ${fenced.snapshotId}` : "the workspace source"} into a new root.` + : isolation === "fresh_isolated_workspace" + ? `The previous writer of run ${run.id} is not proven stopped, so the continuation starts in a new isolated workspace; no unverified files are applied.` + : `The continuation of run ${run.id} starts from the task's last saved workspace; no unverified files are applied.` }; + const freshContinuation = { schema: FRESH_CONTINUATION_SCHEMA, sourceRunId: run.id, trigger: input.trigger, + failureCode: run.errorCode ?? null, delivery, recordedAt: now.toISOString(), isolation, + stopProof: isolation === "writer_ended" ? "writer_ended" : fenced ? "unproven_epoch_abandoned" : "unproven_isolated", + unverifiedActions: unverified, ...(fenced ? { workspace: fenced } : {}) }; + const reconciliation = { ...decision, actorId: FRESH_CONTINUATION_ACTOR, recordedAt: now.toISOString() }; + // Who, what, why and when. A fresh run is not a replay: the interrupted turn + // is not re-sent, no tool call or write is re-executed, and any governed + // action the new run wants goes through its approval gate again. + const settlement = { schema: FRESH_CONTINUATION_SCHEMA, actorType: "system", actorId: FRESH_CONTINUATION_ACTOR, + decision: "continue_in_fresh_run", replay: "none", sourceRunId: run.id, failureCode: run.errorCode ?? null, + reason: "exact_resumption_unavailable", isolation, unverifiedActions: unverified, recordedAt: now.toISOString() }; + const ownerHold = owned.find(hold => issue.status === "blocked" && holdOwnsBlockedStatus(hold, issue, run)) ?? owned.at(-1); + + await notifyDeliveryWork(tx, DELIVERY_QUEUES.executionContinuation); + await notifyDeliveryWork(tx, DELIVERY_QUEUES.executionReplacement); + await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors); + await notifyDeliveryWork(tx, DELIVERY_QUEUES.agentTimers); + await notifyStatusCardIssueChange(tx, companyId); + await notifyRoutineExecutionStatus(tx, issue.id, companyId); + if (delivery === "saved_input") await notifyDeferredWakesForIssue(tx, { companyId, issueId: issue.id }); + + let primaryId: string; + const continuationDelivery = delivery === "recorded" ? "pending" : "not_requested"; + if (ownerHold) { + primaryId = ownerHold.id; + for (const hold of owned) { + const primary = hold.id === ownerHold.id; + // The earlier no-replay decision stays on the hold as history, and the + // fallback is recorded beside it as its own attributed system decision. + const { automaticRecovery, [FRESH_CONTINUATION_CHECK_KEY]: _check, ...evidence } = hold.evidence; + await tx.update(issueRecoveryActions).set({ status: "resolved", outcome: "restored", resolvedAt: hold.resolvedAt ?? now, + updatedAt: now, ownerType: "system", ownerAgentId: null, ownerUserId: null, wakePolicy: null, monitorPolicy: null, + returnOwnerAgentId: primary ? run.agentId : hold.returnOwnerAgentId, nextAction: USER_TEXT, + resolutionNote: "continued_fresh_from_last_saved", + evidence: { ...evidence, executionReconciliation: reconciliation, freshContinuationSettlement: settlement, + ...(automaticRecovery !== undefined ? { automaticRecoveryHistory: automaticRecovery } : {}), + ...(primary ? { freshContinuation, continuationDelivery } + : { continuationDelivery: "coalesced", coalescedIntoRecoveryActionId: ownerHold.id }) }, + }).where(and(eq(issueRecoveryActions.companyId, companyId), eq(issueRecoveryActions.id, hold.id))); + } + } else { + const [created] = await tx.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issue.id, + kind: "active_run_watchdog", status: "resolved", outcome: "restored", ownerType: "system", + returnOwnerAgentId: run.agentId, cause: FRESH_CONTINUATION_CAUSE, fingerprint: `fresh-continuation:${run.id}`, + nextAction: USER_TEXT, resolutionNote: "continued_fresh_from_last_saved", resolvedAt: now, attemptCount: 1, + evidence: { runId: run.id, originalFailureCode: run.errorCode ?? null, executionReconciliation: reconciliation, + freshContinuationSettlement: settlement, freshContinuation, continuationDelivery } }).returning({ id: issueRecoveryActions.id }); + primaryId = created!.id; + } + // The replaced run loses its write authority: its agent may still be alive + // in an unreachable sandbox, and only the continuation may act on the task. + await tx.update(heartbeatRuns).set({ resultJson: sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) + || ${JSON.stringify({ [FRESH_CONTINUATION_SUPERSEDED_KEY]: now.toISOString() })}::jsonb` }).where(and( + eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, run.id))); + // The source is never replayed or replaced exactly after this decision. + if (coordinator) { + await tx.update(nativeRunFinalizations).set({ failureDetail: sql`coalesce(${nativeRunFinalizations.failureDetail}, '{}'::jsonb) + || ${JSON.stringify({ replacementDenied: "fresh_continuation" })}::jsonb` }).where(and( + eq(nativeRunFinalizations.companyId, companyId), eq(nativeRunFinalizations.runId, run.id))); + } + // The isolation is a property of the task's next run, whatever path starts + // it (a system continuation, saved input, a person's Retry, a sweep wake): + // the task no longer points at the directory the old writer may still use, + // so every next run prepares a new workspace. The old one is left in place. + if (isolation === "fresh_isolated_workspace" && issue.executionWorkspaceId) { + await tx.update(issues).set({ executionWorkspaceId: null, workspaceBindingRevision: sql`${issues.workspaceBindingRevision} + 1`, + updatedAt: now }).where(and(eq(issues.companyId, companyId), eq(issues.id, issue.id))); + } + if (issue.status === "blocked") { + await tx.update(issues).set({ status: "todo", unblockDescriptor: null, blockedTransitionAt: null, + blockedOwnerNotifiedAt: null, updatedAt: now }).where(and(eq(issues.companyId, companyId), eq(issues.id, issue.id))); + await logActivity(tx, { companyId, actorType: "system", actorId: FRESH_CONTINUATION_ACTOR, action: "issue.updated", + entityType: "issue", entityId: issue.id, agentId: run.agentId, runId: run.id, + details: { status: "todo", previousStatus: "blocked", reason: "fresh_continuation", recoveryActionId: primaryId, + _previous: { status: "blocked" } } }); + } + await logActivity(tx, { companyId, actorType: "system", actorId: FRESH_CONTINUATION_ACTOR, + action: "issue.continued_from_saved_work", entityType: "issue", entityId: issue.id, agentId: run.agentId, runId: run.id, + details: { recoveryActionId: primaryId, sourceRunId: run.id, failureCode: run.errorCode ?? null, trigger: input.trigger, + delivery, workspaceEpochAbandoned: Boolean(fenced), unverifiedActionCount: unverified.length } }); + logger.info({ runId: run.id, issueId: issue.id, failureCode: run.errorCode, trigger: input.trigger, delivery }, + "Unfinished run continues in a fresh run from saved work"); + return { kind: "continued", recoveryActionId: primaryId, delivery, isolation }; +} + +/** Records why a hold was not continued yet, and when to look again. */ +export async function recordFreshContinuationCheck(db: Db, input: { companyId: string; actionId: string }, + result: FreshContinuationResult, now = new Date()) { + if (result.kind === "continued" || result.kind === "already_continued") return; + const nextCheckAt = result.kind === "backoff" || result.kind === "exact_recovery_pending" ? result.retryAt.getTime() + : result.kind === "person_owned" || result.kind === "dependency_wait" ? now.getTime() + PERSON_RECHECK_MS : null; + const [row] = await db.select({ evidence: issueRecoveryActions.evidence }).from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.id, input.actionId))); + const prior = object(row?.evidence[FRESH_CONTINUATION_CHECK_KEY]); + const same = prior.kind === result.kind; + const checks = same && typeof prior.checks === "number" ? prior.checks + 1 : 1; + const firstPendingAt = result.kind === "exact_recovery_pending" + ? (same && typeof prior.firstPendingAt === "number" ? prior.firstPendingAt : now.getTime()) : null; + const marker = { kind: result.kind, reason: "reason" in result ? result.reason : null, checks, checkedAt: now.getTime(), nextCheckAt, + ...(firstPendingAt !== null ? { firstPendingAt, + progressAt: result.kind === "exact_recovery_pending" ? result.progressAt ?? null : null, + savedWorkSignature: result.kind === "exact_recovery_pending" ? result.savedWorkSignature ?? null : null } : {}) }; + await db.update(issueRecoveryActions).set({ evidence: sql`${issueRecoveryActions.evidence} + || jsonb_build_object(${FRESH_CONTINUATION_CHECK_KEY}::text, ${JSON.stringify(marker)}::jsonb)` }).where(and( + eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.id, input.actionId))); +} + +/** Not yet checked, or due for another check. */ +export function freshContinuationCheckDue(now: Date) { + return sql`(${issueRecoveryActions.evidence}->${FRESH_CONTINUATION_CHECK_KEY} is null + or coalesce((${issueRecoveryActions.evidence}#>>'{freshContinuationCheck,nextCheckAt}')::bigint, 9223372036854775807) <= ${now.getTime()})`; +} + +/** + * Holds that today keep a task waiting with no automatic continuation, including + * every shape older releases saved: settled-but-blocked no-replay holds, and + * saved-work recoveries that finished or gave up. Exact recovery still under + * way is excluded (it is checked again by its owner and here afterwards). + */ +export function heldExecutionsAwaitingFreshContinuation(db: Db, now: Date, limit: number) { + return db.select({ id: issueRecoveryActions.id, companyId: issueRecoveryActions.companyId, + runId: sql`coalesce(${issueRecoveryActions.evidence}->>'runId', ${issueRecoveryActions.evidence}->>'sourceRunId')` }) + .from(issueRecoveryActions).innerJoin(issues, and(eq(issues.id, issueRecoveryActions.sourceIssueId), + eq(issues.companyId, issueRecoveryActions.companyId))) + .where(and(heldExecutionWhere(), freshContinuationCheckDue(now))) + .orderBy(asc(issueRecoveryActions.updatedAt), asc(issueRecoveryActions.id)) + .limit(limit); +} + +/** Held reconciliation records of a task's latest unfinished run (joined to its task). */ +function heldExecutionWhere(options: { includeActive?: boolean } = {}) { + return and( + inArray(issueRecoveryActions.cause, [...EXECUTION_RECONCILIATION_CAUSES]), + sql`${issueRecoveryActions.evidence}->'executionReconciliation' is null`, + sql`${issueRecoveryActions.evidence}->'freshContinuation' is null`, + sql`coalesce(${issueRecoveryActions.evidence}->>'runId', ${issueRecoveryActions.evidence}->>'sourceRunId') is not null`, + or( + sql`${issueRecoveryActions.evidence}->'automaticRecovery'->>'replay' = 'blocked'`, + and(inArray(issueRecoveryActions.status, ["active", "escalated"]), + sql`${issueRecoveryActions.evidence}#>>'{systemRecovery,state}' in ('complete', 'exhausted')`), + options.includeActive ? and(inArray(issueRecoveryActions.status, ["active", "escalated"]), + eq(issueRecoveryActions.kind, "active_run_watchdog")) : undefined, + // Saved-work recovery still under way: checked so its bound is reached + // (exact recovery keeps its first chance inside the fallback). + sql`${issueRecoveryActions.evidence}#>>'{systemRecovery,state}' in ('scheduled', 'running', 'awaiting_evidence')`, + ), + isNull(issueRecoveryActions.ownerUserId), + sql`${issues.status} not in ('done', 'cancelled')`, + sql`${issues.assigneeAgentId} is not null`, + // Only the task's latest run, unfinished and still its assignee's: other + // holds are history, and are never touched here. + sql`exists (select 1 from ${heartbeatRuns} source where source.company_id = ${issueRecoveryActions.companyId} + and source.id::text = coalesce(${issueRecoveryActions.evidence}->>'runId', ${issueRecoveryActions.evidence}->>'sourceRunId') + and source.status in ('failed', 'timed_out', 'interrupted', 'cancelled') and source.finished_at is not null + and source.agent_id = ${issues.assigneeAgentId} + and not exists (select 1 from ${heartbeatRuns} newer where newer.company_id = source.company_id and newer.id <> source.id + and (newer.native_issue_id = ${issues.id} or newer.issue_id = ${issues.id} or newer.context_snapshot->>'issueId' = ${issues.id}::text) + and (newer.status in ('queued', 'running', 'scheduled_retry') or (newer.created_at, newer.id) > (source.created_at, source.id))))`, + )!; +} + +/** The earliest time a deferred check becomes due again, if any. */ +export async function nextFreshContinuationCheckAt(db: Db): Promise { + // The same records the held-run query and the disposition pass would select; + // a deadline on a record nothing would act on never schedules a scan. + // That includes active holds that backed off: the disposition pass rechecks + // them when due, and nothing else would wake it then. + const [held] = await db.select({ at: sql`min((${issueRecoveryActions.evidence}#>>'{freshContinuationCheck,nextCheckAt}')::bigint)` }) + .from(issueRecoveryActions).innerJoin(issues, and(eq(issues.id, issueRecoveryActions.sourceIssueId), + eq(issues.companyId, issueRecoveryActions.companyId))) + .where(and(heldExecutionWhere({ includeActive: true }), + sql`${issueRecoveryActions.evidence}#>>'{freshContinuationCheck,nextCheckAt}' is not null`)); + return held?.at ? Number(held.at) : null; +} + +/** + * Continues tasks held by recovery records, including records saved by older + * releases, so tasks already waiting continue after deploy without a Retry. + * Runs on the execution-disposition worker. Bounded per pass. + */ +export async function continueHeldExecutions(db: Db, now = new Date(), limit = 25) { + const candidates = await heldExecutionsAwaitingFreshContinuation(db, now, limit); + let continued = 0; + const seen = new Set(); + for (const candidate of candidates) { + if (!candidate.runId || seen.has(candidate.runId)) continue; + seen.add(candidate.runId); + try { + const result = await ensureFreshContinuation(db, { companyId: candidate.companyId, runId: candidate.runId, + trigger: "held_recovery", now }); + if (result.kind === "continued") continued += 1; + else await recordFreshContinuationCheck(db, { companyId: candidate.companyId, actionId: candidate.id }, result, now); + } catch (error) { + logger.warn({ err: error, recoveryActionId: candidate.id }, "Fresh continuation of a held task deferred"); + await recordFreshContinuationCheck(db, { companyId: candidate.companyId, actionId: candidate.id }, + { kind: "exact_recovery_pending", reason: "fallback_failed", retryAt: new Date(now.getTime() + EXACT_RECOVERY_RECHECK_MS) }, now) + .catch(() => undefined); + } + } + return { checked: seen.size, continued }; +} + +/** Holds settled together with a primary record follow its final delivery + * state, so no coalesced hold outlives the record it points at. */ +export async function settleCoalescedFreshContinuationHolds(db: Db, input: { companyId: string; primaryId: string; + delivery: "delivered" | "invalidated"; continuationRunId?: string | null }) { + await db.update(issueRecoveryActions).set({ evidence: sql`${issueRecoveryActions.evidence} || ${JSON.stringify({ + continuationDelivery: input.delivery, ...(input.continuationRunId ? { continuationRunId: input.continuationRunId } : {}) })}::jsonb` }) + .where(and(eq(issueRecoveryActions.companyId, input.companyId), + sql`${issueRecoveryActions.evidence}->>'coalescedIntoRecoveryActionId' = ${input.primaryId}`, + sql`${issueRecoveryActions.evidence}->>'continuationDelivery' = 'coalesced'`)); +} + +/** A fresh continuation of this task is recorded and its run does not exist yet. */ +export async function hasPendingFreshContinuation(db: Db, companyId: string, issueId: string) { + const [row] = await db.select({ id: issueRecoveryActions.id }).from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.companyId, companyId), eq(issueRecoveryActions.sourceIssueId, issueId), + eq(issueRecoveryActions.status, "resolved"), + sql`${issueRecoveryActions.evidence}->>'continuationDelivery' = 'pending'`, + sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,schema}' = ${FRESH_CONTINUATION_SCHEMA}`)).limit(1); + return Boolean(row); +} + +/** Newest-first list of fresh continuations of one task (diagnostics and tests). */ +export async function listFreshContinuations(db: Db, input: { companyId: string; issueId: string }) { + return db.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, input.companyId), + eq(issueRecoveryActions.sourceIssueId, input.issueId), + sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,schema}' = ${FRESH_CONTINUATION_SCHEMA}`, + gt(sql`${issueRecoveryActions.evidence}#>>'{freshContinuation,recordedAt}'`, ""))) + .orderBy(desc(issueRecoveryActions.updatedAt)); +} diff --git a/server/src/services/fresh-workspace-continuation.ts b/server/src/services/fresh-workspace-continuation.ts index c05d2b3c233..710147a2bfd 100644 --- a/server/src/services/fresh-workspace-continuation.ts +++ b/server/src/services/fresh-workspace-continuation.ts @@ -20,6 +20,7 @@ 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"; +import { readFreshContinuationReadiness } from "./fresh-continuation-fallback.js"; export type ContinuationReadiness = | { mode: "resume_preserved_workspace"; preservationReceiptId: string } @@ -360,6 +361,11 @@ export async function readFreshWorkspaceReadiness(db: Db, run: Pick>'{explicitUserContinuation,runId}' = ${run.id}`, diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index d51f66b3bd4..4adbbeb259e 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -3,6 +3,7 @@ import { connectionIntentService } from "../connection-intents.js"; import { verifyBlockerStallWake } from "../recovery/blocker-stall-wakeups.js"; import { CONTEXT_COMPACTION_WAKE_REASON, ContextCompactionError, isContextCompactionRun, readContextCompactionRequest } from "../context-compaction.js"; import { isProcessRunAdmissionClosed } from "./run-admission.js"; +import { continueFreshInTransaction, hasPendingFreshContinuation, settleCoalescedFreshContinuationHolds } from "../fresh-continuation-fallback.js"; import { refreshRunStartYieldIfStale } from "../run-start-handover.js"; import { deliveredQueuedCommentIds } from "../queued-comment-delivery.js"; import { hasAutomaticInteractionDeliveryHold, INTERACTION_DELIVERY_DENIED, recheckQueuedRunInteractions, withInteractionDeliveryOrigin } from "../agent-interaction-delivery.js"; @@ -1256,6 +1257,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende if (!previousRunId || previousRunId === run.id) continue; const [previous] = await tx.select({ status: heartbeatRuns.status, agentId: heartbeatRuns.agentId, issueId: heartbeatRuns.issueId, nativeIssueId: heartbeatRuns.nativeIssueId, + supersededByFreshContinuation: sql`${heartbeatRuns.resultJson} ? 'freshContinuationSupersededAt'`, contextIssueId: sql`coalesce(${heartbeatRuns.contextSnapshot}->>'issueId', ${heartbeatRuns.contextSnapshot}->>'taskId')`, }) .from(heartbeatRuns).where(and( @@ -1270,7 +1272,10 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende liveRunExecutions.has(previousRunId)) { return declined("predecessor_still_executing", previousRunId); } - if (await hasPendingRunCleanup(tx, run.companyId, previousRunId)) { + // A fresh continuation replaced the predecessor: its writes are revoked + // and it shares no workspace with this run (a fenced remote epoch or a + // new isolated workspace), so its cleanup continues without holding it. + if (!previous?.supersededByFreshContinuation && await hasPendingRunCleanup(tx, run.companyId, previousRunId)) { return declined("predecessor_cleanup_pending", previousRunId); } } @@ -3632,6 +3637,27 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende } if (action.evidence.continuationDelivery !== "pending") return { kind: "skipped" as const }; + // Under the task lock: a fresh continuation is the task's next run + // only while nothing else continued it. A run started since it was + // recorded (active or already finished, from a person's Retry or + // saved input) consumes it, and a task that moved to review gets none. + const freshRecordedAt = readNonEmptyString(parseObject(action.evidence.freshContinuation).recordedAt); + if (freshRecordedAt) { + const [intervening] = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, issue.companyId), sql`${heartbeatRuns.id}::text <> ${sourceRunId}`, + or(eq(heartbeatRuns.nativeIssueId, issue.id), eq(heartbeatRuns.issueId, issue.id), + sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issue.id}::text`), + sql`${heartbeatRuns.createdAt} >= ${freshRecordedAt}::timestamptz`)).limit(1); + if (intervening || issue.status === "in_review") { + await tx.update(issueRecoveryActions).set({ evidence: sql`${issueRecoveryActions.evidence} || ${JSON.stringify( + intervening ? { continuationDelivery: "delivered", continuationRunId: intervening.id, continuationSupersededByRun: true } + : { continuationDelivery: "invalidated", continuationInvalidatedReason: "in_review" })}::jsonb` }) + .where(and(eq(issueRecoveryActions.companyId, issue.companyId), eq(issueRecoveryActions.id, action.id))); + await settleCoalescedFreshContinuationHolds(tx as unknown as Db, { companyId: issue.companyId, primaryId: action.id, + delivery: intervening ? "delivered" : "invalidated", continuationRunId: intervening?.id ?? null }); + return { kind: "skipped" as const }; + } + } const [reconciledRun] = await tx.select().from(heartbeatRuns).where(and( eq(heartbeatRuns.companyId, issue.companyId), eq(heartbeatRuns.id, sourceRunId), )); @@ -3727,6 +3753,18 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende const continuationHold = () => executionBlocker ?? { recoveryActionId: null, cause: "native_continuation_requires_reconciliation" as const, nextAction: continuationWait.message, }; + // Only system continuation wakes (sweeps, monitors, timers) reach + // the fresh-continuation fallback. A person's Retry, message or + // queued send keeps its own exact admission; the disposition worker + // settles the hold through the same fallback, and the saved input + // then continues the task. + const systemWake = opts.requestedByActorType !== "user" && !taskRetryActorId && !wakeCommentId + && !durableRequest && !opts.queuedCommentInterruptId && !opts.queuedCommentRequestId && !opts.failedRunId + && !executionReconciliationWake; + // A recorded fresh continuation that has no run yet is this task's + // next run: another system wake is coalesced into it, never a second run. + if (systemWake && !executionBlocker && await hasPendingFreshContinuation(tx as unknown as Db, issue.companyId, issue.id)) + return { kind: "skipped" as const }; if ((executionBlocker || opts.queuedCommentInterruptId) && !ownsReconstructionContinuation && !(await admitExplicitNativeContinuation({ db: tx as unknown as Db, companyId: issue.companyId, issueId: issue.id, agentId, actorType: taskRetryActorId ? "user" : opts.requestedByActorType, actorId: taskRetryActorId ?? opts.requestedByActorId, @@ -3739,7 +3777,23 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende interactionPayload: payload, dryRun: true, onBlocked: (reason, message) => { continuationBlocked = true; continuationWait = { reason, message }; }, - })) && (executionBlocker || (continuationBlocked && !verifiedConversationReset))) return deferBlockedExecution(continuationHold()); + })) && (executionBlocker || (continuationBlocked && !verifiedConversationReset))) { + // A hold left by an unfinished run never refuses an ordinary + // continuation: unless its cause is the person's, the fallback + // settles it in this transaction and this wake becomes the fresh + // continuation from the task's saved work. + // Agent Chat conversations keep their own owner-bound continuation. + const freshSourceRunId = systemWake && executionBlocker?.recoveryActionId && executionBlocker.runId + && !issue.conversationAgentId ? executionBlocker.runId : null; + // The continuation is recorded as pending and owned by the + // execution-continuation worker until a run for it exists: a later + // gate (daily limit, slots, pause, budget), a skip or a crash can + // never consume it. This system wake is coalesced into it. + const fresh = freshSourceRunId ? await continueFreshInTransaction(tx as unknown as Db, { + companyId: issue.companyId, runId: freshSourceRunId, trigger: "continuation_wake", delivery: "record" }) : null; + if (fresh?.kind !== "continued" && fresh?.kind !== "already_continued") return deferBlockedExecution(continuationHold()); + return { kind: "skipped" as const }; + } if ( diff --git a/server/src/services/native-runtime/native-controller-host-recovery.ts b/server/src/services/native-runtime/native-controller-host-recovery.ts index eb0a1602ef3..00c8391492e 100644 --- a/server/src/services/native-runtime/native-controller-host-recovery.ts +++ b/server/src/services/native-runtime/native-controller-host-recovery.ts @@ -28,9 +28,10 @@ export async function requestNativeControllerStopConfirmation(tx: Db, coordinato evidence: { runId: coordinator.runId, controller: { bootId: coordinator.controllerBootId, pid: coordinator.controllerPid, hostHash: coordinator.controllerHostHash, processStartedAt: coordinator.controllerProcessStartedAt?.toISOString() ?? null } }, - nextAction: "Paperclip cannot verify that this run's previous server stopped from the current host. " - + "Confirm that the previous server process has stopped (for example, its " - + "container was replaced), then recovery checks the saved run. Controller confirmation does not confirm that its provider or tools stopped.", + // Optional faster path: without a confirmation, the run ends after a + // bounded wait and the task continues in a fresh, isolated run. + nextAction: "The server running this task restarted. Paperclip continues the task in a fresh run shortly. " + + "Confirming that the previous server stopped is optional and only makes that faster.", }).onConflictDoNothing(); } diff --git a/server/src/services/native-runtime/native-remote-retry-admission.test.ts b/server/src/services/native-runtime/native-remote-retry-admission.test.ts index c717dcd5ece..f34349e5ab1 100644 --- a/server/src/services/native-runtime/native-remote-retry-admission.test.ts +++ b/server/src/services/native-runtime/native-remote-retry-admission.test.ts @@ -651,7 +651,7 @@ describeEmbeddedPostgres("remote native retry execution admission", () => { expect(await f.db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId))) .toMatchObject([{ ownerType: "board", wakePolicy: null, evidence: { automaticAdmissionExhausted: true, executorStopEvidence: "unverified", providerPid: 1386, checkpointPreserved: true }, - nextAction: expect.stringContaining("original executor stop and state remain unverified") }]); + nextAction: "This run stopped before it finished. Your saved work is kept." }]); expect(await claimNativeRestartRecoveries({ db: f.db, controller: environment.current.successor, restartKind: "hard", runIds: [f.runId], now: new Date(now.getTime() + 3_600_000) })).toEqual([]); }); diff --git a/server/src/services/native-runtime/native-restart-recovery.ts b/server/src/services/native-runtime/native-restart-recovery.ts index 450e63c531a..6ddd401fcd9 100644 --- a/server/src/services/native-runtime/native-restart-recovery.ts +++ b/server/src/services/native-runtime/native-restart-recovery.ts @@ -989,6 +989,61 @@ export function appendBoundedRecoveryHistory(entry: Record) { )`; } +/** How long a lapsed controller whose process space cannot be verified is + * waited for before its run ends and the task continues in a fresh run. */ +export const NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS = 2 * 60_000; + +/** When the current, unbroken run of namespace waits for this reason began. */ +function namespaceWaitStartedAt(history: unknown, reason: string): number | null { + const entries = Array.isArray(history) ? history as Array> : []; + let since: number | null = null; + for (let index = entries.length - 1; index >= 0; index--) { + const entry = entries[index]!; + if (entry.disposition !== "awaiting_evidence" || entry.reason !== reason) break; + const at = typeof entry.at === "string" ? Date.parse(entry.at) : NaN; + if (Number.isFinite(at)) since = at; + } + return since; +} + +/** Ends a run whose lapsed controller cannot be verified, like a blocked + * restart recovery, and records a system-owned hold for the fallback. */ +async function endNamespaceUnverifiedRun(tx: Db, row: { + run: typeof heartbeatRuns.$inferSelect; coordinator: typeof nativeRunFinalizations.$inferSelect; + issueAssigneeAgentId: string | null; issueStatus: string; +}, now: Date, reason: string, event: ReturnType, recoveryRequestId: string | null) { + await notifyExecutionRunWork(tx, { companyId: row.run.companyId }); + await tx.update(nativeRunFinalizations).set({ phase: "terminal_failure", leaseOwner: null, leaseExpiresAt: null, + nextAttemptAt: null, failureCode: "native_restart_recovery_blocked", + failureDetail: { ...row.coordinator.failureDetail, reason, executorStopEvidence: "unverified" }, + recoveryState: "blocked", recoveryRequestId, recoveryHistory: appendBoundedRecoveryHistory(event), updatedAt: now, + }).where(and(eq(nativeRunFinalizations.runId, row.run.id), eq(nativeRunFinalizations.attempt, row.coordinator.attempt), + eq(nativeRunFinalizations.phase, row.coordinator.phase))); + await notifyExternalAgentSettlement(tx, { companyId: row.run.companyId, runId: row.run.id }); + await notifyNativeEnvironmentSettlement(tx, { companyId: row.run.companyId, runId: row.run.id }); + await notifyInstructionCollection(tx, { companyId: row.run.companyId, runId: row.run.id }); + await notifyCancelledWorkspacePreservation(tx, { companyId: row.run.companyId, runId: row.run.id }); + await notifyUnsafeWorkspaceExportRunChange(tx, row.run); + const [updatedRun] = await tx.update(heartbeatRuns).set({ status: "failed", nativePhase: "terminal_failure", + nativePhaseUpdatedAt: now, executionStatusDeliveryId: randomUUID(), finishedAt: now, + errorCode: "native_restart_recovery_blocked", error: reason, updatedAt: now, + }).where(eq(heartbeatRuns.id, row.run.id)).returning(); + await notifyNativeStatusReassessment(tx, { companyId: row.run.companyId, issueId: row.coordinator.issueId }); + await tx.update(issues).set({ executionRunId: null, updatedAt: now }).where(and(eq(issues.id, row.coordinator.issueId), + eq(issues.companyId, row.run.companyId), eq(issues.executionRunId, row.run.id))); + await tx.update(issues).set({ checkoutRunId: null, updatedAt: now }).where(and(eq(issues.id, row.coordinator.issueId), + eq(issues.companyId, row.run.companyId), eq(issues.checkoutRunId, row.run.id))); + if (row.issueAssigneeAgentId === row.run.agentId && !["done", "cancelled"].includes(row.issueStatus)) { + await issueRecoveryActionService(tx).upsertSourceScoped({ companyId: row.run.companyId, sourceIssueId: row.coordinator.issueId, + kind: "active_run_watchdog", ownerType: "system", returnOwnerAgentId: row.run.agentId, + cause: "native_restart_recovery_blocked", fingerprint: `native-restart:${row.run.id}`, + evidence: { runId: row.run.id, reason, executorStopEvidence: "unverified", providerAttempt: row.coordinator.attempt }, + nextAction: "The server running this task restarted. Paperclip continues the task in a fresh run from its saved work.", + maxAttempts: 3, wakePolicy: null, supersedeOnIdentityChange: true }); + } + if (updatedRun) await preserveNativeFailedWorkspace(tx, updatedRun); +} + /** Shared by restart inspection and failed-owner cleanup under their existing * issue/coordinator/run locks. Publishing attention never grants a new turn. */ export async function surfaceNativeControllerNamespaceAttention(db: Db, input: { @@ -1020,9 +1075,13 @@ export async function surfaceNativeControllerNamespaceAttention(db: Db, input: { evidence: { runId: input.run.id, reason, executorStopEvidence: "unverified", ...(!input.remoteProcess ? { controllerAuthority: { schema: "paperclip.native-controller-authority.v1", digest, leaseExpiresAt: input.coordinator.leaseExpiresAt!.toISOString() } } : {}) }, + // No person is required: once the previous controller has stopped + // renewing its lease for a bounded wait, the run ends and the task + // continues in a fresh, isolated run. Recording the stops is optional + // and only makes that faster. nextAction: input.remoteProcess - ? "Use the task's ordinary Stop action and its environment provider's stop/cleanup recovery. Wait for that exact controller/provider acknowledgement. Local PID checks and local containment confirmation cannot authorize remote recovery." - : "Stop the original controller and provider on their original host. After the saved lease expires, a board operator must record both stops and review action outcomes. Recording containment does not retry the task.", + ? "The server running this task restarted. Paperclip continues the task in a fresh run from its saved work shortly. Using the task's ordinary Stop action is optional and only makes that faster." + : "The server running this task restarted. Paperclip continues the task in a fresh run from its saved work shortly.", createOnly: !existing, supersedeOnIdentityChange: true, attemptCount: 0, maxAttempts: null, timeoutAt: null, lastAttemptAt: null, wakePolicy: null, monitorPolicy: null, @@ -1366,6 +1425,29 @@ export async function claimNativeRestartRecoveries(input: { if (!takeover.allowed && ["controller_host_unrecorded", "controller_host_unprovable"].includes(takeover.reason)) { await requestNativeControllerStopConfirmation(tx as unknown as Db, row.coordinator); } + // The previous controller's lease lapsed (a live one is still renewing it + // and is waited for above) but its process space cannot be verified from + // here. That is system uncertainty, not a person's decision: after a + // bounded wait the run ends, stops holding the task and the agent's + // slots, and the fresh-continuation fallback continues the task with the + // old run's writes revoked and a new workspace root. + // The same holds when the previous controller's host was never recorded + // or cannot be proven from here: confirming its stop is optional. + const unverifiableLapsedController = !takeover.allowed && !nonExecutionOwner + && (row.coordinator.leaseExpiresAt === null || row.coordinator.leaseExpiresAt <= now) + && (namespaceAttentionNeeded || ["controller_host_unrecorded", "controller_host_unprovable"].includes(takeover.reason)); + if (unverifiableLapsedController) { + const waitingSince = namespaceWaitStartedAt(row.coordinator.recoveryHistory, takeover.reason); + if (waitingSince !== null && now.getTime() - waitingSince >= NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS) { + await endNamespaceUnverifiedRun(tx as unknown as Db, row, now, takeover.reason, historyEntry({ + now, restartKind: input.restartKind, controller, generation: row.coordinator.controllerGeneration, + disposition: "blocked", reason: takeover.reason, requestId: input.recoveryRequestId ?? null, + providerAttempt: row.coordinator.attempt, processPid: row.run.processPid, processStartedAt: row.run.processStartedAt, + hasCheckpoint: false, hasProviderEvidence: false, stderrTail: row.run.stderrExcerpt, + }), input.recoveryRequestId ?? null); + return { kind: "blocked", runId: row.run.id, reason: takeover.reason } as const; + } + } if (!takeover.allowed) { if (namespaceAttentionNeeded) { await surfaceNativeControllerNamespaceAttention(tx as unknown as Db, { @@ -1418,7 +1500,9 @@ export async function claimNativeRestartRecoveries(input: { : ownControllerProcess && row.coordinator.leaseExpiresAt && row.coordinator.leaseExpiresAt > now && !input.handedOffForShutdown?.(row.run.id) ? { retryAt: row.coordinator.leaseExpiresAt } : ["controller_lease_held", "controller_lease_grace"].includes(takeover.reason) - ? { retryAt: new Date(now.getTime() + CONTROLLER_LEASE_RENEW_MS) } : {}), + ? { retryAt: new Date(now.getTime() + CONTROLLER_LEASE_RENEW_MS) } + // The bounded wait for an unverifiable controller is checked again when it ends. + : unverifiableLapsedController ? { retryAt: new Date(now.getTime() + NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS) } : {}), } as const; } @@ -1728,9 +1812,11 @@ export async function claimNativeRestartRecoveries(input: { const reason = hold?.reason ?? (ownershipChanged ? "task_ownership_or_status_changed" : exhaustedRemoteRetry ? "execution_recovery_budget_exhausted" : classification.reason); - const nextAction = hold - ? "Automatic admission checks exhausted. The original executor stop and state remain unverified. The provider PID, checkpoint and task bindings are preserved; reconcile that execution before starting fresh work." - : "Inspect the preserved checkpoint and reconcile the previous execution before starting a fresh session."; + // No person is asked to inspect or reconcile: unless the cause is the + // person's, the fresh-continuation fallback continues the task. + // Shown to people: plain words only. A person's Stop or pause keeps the + // task as they asked; otherwise the fallback continues it. + const nextAction = "This run stopped before it finished. Your saved work is kept."; if (!claimKind) { const generation = row.coordinator.controllerGeneration; @@ -2048,11 +2134,74 @@ export async function claimNativeRestartRecoveries(input: { if (terminalRunToReport) void reportRunFailure(input.db, terminalRunToReport); if (claimScope && "leaseOwner" in disposition) input.onClaim?.(disposition, claimScope); - dispositions.push(disposition); + dispositions.push(disposition.kind === "awaiting_evidence" + ? await boundAwaitingEvidence(input.db, candidate, disposition, now, input.restartKind) + : disposition); } return dispositions; } +/** Waits this process resolves by itself (its own executor, a locked row). */ +const SELF_RESOLVING_WAITS = ["current_controller_preparing", "recovery_rows_busy"]; +/** Hard cap on any restart-recovery wait whose owner is not renewing a lease. */ +export const NATIVE_RESTART_EVIDENCE_HARD_CAP_MS = 10 * 60_000; + +/** + * Every restart-recovery wait has an owner and a bound. Each awaiting-evidence + * disposition is checked again (`retryAt`, at most two minutes out). Once the + * previous controller's lease has lapsed for `NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS`, + * or the wait has lasted `NATIVE_RESTART_EVIDENCE_HARD_CAP_MS`, and no live + * controller is renewing a lease, the run ends: it stops holding the task and + * the agent's slots, and the fresh-continuation fallback continues the task, + * isolated. A controller that is still renewing its lease is never ended early. + */ +async function boundAwaitingEvidence(db: Db, candidate: { runId: string; companyId: string; issueId: string }, + disposition: { kind: "awaiting_evidence"; runId: string; reason: string; retryAt?: Date; transitionUnchanged?: boolean }, now: Date, + restartKind: NativeRestartKind): Promise { + // A wait without its own recheck gets one; an owner's own schedule is kept. + const recheck = disposition.retryAt ?? new Date(now.getTime() + NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS); + const waiting = { ...disposition, retryAt: recheck }; + if (SELF_RESOLVING_WAITS.includes(disposition.reason)) return disposition; + try { + return await db.transaction(async tx => { + const [issue] = await tx.select({ id: issues.id }).from(issues).where(and(eq(issues.id, candidate.issueId), + eq(issues.companyId, candidate.companyId))).for("update", { skipLocked: true }); + if (!issue) return waiting; + const [row] = await tx.select({ run: heartbeatRuns, coordinator: nativeRunFinalizations, + issueAssigneeAgentId: issues.assigneeAgentId, issueStatus: issues.status }) + .from(heartbeatRuns).innerJoin(nativeRunFinalizations, eq(nativeRunFinalizations.runId, heartbeatRuns.id)) + .innerJoin(issues, eq(issues.id, nativeRunFinalizations.issueId)) + .where(and(eq(heartbeatRuns.id, candidate.runId), eq(heartbeatRuns.companyId, candidate.companyId))) + .for("update", { of: [heartbeatRuns, nativeRunFinalizations], skipLocked: true }); + if (!row || !["running", "queued"].includes(row.run.status) || row.coordinator.phase === "committed" + || row.coordinator.resultId) return waiting; + const leaseExpiresAt = row.coordinator.leaseExpiresAt?.getTime() ?? 0; + // A controller that still renews its lease is alive: never ended early. + if (leaseExpiresAt > now.getTime()) return waiting; + const detail = (row.coordinator.failureDetail ?? {}) as Record; + const since = typeof detail.restartEvidenceWaitSince === "string" ? Date.parse(detail.restartEvidenceWaitSince) : NaN; + if (!Number.isFinite(since)) { + await tx.update(nativeRunFinalizations).set({ failureDetail: sql`coalesce(${nativeRunFinalizations.failureDetail}, '{}'::jsonb) + || ${JSON.stringify({ restartEvidenceWaitSince: now.toISOString() })}::jsonb` }) + .where(eq(nativeRunFinalizations.runId, row.run.id)); + return waiting; + } + const lapsedFor = now.getTime() - Math.max(since, leaseExpiresAt); + if (lapsedFor < NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS && now.getTime() - since < NATIVE_RESTART_EVIDENCE_HARD_CAP_MS) return waiting; + const reason = `restart_evidence_timeout:${disposition.reason}`.slice(0, 120); + const controller = await currentNativeControllerIdentity(); + await endNamespaceUnverifiedRun(tx as unknown as Db, row, now, reason, historyEntry({ now, restartKind, controller, + generation: row.coordinator.controllerGeneration, disposition: "blocked", reason, requestId: null, + providerAttempt: row.coordinator.attempt, processPid: row.run.processPid, processStartedAt: row.run.processStartedAt, + hasCheckpoint: false, hasProviderEvidence: false, stderrTail: row.run.stderrExcerpt }), null); + return { kind: "blocked" as const, runId: row.run.id, reason }; + }); + } catch (error) { + logger.warn({ err: error, runId: candidate.runId }, "bounded restart-recovery wait check deferred"); + return waiting; + } +} + export async function nativeRestartRecoverySummary(db: Db) { const rows = await db .select({ 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 cf50f4d54b1..04152a91dac 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 @@ -97,7 +97,8 @@ vi.mock("../../sentry.js", async () => { captureRunFailure: mockCaptureRunFailure, }; }); -import { claimNativeRestartRecoveries, currentNativeControllerIdentity, NATIVE_NO_PROGRESS_RESTART_LIMIT, NATIVE_PROGRESS_CREDIT_GENERATION_LIMIT, NATIVE_RESTART_RECOVERY_FAILED, nextNativeProviderAttempt, type NativeControllerIdentity } from "./native-restart-recovery.js"; +import { ensureFreshContinuation } from "../fresh-continuation-fallback.js"; +import { claimNativeRestartRecoveries, currentNativeControllerIdentity, NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS, NATIVE_NO_PROGRESS_RESTART_LIMIT, NATIVE_PROGRESS_CREDIT_GENERATION_LIMIT, NATIVE_RESTART_RECOVERY_FAILED, nextNativeProviderAttempt, type NativeControllerIdentity } from "./native-restart-recovery.js"; import { taskInterruptionPresentation } from "../task-interruption-presentation.js"; import { requestTaskRetry } from "../task-retry.js"; @@ -2345,6 +2346,95 @@ process.on("SIGTERM", () => child.kill("SIGTERM")); ]); }); + // The two-server swap: the new server sees a mid-tool run whose lapsed + // controller lived in another process space it cannot verify. After the + // bounded wait the run ends (freeing the task and the agent's slot), and the + // fresh-continuation fallback continues the task once, isolated. + it("ends a mid-tool run whose lapsed controller cannot be verified after the bounded wait, then continues the task fresh", async () => { + const fixture = await seedRun(`NAMESPACE-END-${randomUUID()}`); + const oldBoot = randomUUID(), foreignSpace = `foreign:${currentProcessSpaceHash()}`, startedAt = new Date(Date.now() - 600_000); + await fixture.db.update(heartbeatRuns).set({ processPid: 2_000_000_011, processStartedAt: startedAt, processHostHash: foreignSpace }) + .where(eq(heartbeatRuns.id, fixture.runId)); + await fixture.db.update(nativeRunFinalizations).set({ controllerBootId: oldBoot, controllerPid: 2_000_000_012, + controllerProcessStartedAt: startedAt, controllerHostHash: foreignSpace, + leaseOwner: `foreign-in-flight:${randomUUID()}`, leaseExpiresAt: new Date(0), attempt: 1, controllerGeneration: 1, + // The new server has already waited past the bound for this exact reason. + recoveryHistory: [{ at: new Date(Date.now() - NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS - 1_000).toISOString(), + disposition: "awaiting_evidence", reason: "controller_process_space_unverified" }], + }).where(eq(nativeRunFinalizations.runId, fixture.runId)); + const dispositions = await claimNativeRestartRecoveries({ db: fixture.db, controller: successor, + restartKind: "hard", runIds: [fixture.runId] }); + expect(dispositions).toEqual([expect.objectContaining({ kind: "blocked", runId: fixture.runId, + reason: "controller_process_space_unverified" })]); + const [run] = await fixture.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId)); + expect(run).toMatchObject({ status: "failed", errorCode: "native_restart_recovery_blocked" }); + const [task] = await fixture.db.select().from(issues).where(eq(issues.id, fixture.issueId)); + expect(task!.executionRunId).toBeNull(); + const holds = await fixture.db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, fixture.issueId)); + const hold = holds.find(row => row.status === "active"); + expect(hold).toMatchObject({ ownerType: "system", cause: "native_restart_recovery_blocked" }); + expect(hold!.nextAction).not.toMatch(/operator|board|inspect|repair/i); + expect(await ensureFreshContinuation(fixture.db, { companyId, runId: fixture.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued" }); + }); + + // Graceful-drain hand-off: the outgoing server handed the run off, the new + // server classified it awaiting evidence, and the evidence never arrived. + // Every awaiting-evidence wait is bounded: once the old lease has lapsed for + // the bound, the run ends (its slot and task lock are freed) and the task + // continues once, fresh and isolated. + it("ends a handed-off run whose restart evidence never arrives within the bound, then continues the task fresh", async () => { + const fixture = await seedRun(`EVIDENCE-TIMEOUT-${randomUUID()}`); + const foreignSpace = `foreign:${currentProcessSpaceHash()}`, startedAt = new Date(Date.now() - 600_000); + await fixture.db.update(nativeRunFinalizations).set({ controllerBootId: randomUUID(), controllerPid: 2_000_000_031, + controllerProcessStartedAt: startedAt, controllerHostHash: foreignSpace, + leaseOwner: `drained:${randomUUID()}`, leaseExpiresAt: new Date(Date.now() - NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS - 5_000), + attempt: 1, controllerGeneration: 1, recoveryHistory: [], + failureDetail: { restartEvidenceWaitSince: new Date(Date.now() - NATIVE_NAMESPACE_UNVERIFIED_WAIT_MS - 1_000).toISOString() }, + }).where(eq(nativeRunFinalizations.runId, fixture.runId)); + const dispositions = await claimNativeRestartRecoveries({ db: fixture.db, controller: successor, + restartKind: "hard", runIds: [fixture.runId] }); + expect(dispositions).toEqual([expect.objectContaining({ kind: "blocked", runId: fixture.runId })]); + const [run] = await fixture.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId)); + expect(run).toMatchObject({ status: "failed", errorCode: "native_restart_recovery_blocked" }); + const [task] = await fixture.db.select().from(issues).where(eq(issues.id, fixture.issueId)); + expect(task!.executionRunId).toBeNull(); + expect(await ensureFreshContinuation(fixture.db, { companyId, runId: fixture.runId, trigger: "recovery_refused" })) + .toMatchObject({ kind: "continued" }); + }); + + it("schedules a recheck for every awaiting-evidence wait and does not end it before the bound", async () => { + const fixture = await seedRun(`EVIDENCE-EARLY-${randomUUID()}`); + const foreignSpace = `foreign:${currentProcessSpaceHash()}`, startedAt = new Date(Date.now() - 600_000); + await fixture.db.update(nativeRunFinalizations).set({ controllerBootId: randomUUID(), controllerPid: 2_000_000_041, + controllerProcessStartedAt: startedAt, controllerHostHash: foreignSpace, + leaseOwner: `drained:${randomUUID()}`, leaseExpiresAt: new Date(Date.now() - 1_000), attempt: 1, controllerGeneration: 1, + recoveryHistory: [], failureDetail: {}, + }).where(eq(nativeRunFinalizations.runId, fixture.runId)); + const dispositions = await claimNativeRestartRecoveries({ db: fixture.db, controller: successor, + restartKind: "hard", runIds: [fixture.runId] }); + expect(dispositions).toEqual([expect.objectContaining({ kind: "awaiting_evidence", runId: fixture.runId, retryAt: expect.any(Date) })]); + const [run] = await fixture.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId)); + expect(run!.status).not.toBe("failed"); + }); + + it("leaves a run alone while its foreign controller still renews its lease during a server overlap", async () => { + const fixture = await seedRun(`NAMESPACE-OVERLAP-${randomUUID()}`); + const foreignSpace = `foreign:${currentProcessSpaceHash()}`, startedAt = new Date(Date.now() - 600_000); + await fixture.db.update(nativeRunFinalizations).set({ controllerBootId: randomUUID(), controllerPid: 2_000_000_021, + controllerProcessStartedAt: startedAt, controllerHostHash: foreignSpace, + leaseOwner: `foreign-live:${randomUUID()}`, leaseExpiresAt: new Date(Date.now() + 60_000), attempt: 1, controllerGeneration: 1, + recoveryHistory: [{ at: new Date(Date.now() - 10 * 60_000).toISOString(), + disposition: "awaiting_evidence", reason: "controller_process_space_unverified" }], + }).where(eq(nativeRunFinalizations.runId, fixture.runId)); + const dispositions = await claimNativeRestartRecoveries({ db: fixture.db, controller: successor, + restartKind: "hard", runIds: [fixture.runId] }); + // A live lease is waited for; the bounded end never applies to it. + expect(dispositions).toEqual([expect.objectContaining({ kind: "awaiting_evidence", runId: fixture.runId })]); + const [run] = await fixture.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId)); + expect(run!.status).not.toBe("failed"); + }); + it.each(["stopped", "fenced"] as const)("keeps foreign local Runner and provider ownership after its controller is %s", async state => { const fixture = await seedRun(`FOREIGN-LOCAL-${state}-${randomUUID()}`); const oldBoot = randomUUID(), foreignSpace = `foreign:${currentProcessSpaceHash()}`; @@ -2388,8 +2478,9 @@ process.on("SIGTERM", () => child.kill("SIGTERM")); const [run] = await fixture.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId)); const stopped = await hasNativeLocalProcessStop(fixture.db, companyId, fixture.runId); expect(probes).toEqual([]); + // The namespace wait is bounded: it is checked again when the wait ends. expect(dispositions).toEqual([{ kind: "awaiting_evidence", runId: fixture.runId, - reason: "controller_process_space_unverified" }]); + reason: "controller_process_space_unverified", retryAt: expect.any(Date) }]); expect(claimed).not.toHaveBeenCalled(); expect(stamped).not.toHaveBeenCalled(); expect(stopped).toBe(false); diff --git a/server/src/services/task-interruption-presentation.ts b/server/src/services/task-interruption-presentation.ts index 1e8c2f59f15..abf793cada9 100644 --- a/server/src/services/task-interruption-presentation.ts +++ b/server/src/services/task-interruption-presentation.ts @@ -89,6 +89,9 @@ type ProjectionState = { * remote environment, or a scheduled close in this process. Without one, * nothing settles the gate by itself, so Retry is the way forward. */ cleanupSettling?: boolean; + /** The fresh-continuation fallback is continuing this run's task (recorded, + * not yet started) or will check it again at `nextCheckAt`. */ + freshContinuation?: { state: "continuing" } | { state: "scheduled"; nextCheckAt: number }; }; // A task read reports the change that made a task fail, not every later read of @@ -263,6 +266,10 @@ function projectTaskInterruptionState(issue: ProjectionIssue, input: ProjectionS && !(retryWait?.sourceRunId === run.id && retryWait.preparationStatus) && system?.state !== "exhausted") return { ...base, intentId: interruptWait.id, state: "working" }; if (["running", "queued"].includes(run.status)) return { ...base, state: "working" }; + // Paperclip is continuing the task by itself: no failed attempt and no Retry. + if (input.freshContinuation?.state === "continuing") return { ...base, state: "working", canRetry: false }; + if (input.freshContinuation?.state === "scheduled" && input.freshContinuation.nextCheckAt > now) + return { ...base, state: "retry_scheduled", nextRetryAt: new Date(input.freshContinuation.nextCheckAt).toISOString(), canRetry: false }; const deniedProject = deniedProjectId(issue, run); let projectAccess: TaskInterruptionPresentation["projectAccess"]; if (deniedProject !== undefined) { @@ -560,6 +567,25 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i inArray(sql`${issueRecoveryActions.evidence}->>'runId'`, runIds), sql`${issueRecoveryActions.evidence} ? 'systemRecovery'`, )).orderBy(issueRecoveryActions.sourceIssueId, desc(issueRecoveryActions.createdAt)) : []; + // The fresh-continuation fallback's records for these runs. + const freshRows = runIds.length ? await db.select({ issueId: issueRecoveryActions.sourceIssueId, + runId: sql`${issueRecoveryActions.evidence}->>'runId'`, + delivery: sql`${issueRecoveryActions.evidence}->>'continuationDelivery'`, + recorded: sql`${issueRecoveryActions.evidence} ? 'freshContinuation'`, + checkKind: sql`${issueRecoveryActions.evidence}#>>'{freshContinuationCheck,kind}'`, + nextCheckAt: sql`${issueRecoveryActions.evidence}#>>'{freshContinuationCheck,nextCheckAt}'` }) + .from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, companyId), inArray(issueRecoveryActions.sourceIssueId, ids), + inArray(sql`${issueRecoveryActions.evidence}->>'runId'`, runIds), + sql`(${issueRecoveryActions.evidence} ? 'freshContinuationSettlement' or ${issueRecoveryActions.evidence} ? 'freshContinuationCheck')`)) : []; + const freshContinuationFor = (issueId: string, runId: string | undefined): ProjectionState["freshContinuation"] => { + const rows = freshRows.filter(row => row.issueId === issueId && row.runId === runId); + // Only the primary record (it carries `freshContinuation`) says whether a + // continuation is still on its way; holds coalesced into it never do. + if (rows.some(row => row.recorded && ["pending", "not_requested"].includes(row.delivery ?? ""))) return { state: "continuing" }; + const scheduled = rows.filter(row => ["exact_recovery_pending", "backoff"].includes(row.checkKind ?? "") && row.nextCheckAt) + .map(row => Number(row.nextCheckAt)).sort((a, b) => a - b)[0]; + return scheduled ? { state: "scheduled", nextCheckAt: scheduled } : undefined; + }; const ownerStops = runIds.length ? await db.select({ issueId: issueRecoveryActions.sourceIssueId, runId: sql`${issueRecoveryActions.evidence}->>'runId'` }).from(issueRecoveryActions).where(and( eq(issueRecoveryActions.companyId, companyId), inArray(issueRecoveryActions.sourceIssueId, ids), @@ -659,6 +685,7 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i const facts = { run: runMap.get(issue.id), action: actionMap.get(issue.id), wait: waitMap.get(issue.id), retryWait: retryWaitMap.get(issue.id) }; const presentation = projectTaskInterruption(issue, { ...facts, + freshContinuation: freshContinuationFor(issue.id, facts.run?.id), interruptWait: interruptWaitFor(issue.id), projectAccessAllowed: denied?.length === 0, projectAccessProjectId: denied?.includes(issue.projectId ?? "") ? issue.projectId : null,