From c14f2fe45d198fe269717c2119f482ebb57edaf4 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 18:21:25 -0600 Subject: [PATCH 01/38] fix(native): read the scheduled-resume evidence the resume reconciler claimed (#20656) 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 > - #20645 lets a local same-run scheduled resume send the one same-conversation continuation for a turn lost on restore. It applies only when durable records prove three facts: the previous runner stopped, the attempt was admitted within the budget, and it is the same checkpointed conversation. > - It read the third proof from the coordinator's saved `failure_detail` while the phase was `retryable_failure`. > - In production, the resume reconciler (`claimNativeSessionResumptions`) claims the run first. It moves the coordinator to `observed` and clears `failure_detail`. So the executor never saw that evidence, and #20645 refused every real scheduled resume. > - The restart-chaos L7 wave showed this live. Codex B5 TM2 hit the exact path (`runner.drain` timeout, scheduled resume, `provider_turn_lost_on_restore`), sent no continuation, and needed Retry. > - This pull request makes the reconciler record that evidence durably when it claims the run, and makes the executor read it from there. > - The benefit is that #20645 works on the real path. The proof rule is unchanged. ## Linked Issues or Issue Description Refs #20645 **What happened?** Wave `w-20261110T212307-s9107` (L7, seed 9107, local, master plus #20645), task codex B5 TM2: - `native_session_recovery_failed: runner_local_connect_failed: PRP command runner.drain timed out`; - `retryable_failure` with `recoveryMode: "exact_checkpoint_resume"`, `recoverable`, `providerSessionEstablished` and `checkpointExists` all set; - `native.local_process_stopped`; - attempt 2 started; - `turn.failed` with `provider_turn_lost_on_restore` for the same turn ID that the checkpoint was running. No continuation was sent. The run failed with `native_provider_terminal_failed` and was preserved with `uncertain_provider_action`. **Expected behavior** The proven scheduled resume sends the single continuation. **Steps to reproduce** The new integration test below. The live path is timing-dependent (the L7 command in #20645). ## What Changed - `native-finalization-reconciler.ts`: when it claims a same-run resume, the reconciler appends one `same_run_resume` entry to `recovery_history`. The append is bounded like other history writes, and it runs in the same update that clears the failure. The entry copies `recoveryMode`, `recoverable`, `providerSessionEstablished`, `checkpointExists`, `successorRunId` and `replacementDenied` from the saved failure, with the controller boot and provider attempt. - `scheduled-resume-continuation.ts`: the evidence for the third proof now comes from either of two durable records: - the saved failure, when the executor claims a `retryable_failure` coordinator directly (unchanged); or - a reconciler claim: an `observed` coordinator whose last history entry is a `same_run_resume` entry naming the executor's own controller boot. The two other proofs are unchanged: the stop receipt, and an admitted attempt from 1 to 3. - `native-session-executor.ts`: passes the coordinator's last history entry and the controller boot to the decision. - `doc/execution-semantics.md`: describes the recorded evidence. Readers of `recovery_history` that look at the last entry do so only for restart claims, Stop recovery and shutdown suspension. Restart recovery's previous-claim lookup skips non-claim dispositions, so a `same_run_resume` entry does not change those paths. **Still refused** (tested): - every #20645 case; - the last history entry is not the resume claim, or there is no history; - the resume claim was recorded by another boot; - the claimed evidence is a bootstrap retry, has no checkpoint, or records a replacement; - a reconciler-claimed resume without a stop receipt. ## Verification - `native-scheduled-resume-continuation.integration.test.ts` now also runs through the real reconciler claim (`claimNativeSessionResumptions`) before `executePaperclipNativeSession`. On master the reconciler-claimed allowed case fails (`resumeInterruptedTurn` is false). With this change it is true, and the claim admits attempt 2. A reconciler-claimed resume without a stop receipt still passes false. - `scheduled-resume-continuation.test.ts`: decision cases for the reconciler-claim entry. - `native-session-resumption.test.ts` passes. 54 tests pass across the three files. - `cd server && npx tsc --noEmit` passes. - Live: not yet. The failing wave above is the reproduction. A rerun is timing-dependent. ## Risks - One more `recovery_history` entry per scheduled resume, inside the existing 20-entry bound. - The proof rule itself is unchanged. This only reads the same evidence from the record where it now survives. - No schema change. A run claimed by an earlier build has no `same_run_resume` entry, so it keeps the existing failure: refused, with Retry offered as today. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits, test runs). Extended reasoning. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- doc/execution-semantics.md | 11 +++++-- .../native-exact-resume-failure.test.ts | 11 +++++++ .../native-exact-resume-failure.ts | 2 +- .../native-finalization-reconciler.ts | 13 ++++---- .../native-runtime/native-restart-recovery.ts | 2 +- ...ed-resume-continuation.integration.test.ts | 27 +++++++++++++---- .../native-runtime/native-session-executor.ts | 3 ++ .../scheduled-resume-continuation.test.ts | 22 ++++++++++++++ .../scheduled-resume-continuation.ts | 30 +++++++++++++++++-- 9 files changed, 104 insertions(+), 17 deletions(-) diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 7101d22b1e3..67d40550fab 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -3349,9 +3349,14 @@ that process is gone. Second, the resume claimed a provider attempt within the three-attempt budget from a `retryable_failure` coordinator. Third, that failure saved `recoveryMode: "exact_checkpoint_resume"`, `recoverable`, `providerSessionEstablished` and `checkpointExists`, with no replacement recorded, -and the runner restores that same checkpointed conversation. A remote run, a -bootstrap retry, an ambiguous state, a missing or superseded stop record, an -exhausted budget, or a replacement session keeps the existing failure. +and the runner restores that same checkpointed conversation. The resume reconciler +clears the saved failure when it claims the run. So it first appends a +`same_run_resume` entry to `recovery_history` that copies those fields, together +with its controller boot. The executor then reads that entry. It must be the last +entry, and it must name the executor's boot. A remote run, a bootstrap retry, an +ambiguous state, a missing or superseded stop record, an exhausted budget, a +replacement session, or a claim entry from another boot or followed by another +entry keeps the existing failure. A restart can also land after the agent proposed its result but before the provider turn ended. When the restored runner proves that turn ended with the diff --git a/server/src/services/native-runtime/native-exact-resume-failure.test.ts b/server/src/services/native-runtime/native-exact-resume-failure.test.ts index 50405fe9157..4994667ab0f 100644 --- a/server/src/services/native-runtime/native-exact-resume-failure.test.ts +++ b/server/src/services/native-runtime/native-exact-resume-failure.test.ts @@ -50,7 +50,18 @@ describe("interruptedExactResumeCause", () => { }); }); + it("finds the interruption behind the resume reconciler's claim entry for the same attempt", () => { + const resumeClaim = { at: "2099-01-01T00:01:00.000Z", disposition: "same_run_resume", controllerBootId: "boot-1", + providerAttempt: 1, evidence: { recoveryMode: "exact_checkpoint_resume" } }; + expect(interruptedExactResumeCause({ ...claimed, recoveryHistory: [interruption, resumeClaim] })).toEqual({ + originalFailureCode: "native_session_interrupted", + originalMessage: "PRP command turn.start failed: classification=session_resume_required", + interruptedAttempt: 1, + }); + }); + it.each([ + ["a resume claim entry for a later provider attempt", { disposition: "same_run_resume", providerAttempt: 2 }], ["a wait for a later provider attempt", { disposition: "blocked", reason: "held", providerAttempt: 2 }], ["a later recovery entry that is not a wait", { disposition: "resume_dead_runner", reason: "restart", providerAttempt: 1 }], ])("does not reach past %s", (_name, later) => { diff --git a/server/src/services/native-runtime/native-exact-resume-failure.ts b/server/src/services/native-runtime/native-exact-resume-failure.ts index 21c150d416c..5fc73e95008 100644 --- a/server/src/services/native-runtime/native-exact-resume-failure.ts +++ b/server/src/services/native-runtime/native-exact-resume-failure.ts @@ -16,7 +16,7 @@ const FAILURE_DETAIL_MAX_CHARS = 2_000; const REFUSAL_MAX_CHARS = 480; const REFUSAL_SEPARATOR = "; exact checkpoint resume refused: "; /** Restart-recovery waits that keep the interrupted provider attempt. */ -const RECOVERY_WAIT_DISPOSITIONS: ReadonlySet = new Set(["blocked", "awaiting_evidence"]); +const RECOVERY_WAIT_DISPOSITIONS: ReadonlySet = new Set(["blocked", "awaiting_evidence", "same_run_resume"]); /** * Cuts to at most `max` UTF-16 code units without splitting a surrogate pair. diff --git a/server/src/services/native-runtime/native-finalization-reconciler.ts b/server/src/services/native-runtime/native-finalization-reconciler.ts index 97782172df6..c22b0389015 100644 --- a/server/src/services/native-runtime/native-finalization-reconciler.ts +++ b/server/src/services/native-runtime/native-finalization-reconciler.ts @@ -1,3 +1,5 @@ +import { sameRunResumeClaimEntry } from "./scheduled-resume-continuation.js"; +import { appendBoundedRecoveryHistory } from "./native-restart-recovery.js"; import { notifyLiveRunRecovery } from "../live-run-recovery-notifications.js"; import { currentControllerProcessStamp } from "../controller-process-identity.js"; import { NATIVE_SESSION_RESUMPTION_ISSUE_STATUSES } from "./native-session-resumption-statuses.js"; @@ -309,15 +311,16 @@ export async function claimNativeSessionResumptions(input: { const leaseExpiresAt = new Date(now.getTime() + 20 * 60_000); await notifyLiveRunRecovery(tx, { companyId: row.run.companyId, runId: row.run.id, agentId: row.run.agentId }); + const stamp = currentControllerProcessStamp(); + const resumeClaim = sameRunResumeClaimEntry({ at: now, controllerBootId: stamp.bootId, + providerAttempt: row.coordinator.attempt, failureDetail: row.coordinator.failureDetail }); const updated = await tx.update(nativeRunFinalizations).set({ phase: "observed", leaseOwner, leaseExpiresAt, - ...(() => { - const stamp = currentControllerProcessStamp(); - return { controllerBootId: stamp.bootId, controllerPid: stamp.pid, controllerHostHash: stamp.hostHash, - controllerProcessStartedAt: stamp.processStartedAt ? new Date(stamp.processStartedAt) : null }; - })(), + controllerBootId: stamp.bootId, controllerPid: stamp.pid, controllerHostHash: stamp.hostHash, + controllerProcessStartedAt: stamp.processStartedAt ? new Date(stamp.processStartedAt) : null, + recoveryHistory: appendBoundedRecoveryHistory(resumeClaim), failureCode: null, failureDetail: null, nextAttemptAt: null, diff --git a/server/src/services/native-runtime/native-restart-recovery.ts b/server/src/services/native-runtime/native-restart-recovery.ts index 7c825b3d318..ec0bce99dbd 100644 --- a/server/src/services/native-runtime/native-restart-recovery.ts +++ b/server/src/services/native-runtime/native-restart-recovery.ts @@ -963,7 +963,7 @@ function historyEntry(input: { } satisfies Record; } -function appendBoundedRecoveryHistory(entry: Record) { +export function appendBoundedRecoveryHistory(entry: Record) { const encoded = JSON.stringify(entry); return sql`( select coalesce(jsonb_agg(item order by ordinal), '[]'::jsonb) diff --git a/server/src/services/native-runtime/native-scheduled-resume-continuation.integration.test.ts b/server/src/services/native-runtime/native-scheduled-resume-continuation.integration.test.ts index 1d02ca75eec..22c96d48e3f 100644 --- a/server/src/services/native-runtime/native-scheduled-resume-continuation.integration.test.ts +++ b/server/src/services/native-runtime/native-scheduled-resume-continuation.integration.test.ts @@ -14,6 +14,7 @@ vi.mock("../../vendor/paperclip-runner/index.js", async (importOriginal) => ({ import { executePaperclipNativeSession } from "./native-session-executor.js"; import { buildNativeCompletionContract } from "./completion-contracts.js"; import { prepareNativeHeartbeatRun } from "./prepare-native-run.js"; +import { claimNativeSessionResumptions } from "./native-finalization-reconciler.js"; const EXITED_PID = 4_194_304; @@ -35,7 +36,7 @@ describe("a scheduled same-run resume reaching the provider runtime", () => { const exactResume = { recoveryMode: "exact_checkpoint_resume", recoverable: true, providerSessionEstablished: true, checkpointExists: true, originalFailureCode: "native_session_recovery_failed" }; - async function resumeOnce(options: { failureDetail: Record; stopRecorded: boolean }) { + async function resumeOnce(options: { failureDetail: Record; stopRecorded: boolean; viaReconciler?: boolean }) { const issueId = randomUUID(); const runId = randomUUID(); const [issue] = await db.insert(issues).values({ id: issueId, companyId, title: "Resume the lost turn", @@ -58,7 +59,12 @@ describe("a scheduled same-run resume reaching the provider runtime", () => { contract: buildNativeCompletionContract(issue!, { revision: contract!.revision }) }, interactionResponses: [], credentialBindings: [], }; - await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: execution } }).where(eq(heartbeatRuns.id, runId)); + await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: execution, + sessionCheckpoint: { backendKind: "runner", driverKind: "codex_app_server", sessionId: native.normalizedSessionId, + identity: { companyId, issueId, runId, agentId, sessionId: native.normalizedSessionId }, + providerSessionId: "provider-thread", cursor: "1", activeTurnId: "lost-turn", pendingRuntimeRequests: [], lineage: [] } }, + ...(options.viaReconciler ? { status: "failed" as const, nativePhase: "retryable_failure" } : {}) }) + .where(eq(heartbeatRuns.id, runId)); await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "retryable_failure", attempt: 1, failureCode: "native_session_interrupted", failureDetail: options.failureDetail }); const identity = { processPid: EXITED_PID, processGroupId: EXITED_PID, processStartedAt: new Date().toISOString() }; @@ -80,7 +86,13 @@ describe("a scheduled same-run resume reaching the provider runtime", () => { passed.push(input.resumeInterruptedTurn); throw new Error("scheduled_resume_fixture_stop"); }); - await executePaperclipNativeSession({ db, execution, runnerInstanceId: native.runnerInstanceId, backend: { + let leaseOwner: string | undefined; + if (options.viaReconciler) { + const claims = await claimNativeSessionResumptions({ db, runnerInstanceId: native.runnerInstanceId, runIds: [runId] }); + expect(claims).toEqual([expect.objectContaining({ runId })]); + leaseOwner = claims[0]!.leaseOwner; + } + await executePaperclipNativeSession({ db, execution, runnerInstanceId: native.runnerInstanceId, leaseOwner, backend: { descriptor: async () => { throw new Error("Unexpected provider call"); }, openSession: async () => { throw new Error("Unexpected provider call"); }, } }).catch(() => undefined); @@ -88,12 +100,17 @@ describe("a scheduled same-run resume reaching the provider runtime", () => { return { passed, coordinator: coordinator! }; } - it("lets the runtime continue a lost turn after a verified stop and an admitted attempt", async () => { - const { passed, coordinator } = await resumeOnce({ failureDetail: exactResume, stopRecorded: true }); + it.each([false, true])("lets the runtime continue a lost turn after a verified stop and an admitted attempt (claimed by the resume reconciler: %s)", async (viaReconciler) => { + const { passed, coordinator } = await resumeOnce({ failureDetail: exactResume, stopRecorded: true, viaReconciler }); expect(passed).toEqual([true]); expect(coordinator.attempt).toBe(2); }); + it("keeps the lost turn failing when the reconciler claimed a resume without a stop receipt", async () => { + const { passed } = await resumeOnce({ failureDetail: exactResume, stopRecorded: false, viaReconciler: true }); + expect(passed).toEqual([false]); + }); + it.each([ ["no stop of the previous runner was recorded", { failureDetail: exactResume, stopRecorded: false }], ["the saved failure is a bootstrap retry", { failureDetail: { ...exactResume, recoveryMode: "bootstrap_retry" }, stopRecorded: true }], diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index b8373d661ee..dafc06da83e 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -10371,6 +10371,9 @@ async function executePaperclipNativeSessionAttempt( targetKind: input.runnerExecutionTarget?.kind === "remote" ? "remote" : "local", coordinatorPhase: coordinator.phase, failureDetail: coordinator.failureDetail, + resumeClaim: Array.isArray(coordinator.recoveryHistory) + ? (coordinator.recoveryHistory.at(-1) as Record | undefined) ?? null : null, + controllerBootId: controller.bootId, admittedAttempt: nextAttempt, })).allowed; const nextControllerGeneration = recovering diff --git a/server/src/services/native-runtime/scheduled-resume-continuation.test.ts b/server/src/services/native-runtime/scheduled-resume-continuation.test.ts index b48033c0eaf..502c3e2657e 100644 --- a/server/src/services/native-runtime/scheduled-resume-continuation.test.ts +++ b/server/src/services/native-runtime/scheduled-resume-continuation.test.ts @@ -8,6 +8,7 @@ import { } from "../../__tests__/helpers/embedded-postgres.js"; import { decideScheduledResumeContinuation, + sameRunResumeClaimEntry, scheduledResumeContinuationAllowed, type ScheduledResumeContinuationEvidence, } from "./scheduled-resume-continuation.js"; @@ -53,6 +54,27 @@ describe("same-run scheduled resume continuation of a turn lost on restore", () ])("refuses when %s", (_name, evidence, reason) => { expect(decideScheduledResumeContinuation(evidence)).toEqual({ allowed: false, reason }); }); + + const resumeClaim = (patch: Record = {}, detail: Record = {}) => + ({ ...sameRunResumeClaimEntry({ at: new Date(), controllerBootId: "boot-1", providerAttempt: 1, + failureDetail: { ...proven.failureDetail, ...detail } }), ...patch }); + const claimed = (claim: Record | null, patch: Partial = {}) => + ({ ...proven, coordinatorPhase: "observed", failureDetail: null, resumeClaim: claim, controllerBootId: "boot-1", ...patch }); + + it("reads the evidence the resume reconciler recorded when it claimed the run", () => { + expect(decideScheduledResumeContinuation(claimed(resumeClaim()))).toEqual({ allowed: true }); + }); + + it.each<[string, ScheduledResumeContinuationEvidence, string]>([ + ["the last history entry is not the resume claim", claimed(resumeClaim({ disposition: "retryable_failure" })), "not_a_scheduled_same_run_resume"], + ["no history entry exists", claimed(null), "not_a_scheduled_same_run_resume"], + ["another boot recorded the resume claim", claimed(resumeClaim(), { controllerBootId: "boot-2" }), "not_a_scheduled_same_run_resume"], + ["the claimed failure was a bootstrap retry", claimed(resumeClaim({}, { recoveryMode: "bootstrap_retry" })), "not_an_exact_checkpoint_resume"], + ["the claimed failure had no checkpoint", claimed(resumeClaim({}, { checkpointExists: false })), "checkpoint_missing"], + ["the claimed failure recorded a replacement", claimed(resumeClaim({}, { successorRunId: "run-2" })), "replacement_recorded"], + ])("refuses a reconciler-claimed resume when %s", (_name, evidence, reason) => { + expect(decideScheduledResumeContinuation(evidence)).toEqual({ allowed: false, reason }); + }); }); const support = await getEmbeddedPostgresTestSupport(); diff --git a/server/src/services/native-runtime/scheduled-resume-continuation.ts b/server/src/services/native-runtime/scheduled-resume-continuation.ts index 4f315655909..215e540754a 100644 --- a/server/src/services/native-runtime/scheduled-resume-continuation.ts +++ b/server/src/services/native-runtime/scheduled-resume-continuation.ts @@ -2,6 +2,28 @@ import type { Db } from "@paperclipai/db"; import { readNativeLocalProcessStop } from "../native-local-process-stop.js"; import { NATIVE_PROVIDER_RECOVERY_ATTEMPT_LIMIT } from "./native-restart-recovery.js"; +export const SAME_RUN_RESUME_DISPOSITION = "same_run_resume"; + +export function sameRunResumeClaimEntry(input: { + at: Date; controllerBootId: string; providerAttempt: number; failureDetail: Record | null | undefined; +}) { + const detail = input.failureDetail ?? {}; + return { + at: input.at.toISOString(), + disposition: SAME_RUN_RESUME_DISPOSITION, + controllerBootId: input.controllerBootId, + providerAttempt: input.providerAttempt, + evidence: { + recoveryMode: detail.recoveryMode ?? null, + recoverable: detail.recoverable ?? null, + providerSessionEstablished: detail.providerSessionEstablished ?? null, + checkpointExists: detail.checkpointExists ?? null, + successorRunId: detail.successorRunId ?? null, + replacementDenied: detail.replacementDenied ?? null, + }, + }; +} + export type ScheduledResumeContinuationRefusal = | "restart_recovery_claim" | "remote_target" @@ -19,6 +41,8 @@ export interface ScheduledResumeContinuationEvidence { targetKind: "local" | "remote"; coordinatorPhase: string | null; failureDetail: Record | null | undefined; + resumeClaim?: Record | null; + controllerBootId?: string; admittedAttempt: number; localStop: { processPid: number } | null; } @@ -33,8 +57,10 @@ export function decideScheduledResumeContinuation( const refuse = (reason: ScheduledResumeContinuationRefusal) => ({ allowed: false as const, reason }); if (evidence.restartRecovery) return refuse("restart_recovery_claim"); if (evidence.targetKind !== "local") return refuse("remote_target"); - if (evidence.coordinatorPhase !== "retryable_failure") return refuse("not_a_scheduled_same_run_resume"); - const detail = evidence.failureDetail ?? {}; + const claimed = evidence.coordinatorPhase === "observed" && evidence.resumeClaim?.disposition === SAME_RUN_RESUME_DISPOSITION + && typeof evidence.controllerBootId === "string" && evidence.resumeClaim.controllerBootId === evidence.controllerBootId; + if (evidence.coordinatorPhase !== "retryable_failure" && !claimed) return refuse("not_a_scheduled_same_run_resume"); + const detail = (claimed ? evidence.resumeClaim?.evidence as Record | undefined : evidence.failureDetail) ?? {}; if (detail.recoveryMode !== "exact_checkpoint_resume") return refuse("not_an_exact_checkpoint_resume"); if (detail.recoverable !== true) return refuse("failure_not_recoverable"); if (detail.providerSessionEstablished !== true) return refuse("provider_session_not_established"); From 81c52e3666128186c5818ea7ab8a65bfe662fee3 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 18:25:59 -0600 Subject: [PATCH 02/38] perf(chat): find terminal GitHub responses by issue run indexes (#20671) 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 > - The GitHub chat channel posts a terminal response when an agent run for a GitHub request stops. A background sweep finds acknowledged response comments (`processed`, not final) whose issue is blocked or whose latest run is terminal > - For each candidate, the sweep reads the status of the latest run of the assigned agent for the issue. It matches runs with `coalesce(native_issue_id::text, context_snapshot->>'issueId')` > - No index has that expression. So PostgreSQL reads every run of the agent for each candidate, and it decompresses the large legacy `context_snapshot` of each run > - On a hosted test database, this statement ran 13 times at a mean of 11 s in a 38-minute window (149 s in total), with single runs of 16 s and 41 s > - This pull request splits the run match into its two disjoint branches. Each branch uses an existing issue index > - The benefit is that each candidate reads a few index entries instead of the agent's full run history. The returned rows do not change, and no migration is necessary ## Linked Issues or Issue Description **What existing behavior does this improve?** The discovery page query in `registerGitHubTerminalResponseWork` in `server/src/services/chat-channels/github/terminal-response-work.ts`. The query runs when the sweep reconstructs its candidates, and once or twice for each candidate check. **Subsystem affected** GitHub chat channel terminal-response recovery. **Current behavior** The `WHERE` clause has `issues.status = 'blocked' or (select r.status from heartbeat_runs r where r.company_id = ... and r.agent_id = ... and coalesce(r.native_issue_id::text, r.context_snapshot->>'issueId') = order by r.created_at desc, r.id desc limit 1) in ()`. The planner can only use `heartbeat_runs_company_agent_started_idx`. It reads all runs of the agent, then evaluates the `coalesce` on each row. That decompresses the context of each legacy run. The cost is the number of candidates times the number of agent runs. **Proposed behavior** The subquery takes the latest run from two branches and then the latest of the two: - runs with `native_issue_id = `, through `heartbeat_runs_company_native_issue_contract_id_uq` - runs with `native_issue_id is null and context_snapshot->>'issueId' = `, through `heartbeat_runs_company_ctx_issue_created_idx` The two branches are disjoint, and together they are exactly the rows where the `coalesce` is equal to the issue ID. Both branches and the outer query use the same order (`created_at desc, id desc`). So the selected run is the same, including ties. **Reason and benefit** This statement was the largest single-statement cost in the hosted window after the earlier database fixes. A local reproduction is about 490x faster on the default fixture, and the gain grows with the agent's run history. **Breaking changes** None. The API, the candidate rules and the results do not change. ## What Changed - Rewrite the latest-run status subquery in the GitHub terminal-response discovery page as two index-backed branches (native binding, and legacy context without a native binding). - Add two integration tests for the sweep. In the first, newer runs of the same agent that do not bind the issue (one with a native binding to another issue, but a legacy context that names this issue) must not hide the stopped run. In the second, a newer active run with a native binding to the issue keeps the request waiting. - Add `scripts/benchmark-github-terminal-response-sweep.ts`. It captures the SQL that the real worker generates at a baseline commit and at `HEAD`, compares all rows, and measures both. ## Verification Cause and thesis. The cost comes from the `coalesce` run match, which has no index and makes each candidate scan the agent's run history. Thesis: if each precedence branch uses its own issue index, the cost of the page no longer depends on the agent's run count, and the rows stay identical. The benchmark confirms the thesis. Local SQL benchmark: ```sh pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-github-terminal-response-sweep.ts --baseline-ref=7b33384446 ``` Fixture (synthetic): two companies, each with one GitHub endpoint and one assigned agent. Each issue has one GitHub response comment. The first N comments are acknowledged and not final; the others are final. Every tenth issue is blocked. Runs alternate between native binding and legacy context, and each run has a 4 KiB incompressible context. The fixture also has these edge cases: newer active runs with a native binding to another issue but a legacy context that names this issue, active runs that tie on `created_at` with the latest run (between native and legacy runs), and newer active runs of another agent. The benchmark compares every column of every candidate row (the page limit is lifted for this check). Embedded PostgreSQL 18.1 on an Apple laptop. The hosted database is Neon with different compute, so absolute times are local SQL measurements only. Each size has 2 warmups and then alternates the baseline and the treatment. | Size | Runs (both companies) | Candidate rows equal | Baseline median (range) | Treatment median (range) | Speedup | | --- | --- | --- | --- | --- | --- | | Small: 200 issues, 3 runs each, 20 candidates, 7 samples | 1,372 | 26 of 26 | 18.7 ms (17.7–20.8) | 3.8 ms (3.3–4.3) | 4.9x | | Default: 1,500 issues, 8 runs each, 150 candidates, 7 samples | 25,300 (156 MB) | 200 of 200 | 3,697 ms (2,875–4,032) | 7.6 ms (6.6–9.6) | 490x | | Large: 3,000 issues, 10 runs each, 400 candidates, 5 samples | 62,600 (382 MB) | 538 of 538 | 57,055 ms (48,343–66,079) | 31 ms (16–79) | 1,800x | Sizes are set with `BENCH_ISSUES`, `BENCH_RUNS_PER_ISSUE`, `BENCH_CANDIDATES` and `BENCH_ITERATIONS`. The timed query is the real first page (limit 100). Plan (default size): the baseline runs `SubPlan` 270 times. Each run is a `Bitmap Heap Scan` on `heartbeat_runs_company_agent_started_idx` that removes about 12,000 rows by filter, for about 8.2 million buffer reads in total. The treatment runs an `Append` of two `Limit` index scans (`heartbeat_runs_company_native_issue_contract_id_uq` and `heartbeat_runs_company_ctx_issue_created_idx`), for about 3,800 buffer reads in total. Tests: - `cd server && npx vitest run src/__tests__/chat-channels.integration.test.ts -t "terminal GitHub"`: 13 passed, including the 2 new tests. - Mutation check: when the legacy branch does not exclude runs with a native binding, the first new test fails. It passes with the fix. - `cd server && npx tsc --noEmit`: passed. ## Risks - Low risk. The change is one SQL subquery. The match is the same set of runs: `native_issue_id::text = ` is equal to `native_issue_id = `, and a null `native_issue_id` makes the `coalesce` use the legacy context. - The candidate set itself is not bounded by this change. Acknowledged responses that never become final stay in the candidate set. Each candidate is now cheap, but the count still grows with that history. - `readGitHubResponseRun` in `response-run-state.ts` uses the same `coalesce` match. The sweep calls it once for each candidate row, and other GitHub paths also call it. Each call is a separate, smaller statement. This pull request does not change it. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic. Used through Claude Code with tool use (shell, file edits, and local PostgreSQL benchmarks). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] 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 --- ...enchmark-github-terminal-response-sweep.ts | 192 ++++++++++++++++++ .../chat-channels.integration.test.ts | 48 +++++ .../github/terminal-response-work.ts | 21 +- 3 files changed, 257 insertions(+), 4 deletions(-) create mode 100644 scripts/benchmark-github-terminal-response-sweep.ts diff --git a/scripts/benchmark-github-terminal-response-sweep.ts b/scripts/benchmark-github-terminal-response-sweep.ts new file mode 100644 index 00000000000..a7b31f3a41d --- /dev/null +++ b/scripts/benchmark-github-terminal-response-sweep.ts @@ -0,0 +1,192 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { promises as fs } from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { createDb, startEmbeddedPostgresTestDatabase, type Db } from "../packages/db/src/index.js"; +import { registerGitHubTerminalResponseWork } from "../server/src/services/chat-channels/github/terminal-response-work.js"; +import { captureReviewWaitQueries, type CapturedReviewWaitQuery } from "../server/src/__tests__/helpers/github-review-wait.js"; + +// Measures the GitHub terminal-response discovery page against a synthetic +// history: many agent runs with incompressible legacy contexts and a set of +// acknowledged (processed, non-final) response comments. +// pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-github-terminal-response-sweep.ts --baseline-ref= +const baselineRef = process.argv.find(arg => arg.startsWith("--baseline-ref="))?.slice(15); +assert.ok(baselineRef, "Pass an explicit pre-fix --baseline-ref="); +const number = (name: string, fallback: number) => Number(process.env[name] ?? fallback); +const fixture = { + issues: number("BENCH_ISSUES", 1_500), + runsPerIssue: number("BENCH_RUNS_PER_ISSUE", 8), + contextPadBytes: number("BENCH_CONTEXT_PAD_BYTES", 4_096), + candidates: number("BENCH_CANDIDATES", 150), + blockedEvery: 10, + decoyCompanies: 1, +}; +const baselineRevision = execFileSync("git", ["rev-parse", "--verify", `${baselineRef}^{commit}`], { encoding: "utf8" }).trim(); +const treatmentRevision = execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim(); +const modulePath = "server/src/services/chat-channels/github/terminal-response-work.ts"; +const root = fileURLToPath(new URL("../", import.meta.url)); +const keepAlive = setInterval(() => {}, 1_000); +let temporary: Awaited> | undefined; +let db: Db | undefined; +let baselineDir: string | undefined; + +async function seed(db: Db, companyIndex: number) { + const sql = db.$client; + const [{ company }] = await sql.unsafe(`insert into companies (name, issue_prefix) values ($1, $2) returning id as company`, + [`Bench ${companyIndex}`, `BN${companyIndex}`]); + const [{ agent }] = await sql.unsafe(`insert into agents (company_id, name) values ($1, 'GitHub agent') returning id as agent`, [company]); + const [{ application }] = await sql.unsafe(`insert into tool_applications (company_id, application_key, name, type) + values ($1, 'github', 'GitHub', 'chat') returning id as application`, [company]); + const [{ connection }] = await sql.unsafe(`insert into tool_connections (company_id, application_id, name, uid, transport, connection_purpose) + values ($1, $2, 'GitHub', $3, 'chat_sdk', 'channel') returning id as connection`, [company, application, `github-${companyIndex}`]); + const [{ endpoint }] = await sql.unsafe(`insert into chat_endpoints (company_id, connection_id, provider, public_id, assigned_agent_id, status) + values ($1, $2, 'github', $3, $4, 'active') returning id as endpoint`, [company, connection, `bench-${companyIndex}`, agent]); + const [{ resource }] = await sql.unsafe(`insert into chat_endpoint_resources (company_id, endpoint_id, type, provider_resource_id, label, metadata) + values ($1, $2, 'repository', 'R_1', 'paperclipai/paperclip', '{"providerRepositoryId":"R_1"}') returning id as resource`, [company, endpoint]); + // Issue numbers are 1..N; every tenth issue is blocked. + await sql.unsafe(`insert into issues (company_id, title, status) + select $1, 'Issue ' || n, case when n % ${fixture.blockedEvery} = 0 then 'blocked' else 'in_progress' end + from generate_series(1, ${fixture.issues}) n`, [company]); + await sql.unsafe(`create unlogged table if not exists bench_issue (n int, id uuid, company uuid)`); + await sql.unsafe(`delete from bench_issue`); + await sql.unsafe(`insert into bench_issue select (regexp_replace(title, '\\D', '', 'g'))::int, id, company_id from issues where company_id = $1`, [company]); + await sql.unsafe(`insert into chat_conversations (company_id, endpoint_id, issue_id, external_conversation_id, external_label, + external_thread_id, resource_id) + select $1, $2, i.id, 'github:paperclipai/paperclip:' || i.n, 'PR #' || i.n, 'github:paperclipai/paperclip:' || i.n, $3 + from bench_issue i`, [company, endpoint, resource]); + await sql.unsafe(`insert into chat_deliveries (company_id, endpoint_id, provider_event_id, deduplication_key, event_kind, + normalized_event, conversation_id, state) + select $1, $2, 'event-' || i.n, 'dedupe-' || i.n, 'message', '{}', c.id, 'processed' + from bench_issue i join chat_conversations c on c.issue_id = i.id`, [company, endpoint]); + // One response comment per issue. The first N issues are acknowledged and + // not final; the rest finished long ago with a final response. + await sql.unsafe(`insert into chat_actions (company_id, endpoint_id, delivery_id, conversation_id, kind, provider_action_id, status, result) + select $1, $2, d.id, c.id, 'github_response_comment', 'response-' || i.n, 'processed', + case when i.n <= ${fixture.candidates} then jsonb_build_object('id', 'IC_' || i.n, 'final', false) + else jsonb_build_object('id', 'IC_' || i.n, 'final', true) end + from bench_issue i join chat_conversations c on c.issue_id = i.id join chat_deliveries d on d.conversation_id = c.id`, [company, endpoint]); + await sql.unsafe(`insert into chat_message_links (company_id, endpoint_id, conversation_id, delivery_id, provider_message_id, direction) + select $1, $2, c.id, d.id, 'IC_in_' || i.n, 'inbound' + from bench_issue i join chat_conversations c on c.issue_id = i.id join chat_deliveries d on d.conversation_id = c.id`, [company, endpoint]); + // Runs: odd issues are legacy (context_snapshot only), even issues are native. + // Legacy contexts carry incompressible padding like real prompt context. + await sql.unsafe(`insert into heartbeat_runs (company_id, agent_id, status, native_issue_id, context_snapshot, created_at) + select $1, $2, case when r = ${fixture.runsPerIssue} and i.n % 3 = 0 then 'running' else 'succeeded' end, + case when i.n % 2 = 0 then i.id end, + jsonb_build_object('issueId', i.id::text, 'pad', + (select string_agg(md5(random()::text || g::text || i.n::text || r::text), '') from generate_series(1, ${Math.ceil(fixture.contextPadBytes / 32)}) g)), + timestamptz '2026-01-01' + (i.n * ${fixture.runsPerIssue} + r) * interval '1 second' + from bench_issue i cross join generate_series(1, ${fixture.runsPerIssue}) r`, [company, agent]); + // Precedence decoys: a newer active run natively bound to another issue whose + // legacy context still names this issue. It must not count for this issue. + await sql.unsafe(`insert into heartbeat_runs (company_id, agent_id, status, native_issue_id, context_snapshot, created_at) + select $1, $2, 'running', gen_random_uuid(), jsonb_build_object('issueId', i.id::text), + timestamptz '2026-01-01' + (i.n * ${fixture.runsPerIssue} + ${fixture.runsPerIssue} + 1) * interval '1 second' + from bench_issue i where i.n % 7 = 0`, [company, agent]); + // Ordering ties: an active run with the latest creation time of the issue's + // other runs (native and legacy). The id decides which run is latest. + await sql.unsafe(`insert into heartbeat_runs (company_id, agent_id, status, native_issue_id, context_snapshot, created_at) + select $1, $2, 'running', case when i.n % 2 = 1 then i.id end, jsonb_build_object('issueId', i.id::text), + timestamptz '2026-01-01' + (i.n * ${fixture.runsPerIssue} + ${fixture.runsPerIssue}) * interval '1 second' + from bench_issue i where i.n % 11 = 0`, [company, agent]); + // Another agent's newer active runs on the same issues. + const [{ other }] = await sql.unsafe(`insert into agents (company_id, name) values ($1, 'Other agent') returning id as other`, [company]); + await sql.unsafe(`insert into heartbeat_runs (company_id, agent_id, status, native_issue_id, context_snapshot, created_at) + select $1, $2, 'running', case when i.n % 2 = 0 then i.id end, jsonb_build_object('issueId', i.id::text), timestamptz '2027-01-01' + from bench_issue i where i.n % 5 = 0`, [company, other]); + return { company, agent, endpoint }; +} + +try { + const oldSource = execFileSync("git", ["show", `${baselineRevision}:${modulePath}`], { encoding: "utf8" }); + const moduleUrl = new URL(`../${modulePath}`, import.meta.url); + baselineDir = await fs.mkdtemp(path.join(root, "server/scripts/.terminal-response-baseline-")); + const baselineFile = path.join(baselineDir, "terminal-response-work.ts"); + await fs.writeFile(baselineFile, oldSource.replace(/from "(\.{1,2}\/[^\"]+)"/g, + (_match, specifier: string) => `from ${JSON.stringify(fileURLToPath(new URL(specifier, moduleUrl)))}`)); + const baseline = await import(pathToFileURL(baselineFile).href) as typeof import("../server/src/services/chat-channels/github/terminal-response-work.js"); + temporary = await startEmbeddedPostgresTestDatabase("github-terminal-response-benchmark-"); + db = createDb(temporary.connectionString); + const seedStart = performance.now(); + const main = await seed(db, 0); + for (let n = 1; n <= fixture.decoyCompanies; n++) await seed(db, n); + await db.$client.unsafe("DROP TABLE bench_issue"); + await db.$client.unsafe("ANALYZE"); + const seedMs = performance.now() - seedStart; + + const stop = new Error("captured"); + async function capture(register: typeof registerGitHubTerminalResponseWork) { + const queries: CapturedReviewWaitQuery[] = []; + const proxy = captureReviewWaitQueries(db!, queries); + let task: { run(signal: AbortSignal): Promise } | undefined; + const coordinator = { register: (_queue: unknown, value: typeof task) => { task = value; return { wake() {}, stop: async () => {} }; } }; + register(new Proxy(proxy, { get(target, key) { + const value = Reflect.get(target, key); + if (key !== "select") return value; + return (...args: unknown[]) => { + if (queries.some(query => query.sql.includes("github-publication:"))) throw stop; + return (value as (...args: unknown[]) => unknown)(...args); + }; + } }), coordinator as never, async () => {}, () => true); + await task!.run(new AbortController().signal).catch(() => {}); + const query = queries.find(query => query.sql.includes("github-publication:")); + assert.ok(query, "Capture the real discovery page query"); + return query; + } + const queries = { + baseline: await capture(baseline.registerGitHubTerminalResponseWork), + treatment: await capture(registerGitHubTerminalResponseWork), + }; + + // Compare every candidate, not only the first page: lift the page limit. + async function rows(query: CapturedReviewWaitQuery) { + assert.match(query.sql, /limit \$\d+$/); + const params = [...query.params.slice(0, -1), 1_000_000]; + return (await db!.$client.unsafe(query.sql, params as never[]).values()).map(row => row.map(value => + value === null ? null : typeof value === "object" && !(value instanceof Date) ? JSON.stringify(value) : String(value))); + } + const before = await rows(queries.baseline), after = await rows(queries.treatment); + assert.deepEqual(after, before, "Every returned column and row order must match"); + assert.ok(before.length > 0, "The fixture must return terminal candidates"); + + async function timed(query: CapturedReviewWaitQuery) { + const start = performance.now(); + await db!.$client.unsafe(query.sql, query.params as never[]).values(); + return performance.now() - start; + } + const iterations = number("BENCH_ITERATIONS", 7); + const samples = { baseline: [] as number[], treatment: [] as number[] }; + for (let n = 0; n < iterations + 2; n++) { + const versions = n % 2 ? ["treatment", "baseline"] as const : ["baseline", "treatment"] as const; + for (const version of versions) { + const elapsed = await timed(queries[version]); + if (n >= 2) samples[version].push(elapsed); + } + } + const stats = (values: number[]) => { + const sorted = [...values].sort((a, b) => a - b); + return { samplesMs: values.map(value => Math.round(value * 10) / 10), medianMs: sorted[Math.floor(sorted.length / 2)], + minMs: sorted[0], maxMs: sorted.at(-1) }; + }; + async function plan(query: CapturedReviewWaitQuery) { + return (await db!.$client.unsafe(`EXPLAIN (ANALYZE, BUFFERS) ${query.sql}`, query.params as never[]).values()).map(row => row[0]); + } + const counts = (await db.$client.unsafe(`select (select count(*) from heartbeat_runs)::int runs, + (select count(*) from chat_actions)::int actions, pg_size_pretty(pg_total_relation_size('heartbeat_runs')) runs_size`))[0]; + console.log(JSON.stringify({ baselineRevision, treatmentRevision, + treatmentDiff: execFileSync("git", ["diff", "HEAD", "--", modulePath], { cwd: root, encoding: "utf8" }), + postgresVersion: (await db.$client.unsafe("SELECT version()"))[0]!.version, + fixture: { ...fixture, ...counts, seedMs: Math.round(seedMs), mainCompany: main.company, synthetic: true }, + correctness: { completeOutputEqual: true, rows: before.length }, + timings: { warmups: 2, samples: iterations, order: "alternating", baseline: stats(samples.baseline), treatment: stats(samples.treatment) }, + plans: { baseline: await plan(queries.baseline), treatment: await plan(queries.treatment) }, + generatedQueries: { baseline: queries.baseline, treatment: queries.treatment }, + }, null, 2)); +} finally { + try { + await db?.$client.end({ timeout: 0 }); + await temporary?.cleanup(); + if (baselineDir) await fs.rm(baselineDir, { recursive: true, force: true }); + } finally { clearInterval(keepAlive); } +} diff --git a/server/src/__tests__/chat-channels.integration.test.ts b/server/src/__tests__/chat-channels.integration.test.ts index 9fa666c38a6..909f9bd60a8 100644 --- a/server/src/__tests__/chat-channels.integration.test.ts +++ b/server/src/__tests__/chat-channels.integration.test.ts @@ -4194,6 +4194,54 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { } finally { await coordinator.stop(); vi.useRealTimers(); } }); + it("finds terminal GitHub responses by native issue binding before legacy run context", async () => { + const f = await toolReplyFixture(); + const issueId = f.conversation.issueId!; + await db.update(heartbeatRuns).set({ status: "failed", updatedAt: new Date() }).where(eq(heartbeatRuns.id, f.run.id)); + // Newer runs of the same agent that do not bind this issue: one is natively + // bound to another issue although its legacy context names this issue, and + // one names another issue in its context. Neither may hide the stopped run. + await db.insert(heartbeatRuns).values([ + { companyId: f.companyId, agentId: f.assignedAgentId, status: "running", runtimeMode: "native", + nativeIssueId: randomUUID(), contextSnapshot: { issueId }, createdAt: new Date(Date.now() + 60_000) }, + { companyId: f.companyId, agentId: f.assignedAgentId, status: "running", + contextSnapshot: { issueId: randomUUID() }, createdAt: new Date(Date.now() + 120_000) }, + ]); + const errors: unknown[] = []; + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: error => errors.push(error) }); + try { + await githubResponseCommentService(db, f.providerFetch).registerTerminalResponseWork(coordinator, () => true).ready; + await expect.poll(() => [...f.responseComments.values()][0]?.body, { timeout: 5000 }).toContain("stopped before completing"); + await expect.poll(() => ({ next: coordinator.nextWakeAt(), active: idleWorkSnapshot().active }), + { timeout: 5000 }).toEqual({ next: null, active: 0 }); + expect(errors).toEqual([]); + } finally { await coordinator.stop(); } + }); + + it("keeps terminal GitHub responses waiting while a natively bound newer run is active", async () => { + const f = await toolReplyFixture(); + const issueId = f.conversation.issueId!; + await db.update(heartbeatRuns).set({ status: "failed", updatedAt: new Date() }).where(eq(heartbeatRuns.id, f.run.id)); + // The newer run binds this issue natively; its legacy context is ignored. + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.assignedAgentId, + status: "running", runtimeMode: "native", nativeIssueId: issueId, contextSnapshot: { issueId: randomUUID() }, + createdAt: new Date(Date.now() + 60_000) }); + const baseline = f.responseWrites.length; + const errors: unknown[] = []; + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: error => errors.push(error) }); + try { + await githubResponseCommentService(db, f.providerFetch).registerTerminalResponseWork(coordinator, () => true).ready; + await expect.poll(() => ({ next: coordinator.nextWakeAt(), active: idleWorkSnapshot().active }), + { timeout: 5000 }).toEqual({ next: null, active: 0 }); + expect(f.responseWrites).toHaveLength(baseline); + const [action] = await db.select().from(chatActions).where(and(eq(chatActions.endpointId, f.endpoint.id), + eq(chatActions.kind, "github_response_comment"))); + expect(action).toMatchObject({ status: "processed" }); + expect(action.result?.final).not.toBe(true); + expect(errors).toEqual([]); + } finally { await coordinator.stop(); } + }); + it("settles a deleted Board-origin request without starving unrelated terminal GitHub replies", async () => { const invalid = await toolReplyFixture(); const valid = await toolReplyFixture(); diff --git a/server/src/services/chat-channels/github/terminal-response-work.ts b/server/src/services/chat-channels/github/terminal-response-work.ts index c43910d550e..cb1f240bb9e 100644 --- a/server/src/services/chat-channels/github/terminal-response-work.ts +++ b/server/src/services/chat-channels/github/terminal-response-work.ts @@ -21,6 +21,22 @@ export function registerGitHubTerminalResponseWork( const repositoryId = sql`${chatEndpointResources.metadata}->>'providerRepositoryId'`; const number = sql`substring(${chatConversations.externalThreadId} from '^github:[^:]+:(?:issue:)?([1-9][0-9]*)(?::rc:[1-9][0-9]*)?$')`; + // Status of the assigned agent's latest run bound to the issue, where a run's + // issue is coalesce(native_issue_id, context_snapshot->>'issueId'). The two + // precedence branches are disjoint and each uses an issue index, so a + // candidate does not walk (and detoast) the agent's whole run history. + const latestIssueRunStatus = sql`select latest.status from ( + (select r.status, r.created_at, r.id from ${heartbeatRuns} r + where r.company_id = ${chatActions.companyId} and r.native_issue_id = ${chatConversations.issueId} + and r.agent_id = ${chatEndpoints.assignedAgentId} + order by r.created_at desc, r.id desc limit 1) + union all + (select r.status, r.created_at, r.id from ${heartbeatRuns} r + where r.company_id = ${chatActions.companyId} and r.native_issue_id is null + and r.context_snapshot->>'issueId' = ${chatConversations.issueId}::text + and r.agent_id = ${chatEndpoints.assignedAgentId} + order by r.created_at desc, r.id desc limit 1) + ) latest order by latest.created_at desc, latest.id desc limit 1`; async function page(scope?: Scope, cursor?: string, actionId?: string) { return db.select({ id: chatActions.id, companyId: chatActions.companyId, endpointId: chatActions.endpointId, @@ -42,10 +58,7 @@ export function registerGitHubTerminalResponseWork( .where(and(eq(chatActions.kind, "github_response_comment"), eq(chatActions.status, "processed"), isNotNull(chatActions.deliveryId), isNotNull(chatEndpoints.assignedAgentId), sql`coalesce(${chatActions.result}->>'final', 'false') <> 'true'`, - sql`(${issues.status} = 'blocked' or (select r.status from ${heartbeatRuns} r - where r.company_id = ${chatActions.companyId} and r.agent_id = ${chatEndpoints.assignedAgentId} - and coalesce(r.native_issue_id::text, r.context_snapshot->>'issueId') = ${chatConversations.issueId}::text - order by r.created_at desc, r.id desc limit 1) in ('succeeded', 'failed', 'interrupted', 'timed_out', 'cancelled'))`, + sql`(${issues.status} = 'blocked' or (${latestIssueRunStatus}) in ('succeeded', 'failed', 'interrupted', 'timed_out', 'cancelled'))`, scope ? eq(chatActions.companyId, scope.companyId) : undefined, scope?.issueId ? eq(issues.id, scope.issueId) : undefined, scope?.conversationId ? eq(chatActions.conversationId, scope.conversationId) : undefined, From c444da7d055e679fade2c8ce8cfff3932c6a6a5b Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 18:27:58 -0600 Subject: [PATCH 03/38] perf(run-events): stop blocking checkpoint FK checks during event appends (#20670) 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. > - A native run sends a stream of runner events. The server appends each event to the run log. The runner controller then saves a checkpoint for recovery. > - Each checkpoint save inserts the new `event:N` row and updates the `cursor` row in `native_runner_checkpoints`. The new row has a foreign key to the run row in `heartbeat_runs`. > - The event append locks the same run row `FOR UPDATE`. That lock blocks the `FOR KEY SHARE` lock that the foreign key check takes. So each checkpoint save waits for the event append that is in progress. > - On a hosted database, the two-row checkpoint upsert had the largest total SQL time. The one-row (cursor-only) upsert, which has no foreign key check, was much cheaper. > - This pull request changes the append lock to `FOR NO KEY UPDATE`. Appenders still serialize. Child foreign key checks no longer wait. > - The benefit is shorter checkpoint saves, shorter waits before each runner ACK, and less lock wait on the database. ## Linked Issues or Issue Description **What existing behavior does this improve?** The controller checkpoint save for native runs (`nativeRunnerCheckpointWriter`), and the native run-event append (`appendHeartbeatRunEvent`). **Subsystem affected** Server run-event log and native runtime checkpoint persistence. **Current behavior** On one hosted database, Neon query performance showed this statement as the largest total: `insert into native_runner_checkpoints ... values (...), (...) on conflict (run_id, part) do update`. It ran 6,582 times at 62.6 ms (412 s) in the first 38 minutes after a compute restart, and 9,435 times at 31.8 ms (300 s) about two hours later. An earlier day showed 100,650 calls at 102 ms. The one-row form of the same upsert ran 965 times at 13.4 ms. The runner already writes only changed records (`captureCheckpoint` compares plaintext), so unchanged material is not rewritten. The two-row form is a new event row plus the cursor. Only the new row fires the foreign key check. `appendHeartbeatRunEvent` locks the run row `FOR UPDATE` for each native event, in a transaction with several statements. `FOR UPDATE` conflicts with `FOR KEY SHARE`, so the check waits for that transaction. **Proposed behavior** `appendHeartbeatRunEvent` locks the run row `FOR NO KEY UPDATE`. This mode still conflicts with other appenders, `FOR SHARE`, `FOR UPDATE`, deletes and updates. It does not conflict with `FOR KEY SHARE`. The append never changes key columns: `runUpdate` is limited to process fields, and the native and retry-exhaustion paths reject it. The fast path already uses a plain `UPDATE`, which takes the same lock mode. The execution-admission adapter already locks this row `FOR NO KEY UPDATE`. **Reason and benefit** The wait goes in both directions. A checkpoint save waits for an append. An append also waits for an open checkpoint transaction that holds `FOR KEY SHARE`. Both waits stop. The controller sends each ACK only after its checkpoint commits, so shorter saves also shorten the event loop. ## What Changed - `server/src/services/heartbeat-run-events.ts`: lock the run row `FOR NO KEY UPDATE` instead of `FOR UPDATE` in the transactional append path. Add a comment that names the contract. - `heartbeat-run-event-atomic-append.test.ts`: add a regression test. An append transaction stays open. A checkpoint row insert for the same run must finish under a 2 s `lock_timeout`. A second appender must still wait. After release, the sequence is 1, 2 with no gap and no duplicate. The existing test with 40 concurrent appenders on two connections still proves contiguous sequence numbers. Update the existing lock-statement assertion to the new clause. - Add `scripts/benchmark-run-event-checkpoint-lock.ts`. It replays a native event stream with the real append and the real checkpoint writer on separate connections. It times each checkpoint save for a baseline append module and the current one. ## Verification - Red: with the old `FOR UPDATE` clause, the new test fails with `canceling statement due to lock timeout`. With the change it passes. - `npx vitest run src/__tests__/heartbeat-run-event-atomic-append.test.ts src/__tests__/heartbeat-run-event-sequencing.test.ts src/services/native-runtime/native-runner-checkpoint-authority.integration.test.ts src/__tests__/native-recovery-notice-work.test.ts` (server): 4 files, 42 tests passed. - `pnpm --filter @paperclipai/server typecheck`: passed. - `pnpm verify` exits 2, because a new script under `scripts/` is a global CI input. Required CI supplies the broad coverage. Local benchmark. Embedded PostgreSQL 18.1 on a laptop. 400 events per pass, 2 KiB event payload, 6 KiB header, real encryption. Order: warm-up, baseline, current, baseline, current. `HOLD_MS` keeps each append transaction open longer. It stands in for hosted round trips. | Hold | Pass | Median save | p90 | Max | Saves > 2 ms | Total save time | | --- | --- | --- | --- | --- | --- | --- | | 5 ms | Baseline (1) | 8.16 ms | 9.50 ms | 129.48 ms | 396 / 400 | 3,551 ms | | 5 ms | Current (2) | 1.44 ms | 2.08 ms | 12.66 ms | 44 / 400 | 677 ms | | 5 ms | Baseline (3) | 8.12 ms | 9.64 ms | 22.08 ms | 398 / 400 | 3,453 ms | | 5 ms | Current (4) | 1.50 ms | 2.37 ms | 10.54 ms | 80 / 400 | 700 ms | | 0 ms | Baseline (1) | 1.71 ms | 2.50 ms | 11.05 ms | 105 / 400 | 780 ms | | 0 ms | Current (2) | 0.97 ms | 1.42 ms | 10.28 ms | 22 / 400 | 458 ms | | 0 ms | Baseline (3) | 1.49 ms | 2.02 ms | 6.45 ms | 41 / 400 | 667 ms | | 0 ms | Current (4) | 0.91 ms | 1.24 ms | 9.80 ms | 19 / 400 | 420 ms | - Event order: the controller frame chain awaits each event's append and its local commit, but not its checkpoint save. The ACK goes through `#sendJson`, which queues the save and does not block the next frame. Only semantic inputs and command results await the save. So the save for event N overlaps the append of event N+1. Streaming events (`item.delta`) also go through the same locked append, with no checkpoint save, so a save can also overlap them. The benchmark uses this order. - Control without overlap (`SERIAL=1`, each save finishes before the next append, 5 ms hold): baseline median 1.15 / 1.07 ms, current 1.03 / 1.00 ms. There is no material difference. The gain comes only from the removed lock wait. - Results are the same in every pass. The script asserts that all event rows, the header and the cursor are stored, and that the run-log sequence is contiguous. - Command: see the script header. It needs a baseline copy of `heartbeat-run-events.ts` from the base revision. ## Risks - Low risk. The SQL change is one lock clause. Appenders still serialize with each other, with `FOR UPDATE` and `FOR SHARE` lockers, and with updates and deletes of the run row. Run deletion and key changes take `FOR UPDATE`, so they still wait for an append, and an append still waits for them. - The only new concurrency is with `FOR KEY SHARE` lockers. In this code base those are foreign key checks of child inserts. The one explicit `FOR KEY SHARE` read is on `issues`, not on `heartbeat_runs`. A foreign key check only needs the run row and its key to exist. The append does not delete the row or change its key. - The hosted cause is inferred. Neon shows calls and mean time only. We did not read lock waits on the hosted database. The local proof shows the mechanism and the size of the effect. A new query-performance window after deployment must confirm the result. - Persisted run state: no saved run, session, event or checkpoint shape changes. State saved by the previous release carries forward unchanged. The lock mode applies only inside one transaction, so a deploy during a run needs no special case. ## Model Used - Claude Opus 5.5 (Anthropic), model ID `claude-opus-5-5`, used through Claude Code with tool use (shell, file edits, local PostgreSQL). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../benchmark-run-event-checkpoint-lock.ts | 123 ++++++++++++++++++ .../heartbeat-run-event-atomic-append.test.ts | 52 +++++++- server/src/services/heartbeat-run-events.ts | 6 +- 3 files changed, 178 insertions(+), 3 deletions(-) create mode 100644 scripts/benchmark-run-event-checkpoint-lock.ts diff --git a/scripts/benchmark-run-event-checkpoint-lock.ts b/scripts/benchmark-run-event-checkpoint-lock.ts new file mode 100644 index 00000000000..42e7d5cadd2 --- /dev/null +++ b/scripts/benchmark-run-event-checkpoint-lock.ts @@ -0,0 +1,123 @@ +/** + * Local proof for the run-event append lock and controller checkpoint saves. + * + * A native run appends every PRP event through `appendHeartbeatRunEvent`, + * which locks the run row. The controller then saves its checkpoint: a new + * `event:N` row plus the `cursor` row. The new row's foreign key check takes + * FOR KEY SHARE on the same run row. This script replays that pattern with the + * real append and the real checkpoint writer, on separate connections, and + * times each checkpoint save. It compares a baseline append module (FOR UPDATE) + * with the current one (FOR NO KEY UPDATE), in alternating order. + * + * Overlap is the normal controller order. The frame chain awaits each event's + * append (onCommittedEvent) and local commit, but not its checkpoint save: the + * ACK goes through #sendJson, which queues the save and does not block the + * next frame. Only semantic inputs and command results await the save. So the + * save for event N runs while event N+1 is appended. SERIAL=1 awaits every + * save before the next append, as a control without overlap. + * + * HOLD_MS keeps each append transaction open that much longer. It stands in + * for hosted round trips, which make the real append transaction last longer + * than on loopback. + * + * git show :server/src/services/heartbeat-run-events.ts \ + * > server/src/services/heartbeat-run-events.baseline.ts + * pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-run-event-checkpoint-lock.ts + * + * Optional: EVENTS (default 400 per pass), PASSES (4), HOLD_MS (5), EVENT_KIB (2), SERIAL (0). + * Delete the baseline copy afterwards. + */ +import assert from "node:assert/strict"; +import { randomBytes, randomUUID } from "node:crypto"; +import { existsSync } from "node:fs"; +import { createRequire } from "node:module"; +import { fileURLToPath } from "node:url"; +import { agents, companies, createDb, heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations, + nativeRunnerCheckpoints, startEmbeddedPostgresTestDatabase } from "../packages/db/src/index.js"; +import * as candidate from "../server/src/services/heartbeat-run-events.js"; +import { nativeRunnerCheckpointWriter } from "../server/src/services/native-runtime/native-runner-checkpoint.js"; + +const { eq, sql: drizzleSql } = createRequire(new URL("../server/package.json", import.meta.url))("drizzle-orm") as typeof import("drizzle-orm"); + +const baselinePath = fileURLToPath(new URL("../server/src/services/heartbeat-run-events.baseline.ts", import.meta.url)); +assert(existsSync(baselinePath), "Write the baseline module first (see the header)"); +const baseline = await import(baselinePath) as typeof candidate; +const size = (name: string, fallback: number) => Number(process.env[name] ?? fallback); +const EVENTS = size("EVENTS", 400), PASSES = size("PASSES", 4), HOLD_MS = size("HOLD_MS", 5), EVENT_KIB = size("EVENT_KIB", 2); +const SERIAL = process.env.SERIAL === "1"; +process.env.PAPERCLIP_SECRETS_MASTER_KEY ??= randomBytes(32).toString("base64"); + +const keepAlive = setInterval(() => {}, 1_000); +const temporary = await startEmbeddedPostgresTestDatabase("run-event-checkpoint-lock-"); +const appendDb = createDb(temporary.connectionString); +const checkpointDb = createDb(temporary.connectionString); +try { + const [company] = await appendDb.insert(companies).values({ name: "Lock", issuePrefix: "LCK" }).returning(); + const [agent] = await appendDb.insert(agents).values({ companyId: company!.id, name: "Native" }).returning(); + const [issue] = await appendDb.insert(issues).values({ companyId: company!.id, title: "Streaming task" }).returning(); + const quantile = (values: number[], q: number) => [...values].sort((a, b) => a - b)[Math.min(values.length - 1, Math.floor(values.length * q))]!; + const round = (value: number) => Number(value.toFixed(2)); + + async function pass(label: "baseline" | "candidate") { + const append = (label === "baseline" ? baseline : candidate).appendHeartbeatRunEvent; + const runId = randomUUID(), bootId = randomUUID(), leaseOwner = randomUUID(); + await appendDb.insert(heartbeatRuns).values({ id: runId, companyId: company!.id, agentId: agent!.id, status: "running", + runtimeMode: "native", nativeIssueId: issue!.id, issueId: issue!.id, + runnerProfileJson: { padding: randomBytes(3 * 1024).toString("base64") } }); + await appendDb.insert(nativeRunFinalizations).values({ runId, companyId: company!.id, issueId: issue!.id, phase: "observed", + controllerBootId: bootId, controllerGeneration: 1, leaseOwner, leaseExpiresAt: new Date(Date.now() + 3_600_000) }); + const write = nativeRunnerCheckpointWriter(checkpointDb, { companyId: company!.id, issueId: issue!.id, runId, + authorityRunId: runId, bootId, generation: 1, leaseOwner }); + const checkpoint = (records: Map, changed: Map, reset: boolean) => ({ + runId, records, changedRecords: changed, removedRecords: [], reset, workCommandIds: [], predecessor: null, + runnerVersion: "bench", runnerDigest: `sha256:${"a".repeat(64)}`, + recoveryEvidence: { runnerInstanceId: "bench", normalizedSessionId: "bench", authenticatedConnectionCount: 1, highestRecordedSourceSeq: 0 }, + restoreSessionDirectory() {}, + }) as unknown as Parameters[0]; + const records = new Map([["header", JSON.stringify({ padding: randomBytes(6 * 1024).toString("base64") })], + ["cursor", JSON.stringify({ ackedSourceSeq: 0 })]]); + await write(checkpoint(records, new Map(records), true)); + const saves: number[] = []; + let tail = Promise.resolve(); + const started = performance.now(); + for (let seq = 1; seq <= EVENTS; seq++) { + const event = { sourceSeq: seq, eventType: "item.completed", text: randomBytes(EVENT_KIB * 768).toString("base64") }; + // The append commits before the controller ACKs, like onCommittedEvent. + await appendDb.transaction(async tx => { + await append(tx as unknown as typeof appendDb, { companyId: company!.id, agentId: agent!.id, runId, + eventType: "item.completed", stream: "system", level: "info", payload: { prpEvent: event }, + nativeSource: { sourceInstanceId: "bench-runner", sourceEventId: `event-${seq}`, sourceSeq: seq, + protocolSchemaVersion: 1, canonicalPayload: event } }); + if (HOLD_MS) await tx.execute(drizzleSql`select pg_sleep(${HOLD_MS / 1000})`); + }); + const changed = new Map([[`event:${seq}`, JSON.stringify(event)], ["cursor", JSON.stringify({ ackedSourceSeq: seq })]]); + for (const [key, value] of changed) records.set(key, value); + // Checkpoint saves are serialized per controller and overlap the next append. + tail = tail.then(async () => { + const start = performance.now(); + await write(checkpoint(new Map(records), changed, false)); + saves.push(performance.now() - start); + }); + if (SERIAL) await tail; + } + await tail; + const elapsed = performance.now() - started; + const [stored] = await checkpointDb.select({ count: drizzleSql`count(*)::int` }).from(nativeRunnerCheckpoints) + .where(eq(nativeRunnerCheckpoints.runId, runId)); + const events = await appendDb.select({ seq: heartbeatRunEvents.seq }).from(heartbeatRunEvents) + .where(eq(heartbeatRunEvents.runId, runId)).orderBy(heartbeatRunEvents.seq); + assert.equal(stored!.count, EVENTS + 2, "Every event row, the header and the cursor are stored"); + assert.deepEqual(events.map(row => row.seq), Array.from({ length: EVENTS }, (_, index) => index + 1)); + return { label, saves: saves.length, saveMedianMs: round(quantile(saves, 0.5)), saveP90Ms: round(quantile(saves, 0.9)), + saveMaxMs: round(Math.max(...saves)), savesOver2Ms: saves.filter(value => value > 2).length, + saveTotalMs: round(saves.reduce((sum, value) => sum + value, 0)), elapsedMs: round(elapsed) }; + } + + await pass("candidate"); // Warm caches and the prepared-statement path once. + const results = []; + for (let index = 0; index < PASSES; index++) results.push(await pass(index % 2 === 0 ? "baseline" : "candidate")); + console.log(JSON.stringify({ events: EVENTS, serial: SERIAL, holdMs: HOLD_MS, eventKiB: EVENT_KIB, results }, null, 2)); +} finally { + clearInterval(keepAlive); + await temporary.cleanup(); +} diff --git a/server/src/__tests__/heartbeat-run-event-atomic-append.test.ts b/server/src/__tests__/heartbeat-run-event-atomic-append.test.ts index 3d4b55b76cb..69d9b9e688c 100644 --- a/server/src/__tests__/heartbeat-run-event-atomic-append.test.ts +++ b/server/src/__tests__/heartbeat-run-event-atomic-append.test.ts @@ -3,7 +3,7 @@ import { randomBytes } from "node:crypto"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { eq, inArray, sql } from "drizzle-orm"; import { drizzle } from "drizzle-orm/postgres-js"; -import { agents, companies, createDb, heartbeatRunEvents, heartbeatRuns } from "@paperclipai/db"; +import { agents, companies, createDb, heartbeatRunEvents, heartbeatRuns, issues, nativeRunnerCheckpoints } from "@paperclipai/db"; import { appendHeartbeatRunEvent } from "../services/heartbeat-run-events.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; @@ -51,6 +51,7 @@ describeEmbeddedPostgres("atomic ordinary run events", () => { const fixtureCompanies = [companyId, otherCompanyId]; await db.delete(heartbeatRunEvents).where(inArray(heartbeatRunEvents.companyId, fixtureCompanies)); await db.delete(heartbeatRuns).where(inArray(heartbeatRuns.companyId, fixtureCompanies)); + await db.delete(issues).where(inArray(issues.companyId, fixtureCompanies)); await db.delete(agents).where(inArray(agents.companyId, fixtureCompanies)); await db.delete(companies).where(inArray(companies.id, fixtureCompanies)); } @@ -145,7 +146,7 @@ describeEmbeddedPostgres("atomic ordinary run events", () => { expect((await readRun(runId)).nextEventSeq).toBe(2); expect(await readEvents(runId)).toEqual([committed.row]); const lockReads = statements.filter(query => query.startsWith("select ") && - query.includes('from "heartbeat_runs"') && query.endsWith("for update")); + query.includes('from "heartbeat_runs"') && query.endsWith("for no key update")); expect(lockReads).toHaveLength(2); for (const query of lockReads) { expect(query).toMatch(/^select "company_id", "agent_id" from "heartbeat_runs" /); @@ -153,6 +154,53 @@ describeEmbeddedPostgres("atomic ordinary run events", () => { } }); + it("serializes appenders without blocking child foreign key checks on the run", async () => { + const runId = await makeRun(); + const [issue] = await db.insert(issues).values({ companyId, title: "Checkpointed task" }).returning(); + await db.update(heartbeatRuns).set({ nativeIssueId: issue!.id, runtimeMode: "native" }) + .where(eq(heartbeatRuns.id, runId)); + const native = (ordinal: number) => ({ + companyId, agentId, runId, eventType: "item.completed", + nativeSource: { sourceInstanceId: "native-writer", sourceEventId: `held-${ordinal}`, + sourceSeq: ordinal, protocolSchemaVersion: 1, canonicalPayload: { ordinal } }, + }); + let releaseHolder!: () => void; + const held = new Promise(resolve => { releaseHolder = resolve; }); + let holderLocked!: () => void; + const locked = new Promise(resolve => { holderLocked = resolve; }); + // An append whose transaction is still open holds the run lock, as an + // event append does while its remaining statements run. + const holder = otherDb.transaction(async tx => { + await appendHeartbeatRunEvent(tx as unknown as typeof db, native(1)); + holderLocked(); + await held; + }); + await locked; + let secondSettled = false; + const second = appendHeartbeatRunEvent(db, native(2)).finally(() => { secondSettled = true; }); + try { + // A controller checkpoint row references the run row by foreign key. + // Its insert must not wait for the open append. + await db.transaction(async tx => { + await tx.execute(sql`set local lock_timeout = '2s'`); + await tx.insert(nativeRunnerCheckpoints).values({ companyId, issueId: issue!.id, runId, + part: "event:1", material: { fixture: true } }); + }); + // Another appender still waits for the open append. + await new Promise(resolve => setTimeout(resolve, 200)); + expect(secondSettled).toBe(false); + } finally { + releaseHolder(); + await holder; + } + expect((await second).row.seq).toBe(2); + expect((await readEvents(runId)).map(row => [row.seq, row.sourceSeq])).toEqual([[1, 1], [2, 2]]); + expect((await readRun(runId)).nextEventSeq).toBe(3); + expect(await db.select({ part: nativeRunnerCheckpoints.part }).from(nativeRunnerCheckpoints) + .where(eq(nativeRunnerCheckpoints.runId, runId))).toEqual([{ part: "event:1" }]); + await db.delete(nativeRunnerCheckpoints).where(eq(nativeRunnerCheckpoints.runId, runId)); + }); + it("rejects mismatched authority without changing either run", async () => { const runId = await makeRun(); const otherRunId = "30000000-0000-4000-8000-000000000099"; diff --git a/server/src/services/heartbeat-run-events.ts b/server/src/services/heartbeat-run-events.ts index 1c3325ebd05..695e740f658 100644 --- a/server/src/services/heartbeat-run-events.ts +++ b/server/src/services/heartbeat-run-events.ts @@ -134,7 +134,11 @@ export async function appendHeartbeatRunEvent( ...(projectsProgress ? { issueId: boundRunIssueIdSql() } : {}) }) .from(heartbeatRuns) .where(eq(heartbeatRuns.id, input.runId)) - .for("update") + // Appenders, Stop, recovery and deletion still serialize on this row. + // The append never changes key columns, so it must not block foreign + // key checks (FOR KEY SHARE) of child rows, such as controller + // checkpoints, that are written for the same run while events stream. + .for("no key update") .limit(1) .then((rows) => rows[0] ?? null); if (!run || run.companyId !== input.companyId || run.agentId !== input.agentId) { From e9db5e0d03fd3a8c157e35bfd935e50a992807b9 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 18:35:39 -0600 Subject: [PATCH 04/38] perf(github): read the inherited review waits of an issue list in one pass (#20673) 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. > - An agent can review a GitHub pull request. After the agent publishes the review, the task can wait in review for the next GitHub reply. A later run of the same task can inherit this wait. > - Issue lists and inbox attention show these waits. For each waiting task, the server reads the inherited GitHub review wait: the source comment, the latest review, and the review publication. > - The server did these reads one time for each waiting task. A list request with N waiting tasks sent N copies of the prepared review statement and N copies of the publication read. > - On a hosted database, the prepared review statement ran about 270,000 times in about 2.5 hours (up to 87 calls per second). The run identity read before it ran the same number of times. The list read that calls it ran only about 1,400 times, so each list read started about 190 review reads on average. No other caller reads the waits of many runs in a loop. > - This pull request reads the reviews and the publications of all waits of one list request with one statement each. Each wait gets the same result as before. > - The benefit is about 200 times fewer review statements and fewer pool connections for each issue list. ## Linked Issues or Issue Description Refs #20400 (shares review-wait reads between the callers of one request). Refs #20551 (authorizes the waits of one issue page with one read; this change does the same for the inherited GitHub review reads of that page). **What happened** `listExternalReviewWaits` called `readInheritedGitHubReviewWait` one time for each candidate wait, inside `Promise.all`. Each call sent a run identity read, a source-message read, the prepared `inherited_github_review_wait` statement, and a publication read. A list with N waits sent each statement N times. **Expected behavior** One list request sends one review statement and one publication read for each company. The result of each wait does not change. **Steps to reproduce** 1. Put many tasks of one company in review with an inherited GitHub review wait. 2. Open the issue list or the inbox. 3. Count the statements of the database. The review statement runs one time for each waiting task. ## What Changed - `server/src/services/chat-channels/github/review-wait.ts`: - Split `readInheritedGitHubReviewWait` into shared steps: the source comment read, the review checks, the publication key, and the published result. The single-run read uses the same prepared statement and the same checks as before. - Add `readInheritedGitHubReviewWaits(db, runs)`. It reads the source comment of each run with the same lineage check as before. Then, for each company, one `DISTINCT ON` statement reads the latest review for each (source comment, task, agent) key, with the same joins, filters and order as the prepared statement. One read finds the processed publications. Each run gets the same result as a separate call: `null`, `revoked`, or `published`. - `server/src/services/native-runtime/external-review-wait.ts`: `listExternalReviewWaits` uses the batch read. The rest of the list and its authorization do not change. - `server/src/__tests__/github-review-wait.test.ts`: a new test reads 18 runs in one batch and compares each result with a separate single-run read. The runs include each revocation case (connection disabled or inactive, review state, review agent, repository, repository id, thread, publication, identity, company), a newer unreviewed head, no identity, no task, an endpoint of another agent, a run in another company and a duplicate run. The test also makes sure that the batch sends one review statement and one publication read for each company. The existing revocation tests also check the batch read. - `server/src/__tests__/helpers/github-review-wait.ts`: the seed helper can add a wait to an existing company and agent. ## Verification - `pnpm vitest run server/src/__tests__/github-review-wait.test.ts server/src/__tests__/github-review-check-state.test.ts server/src/__tests__/issue-list-review-wait-authorization.integration.test.ts server/src/__tests__/blocked-inbox-review-wait-scope.test.ts` - Focused local run of every test that imports the changed modules or the seed helper (7 files, 335 tests passed), including `external-chat-wait.integration.test.ts`, `external-review-wait.test.ts` and `legacy-execution-recovery.test.ts`. The change to the shared seed helper makes `pnpm verify` select the full server suite, so CI supplies that coverage. - Local measurement on real PostgreSQL (embedded PostgreSQL, `ANALYZE` after seeding). One company and agent, each wait has 5 reviews and 10 outbound messages. "Before" is the previous list code: one `readInheritedGitHubReviewWait` call for each run in `Promise.all`. "After" is `readInheritedGitHubReviewWaits`. The runs alternate order in each pair. Both return equal results in every sample. | Waits | Version | Statements | Review statements | Median ms | Min–max ms | Samples | | --- | --- | --- | --- | --- | --- | --- | | 200 | before | 800 | 200 | 106.8 | 98.0–117.5 | 10 | | 200 | after | 402 | 1 | 44.3 | 41.6–50.9 | 10 | | 20 | before | 80 | 20 | 9.8 | 8.6–14.7 | 12 | | 20 | after | 42 | 1 | 6.3 | 5.3–7.0 | 12 | - `EXPLAIN (ANALYZE, BUFFERS)` of the batch review statement for 200 waits: index scans on each join, 6.7 ms execution. The single statement: 0.05 ms execution and about 2.7 ms planning for each call. - The run identity read and the source-message read still run one time for each wait. They are cheap on the hosted database (about 0 ms each), and they keep the lineage check for each run. ## Risks - Low risk. The batch statement uses the same joins, filters and order as the prepared statement, and `DISTINCT ON` keeps the first row for each key. The array filters can also match a mix of two keys. The code uses only rows of exact requested keys. - The single-run read and its prepared statement do not change. The finalizer, the status committer, and the attachment reuse paths still use it. - Errors do not change: a 403 from the lineage check gives `revoked`, and other errors are thrown. - No migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (code reading, editing, shell, tests). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] 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 --- .../src/__tests__/github-review-wait.test.ts | 96 +++++++-- .../__tests__/helpers/github-review-wait.ts | 15 +- .../chat-channels/github/review-wait.ts | 187 ++++++++++++++---- .../native-runtime/external-review-wait.ts | 24 ++- 4 files changed, 253 insertions(+), 69 deletions(-) diff --git a/server/src/__tests__/github-review-wait.test.ts b/server/src/__tests__/github-review-wait.test.ts index cad6571fe42..f4874dff9a1 100644 --- a/server/src/__tests__/github-review-wait.test.ts +++ b/server/src/__tests__/github-review-wait.test.ts @@ -6,7 +6,41 @@ import { agents, chatActions, chatConversations, chatEndpointResources, chatEndp import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; import { captureReviewWaitQueries, seedGitHubReviewWait, setGitHubReviewAssessment, type CapturedReviewWaitQuery } from "./helpers/github-review-wait.js"; -import { readInheritedGitHubReviewWait } from "../services/chat-channels/github/review-wait.js"; +import { readInheritedGitHubReviewWait, readInheritedGitHubReviewWaits } from "../services/chat-channels/github/review-wait.js"; + +const reviewWaitChanges = ["disabled", "inactive", "review_state", "review_agent", "repository", "repository_id", + "thread", "publication", "identity", "endpoint_agent", "company"] as const; + +async function applyReviewWaitChange(db: Db, f: Awaited>, + change: typeof reviewWaitChanges[number]) { + if (change === "disabled") await db.update(toolConnections).set({ enabled: false }).where(eq(toolConnections.id, f.connectionId)); + if (change === "inactive") await db.update(toolConnections).set({ status: "disabled" }).where(eq(toolConnections.id, f.connectionId)); + if (change === "review_state") await db.update(chatGitHubReviews).set({ state: "queued" }).where(eq(chatGitHubReviews.id, f.reviewId)); + if (change === "review_agent" || change === "endpoint_agent") { + const [other] = await db.insert(agents).values({ companyId: f.companyId, name: "Other", adapterType: "process" }).returning(); + if (change === "review_agent") await db.update(heartbeatRuns).set({ agentId: other!.id }).where(eq(heartbeatRuns.id, f.reviewRunId)); + else await db.update(chatEndpoints).set({ assignedAgentId: other!.id }).where(eq(chatEndpoints.id, f.endpointId)); + } + if (change === "repository") await db.update(chatEndpointResources).set({ providerResourceId: "other/repository" }).where(eq(chatEndpointResources.id, f.resourceId)); + if (change === "repository_id") await db.update(chatEndpointResources).set({ metadata: { providerRepositoryId: "43" } }).where(eq(chatEndpointResources.id, f.resourceId)); + if (change === "thread") await db.update(chatConversations).set({ externalThreadId: "github:synthetic/repository:8" }).where(eq(chatConversations.id, f.conversationId)); + if (change === "publication") await db.update(chatActions).set({ status: "received" }).where(eq(chatActions.id, f.publicationId)); + if (change === "identity") await db.update(runIdentityContexts).set({ status: "rejected" }).where(eq(runIdentityContexts.id, f.activeIdentityContextId!)); + if (change === "company") { + const otherCompanyId = randomUUID(); + await db.insert(companies).values({ id: otherCompanyId, name: "Other", issuePrefix: otherCompanyId }); + f.run = { ...f.run, companyId: otherCompanyId }; + } +} + +/** Record the SQL text of every statement that the client sends. */ +async function withStatements(db: Db, read: () => Promise) { + const client = db.$client as unknown as { unsafe: (query: string, ...rest: unknown[]) => unknown }; + const unsafe = client.unsafe; + const sql: string[] = []; + client.unsafe = (query: string, ...rest: unknown[]) => { sql.push(query); return unsafe.call(client, query, ...rest); }; + try { return { result: await read(), sql }; } finally { client.unsafe = unsafe; } +} describe("inherited GitHub review wait projection", () => { let temporary: Awaited>; @@ -54,32 +88,54 @@ describe("inherited GitHub review wait projection", () => { expect(await readInheritedGitHubReviewWait(db, f.run)).toEqual({ kind: "revoked" }); }); - it.each(["disabled", "inactive", "review_state", "review_agent", "repository", "repository_id", "thread", "publication", "identity", "endpoint_agent", "company"] as const)( + it.each(reviewWaitChanges)( "continues to reject a changed %s binding", async change => { const f = await seedGitHubReviewWait(db); expect((await readInheritedGitHubReviewWait(db, f.run))?.kind).toBe("published"); - if (change === "disabled") await db.update(toolConnections).set({ enabled: false }).where(eq(toolConnections.id, f.connectionId)); - if (change === "inactive") await db.update(toolConnections).set({ status: "disabled" }).where(eq(toolConnections.id, f.connectionId)); - if (change === "review_state") await db.update(chatGitHubReviews).set({ state: "queued" }).where(eq(chatGitHubReviews.id, f.reviewId)); - if (change === "review_agent" || change === "endpoint_agent") { - const [other] = await db.insert(agents).values({ companyId: f.companyId, name: "Other", adapterType: "process" }).returning(); - if (change === "review_agent") await db.update(heartbeatRuns).set({ agentId: other!.id }).where(eq(heartbeatRuns.id, f.reviewRunId)); - else await db.update(chatEndpoints).set({ assignedAgentId: other!.id }).where(eq(chatEndpoints.id, f.endpointId)); - } - if (change === "repository") await db.update(chatEndpointResources).set({ providerResourceId: "other/repository" }).where(eq(chatEndpointResources.id, f.resourceId)); - if (change === "repository_id") await db.update(chatEndpointResources).set({ metadata: { providerRepositoryId: "43" } }).where(eq(chatEndpointResources.id, f.resourceId)); - if (change === "thread") await db.update(chatConversations).set({ externalThreadId: "github:synthetic/repository:8" }).where(eq(chatConversations.id, f.conversationId)); - if (change === "publication") await db.update(chatActions).set({ status: "received" }).where(eq(chatActions.id, f.publicationId)); - if (change === "identity") await db.update(runIdentityContexts).set({ status: "rejected" }).where(eq(runIdentityContexts.id, f.activeIdentityContextId!)); - if (change === "company") { - const otherCompanyId = randomUUID(); - await db.insert(companies).values({ id: otherCompanyId, name: "Other", issuePrefix: otherCompanyId }); - f.run = { ...f.run, companyId: otherCompanyId }; - } + await applyReviewWaitChange(db, f, change); expect((await readInheritedGitHubReviewWait(db, f.run))?.kind).not.toBe("published"); + expect((await readInheritedGitHubReviewWaits(db, [f.run]))[0]?.kind).not.toBe("published"); }, ); + it("reads the waits of many runs with one review read and the same results", async () => { + const [companyId, agentId] = [randomUUID(), randomUUID()]; + await db.insert(companies).values({ id: companyId, name: "Batch", issuePrefix: companyId }); + await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", adapterType: "process" }); + const fixtures: Array>> = []; + for (const change of [null, ...reviewWaitChanges, "newer_head", "no_identity", "no_issue", null] as const) { + const f = await seedGitHubReviewWait(db, change === "company" ? undefined : { companyId, agentId }); + if (change === "newer_head") { + const [review] = await db.select().from(chatGitHubReviews).where(eq(chatGitHubReviews.id, f.reviewId)); + await db.insert(chatGitHubReviews).values({ ...review!, id: randomUUID(), deliveryId: randomUUID(), + headSha: "2".repeat(40), state: "queued", createdAt: new Date(review!.createdAt.getTime() + 1_000) }); + } else if (change === "no_identity") f.run = { ...f.run, activeIdentityContextId: null }; + else if (change === "no_issue") f.run = { ...f.run, nativeIssueId: null }; + else if (change) await applyReviewWaitChange(db, f, change); + fixtures.push(f); + } + // A run can be read twice in one pass. + const [first] = fixtures; + // The "company" wait moved its run to a third company; its own company + // also has one published wait. + const otherCompany = await seedGitHubReviewWait(db); + const runs = [...fixtures.map(f => f.run), first!.run, otherCompany.run]; + const single = []; + for (const run of runs) single.push(await readInheritedGitHubReviewWait(db, run)); + expect(single.filter(wait => wait?.kind === "published")).toHaveLength(4); + // No identity, no task, and an endpoint of another agent have no inherited wait. + expect(single.filter(wait => wait === null)).toHaveLength(3); + expect(single.filter(wait => wait?.kind === "revoked")).toHaveLength(runs.length - 7); + + const { result, sql } = await withStatements(db, () => readInheritedGitHubReviewWaits(db, runs)); + expect(result).toEqual(single); + // One review read and one publication read for each company with a source + // comment, not one of each for every run. + expect(sql.filter(text => /join "chat_github_reviews"/i.test(text))).toHaveLength(2); + expect(sql.filter(text => /from "chat_actions"/i.test(text))).toHaveLength(2); + expect(await readInheritedGitHubReviewWaits(db, [])).toEqual([]); + }); + it("binds each call afresh while reusing the compiled query", async () => { const first = await seedGitHubReviewWait(db), second = await seedGitHubReviewWait(db); const queries: CapturedReviewWaitQuery[] = []; diff --git a/server/src/__tests__/helpers/github-review-wait.ts b/server/src/__tests__/helpers/github-review-wait.ts index ecdcbe0075f..789c4fe9fae 100644 --- a/server/src/__tests__/helpers/github-review-wait.ts +++ b/server/src/__tests__/helpers/github-review-wait.ts @@ -5,14 +5,19 @@ import { agents, chatActions, chatConversations, chatDeliveries, chatEndpointRes runIdentityContexts, toolApplications, toolConnections, type Db } from "@paperclipai/db"; import { defaultGitHubReviewPolicy } from "@paperclipai/shared"; -export async function seedGitHubReviewWait(db: Db) { - const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(); +/** Seed one published inherited review wait. With `into`, the wait is added to + * an existing company and agent. */ +export async function seedGitHubReviewWait(db: Db, into?: { companyId: string; agentId: string }) { + const companyId = into?.companyId ?? randomUUID(), agentId = into?.agentId ?? randomUUID(); + const issueId = randomUUID(), runId = randomUUID(); const reviewRunId = randomUUID(), reviewId = randomUUID(), endpointId = randomUUID(), resourceId = randomUUID(); const conversationId = randomUUID(), commentId = randomUUID(), activeIdentityContextId = randomUUID(); const applicationId = randomUUID(), connectionId = randomUUID(), publicationId = randomUUID(); const headSha = "1".repeat(40), repository = "synthetic/repository", repositoryId = "42", pullNumber = 7; - await db.insert(companies).values({ id: companyId, name: "Synthetic review", issuePrefix: companyId }); - await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", adapterType: "process" }); + if (!into) { + await db.insert(companies).values({ id: companyId, name: "Synthetic review", issuePrefix: companyId }); + await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", adapterType: "process" }); + } await db.insert(issues).values({ id: issueId, companyId, title: "Review", assigneeAgentId: agentId }); await db.insert(heartbeatRuns).values([ { id: runId, companyId, agentId, nativeIssueId: issueId, responsibleUserId: "operator", activeIdentityContextId }, @@ -21,7 +26,7 @@ export async function seedGitHubReviewWait(db: Db) { await db.insert(issueComments).values({ id: commentId, companyId, issueId, authorUserId: "operator", body: "Review" }); await db.insert(runIdentityContexts).values({ id: activeIdentityContextId, companyId, runId, revision: 1, responsibleUserId: "operator", messageId: commentId, cause: "test", correlationId: "test", status: "accepted" }); - await db.insert(toolApplications).values({ id: applicationId, companyId, name: "GitHub", type: "chat" }); + await db.insert(toolApplications).values({ id: applicationId, companyId, name: into ? `GitHub ${applicationId}` : "GitHub", type: "chat" }); await db.insert(toolConnections).values({ id: connectionId, companyId, applicationId, name: "GitHub", uid: connectionId, transport: "chat_sdk", connectionPurpose: "channel", enabled: true, status: "active" }); await db.insert(chatEndpoints).values({ id: endpointId, companyId, connectionId, provider: "github", diff --git a/server/src/services/chat-channels/github/review-wait.ts b/server/src/services/chat-channels/github/review-wait.ts index c3481257780..7f490c327a4 100644 --- a/server/src/services/chat-channels/github/review-wait.ts +++ b/server/src/services/chat-channels/github/review-wait.ts @@ -22,7 +22,7 @@ export async function hasPublishedGitHubReview(db: Db, binding: { eq(chatActions.companyId, binding.companyId), or(...reviews.map(review => and( eq(chatActions.endpointId, review.endpointId), - eq(chatActions.providerActionId, `github_publication:${binding.issueId}:assessment:${createHash("sha256").update(JSON.stringify(review.id)).digest("hex")}`), + eq(chatActions.providerActionId, publicationActionId(binding.issueId, review.id)), ))), eq(chatActions.kind, "github_review_publication"), eq(chatActions.status, "processed"), @@ -33,20 +33,24 @@ export async function hasPublishedGitHubReview(db: Db, binding: { type WaitRun = Pick; +/** The columns of one inherited review. The single read and the batch read + * select the same columns. */ +const inheritedReviewFields = { + id: chatGitHubReviews.id, endpointId: chatGitHubReviews.endpointId, + state: chatGitHubReviews.state, repository: chatGitHubReviews.repository, + repositoryId: chatGitHubReviews.repositoryId, headSha: chatGitHubReviews.headSha, + reviewedCommit: sql`${chatGitHubReviews.assessment}->'reviewedCommit'`, reviewRunId: chatGitHubReviews.runId, + connectionEnabled: toolConnections.enabled, connectionStatus: toolConnections.status, + reviewAgentId: heartbeatRuns.agentId, reviewCompanyId: heartbeatRuns.companyId, + resourceRepository: chatEndpointResources.providerResourceId, + resourceRepositoryId: sql`${chatEndpointResources.metadata}->>'providerRepositoryId'`, + pullNumber: chatGitHubReviews.pullNumber, thread: chatConversations.externalThreadId, +}; + const inheritedReviewQueries = new WeakMap>(); function prepareInheritedReviewQuery(db: Db) { - return db.select({ - id: chatGitHubReviews.id, endpointId: chatGitHubReviews.endpointId, - state: chatGitHubReviews.state, repository: chatGitHubReviews.repository, - repositoryId: chatGitHubReviews.repositoryId, headSha: chatGitHubReviews.headSha, - reviewedCommit: sql`${chatGitHubReviews.assessment}->'reviewedCommit'`, reviewRunId: chatGitHubReviews.runId, - connectionEnabled: toolConnections.enabled, connectionStatus: toolConnections.status, - reviewAgentId: heartbeatRuns.agentId, reviewCompanyId: heartbeatRuns.companyId, - resourceRepository: chatEndpointResources.providerResourceId, - resourceRepositoryId: sql`${chatEndpointResources.metadata}->>'providerRepositoryId'`, - pullNumber: chatGitHubReviews.pullNumber, thread: chatConversations.externalThreadId, - }).from(chatMessageLinks) + return db.select(inheritedReviewFields).from(chatMessageLinks) .innerJoin(chatConversations, and(eq(chatConversations.id, chatMessageLinks.conversationId), eq(chatConversations.companyId, sql.placeholder("companyId")), eq(chatConversations.issueId, sql.placeholder("issueId")))) .innerJoin(chatEndpoints, and(eq(chatEndpoints.id, chatConversations.endpointId), @@ -65,6 +69,8 @@ function prepareInheritedReviewQuery(db: Db) { .prepare("inherited_github_review_wait"); } +type InheritedReviewRow = Awaited["execute"]>>[number]; + function inheritedReviewQuery(db: Db) { let query = inheritedReviewQueries.get(db); if (!query) { @@ -74,35 +80,77 @@ function inheritedReviewQuery(db: Db) { return query; } -/** Passive review waits inherit the same accepted requester lineage as GitHub - * tools. This is not a grant to publish, run a monitor, or reuse attachments. */ -export async function readInheritedGitHubReviewWait(db: Db, run: WaitRun) { +type InheritedReviewKey = { commentId: string; issueId: string; agentId: string }; + +function inheritedReviewKey(key: InheritedReviewKey) { + return `${key.commentId}:${key.issueId}:${key.agentId}`; +} + +/** The latest review for each (source comment, task, agent) key of one + * company. For each key this is the row of the single prepared read: the same + * joins and filters, and DISTINCT ON keeps the first row in the same order. */ +async function readInheritedReviewsForKeys(db: Db, companyId: string, keys: InheritedReviewKey[]) { + const unique = (values: string[]) => [...new Set(values)]; + const rows = await db.selectDistinctOn([chatMessageLinks.commentId, chatConversations.issueId, chatEndpoints.assignedAgentId], { + ...inheritedReviewFields, + keyCommentId: chatMessageLinks.commentId, keyIssueId: chatConversations.issueId, keyAgentId: chatEndpoints.assignedAgentId, + }).from(chatMessageLinks) + .innerJoin(chatConversations, and(eq(chatConversations.id, chatMessageLinks.conversationId), + eq(chatConversations.companyId, companyId), + sql`${chatConversations.issueId} = any(${sql.param(unique(keys.map(key => key.issueId)))}::uuid[])`)) + .innerJoin(chatEndpoints, and(eq(chatEndpoints.id, chatConversations.endpointId), + eq(chatEndpoints.companyId, companyId), eq(chatEndpoints.provider, "github"), + sql`${chatEndpoints.assignedAgentId} = any(${sql.param(unique(keys.map(key => key.agentId)))}::uuid[])`)) + .leftJoin(toolConnections, and(eq(toolConnections.id, chatEndpoints.connectionId), + eq(toolConnections.companyId, companyId))) + .innerJoin(chatEndpointResources, and(eq(chatEndpointResources.id, chatConversations.resourceId), + eq(chatEndpointResources.companyId, companyId), eq(chatEndpointResources.endpointId, chatEndpoints.id))) + .innerJoin(chatGitHubReviews, and(eq(chatGitHubReviews.endpointId, chatEndpoints.id), + eq(chatGitHubReviews.companyId, companyId), eq(chatGitHubReviews.issueId, chatConversations.issueId))) + .leftJoin(heartbeatRuns, eq(heartbeatRuns.id, chatGitHubReviews.runId)) + .where(and(eq(chatMessageLinks.companyId, companyId), + sql`${chatMessageLinks.commentId} = any(${sql.param(unique(keys.map(key => key.commentId)))}::uuid[])`, + eq(chatMessageLinks.direction, "inbound"))) + .orderBy(chatMessageLinks.commentId, chatConversations.issueId, chatEndpoints.assignedAgentId, + desc(chatGitHubReviews.createdAt), desc(chatGitHubReviews.id)); + // The array filters can also match a mix of two keys. Only exact keys are read. + const byKey = new Map(); + for (const { keyCommentId, keyIssueId, keyAgentId, ...review } of rows) { + if (keyCommentId && keyIssueId && keyAgentId) { + byKey.set(inheritedReviewKey({ commentId: keyCommentId, issueId: keyIssueId, agentId: keyAgentId }), review); + } + } + return byKey; +} + +function publicationActionId(issueId: string, reviewId: string) { + return `github_publication:${issueId}:assessment:${createHash("sha256").update(JSON.stringify(reviewId)).digest("hex")}`; +} + +/** The accepted GitHub source comment of the run. A changed requester lineage + * revokes the inherited wait. */ +async function inheritedSourceComment(db: Db, run: WaitRun): Promise<{ kind: "revoked" } | { commentId: string } | null> { if (!run.activeIdentityContextId || !run.nativeIssueId) return null; let commentId: string | null; try { commentId = await chatRunSourceMessageId(db, run, { provider: "github" }); } catch (error) { - if (error instanceof HttpError && error.status === 403) return { kind: "revoked" as const }; + if (error instanceof HttpError && error.status === 403) return { kind: "revoked" }; throw error; } - if (!commentId) return null; - const [review] = await inheritedReviewQuery(db).execute({ - companyId: run.companyId, issueId: run.nativeIssueId, agentId: run.agentId, commentId, - }); - // A newer unreviewed head cannot inherit the prior head's publication. - if (!review) return null; - if (!review.connectionEnabled || review.connectionStatus !== "active" || review.state !== "completed" || - review.reviewCompanyId !== run.companyId || review.reviewAgentId !== run.agentId || - review.reviewedCommit !== review.headSha || - review.resourceRepository.toLowerCase() !== review.repository.toLowerCase() || - review.resourceRepositoryId !== review.repositoryId || - review.thread.toLowerCase() !== `github:${review.repository}:${review.pullNumber}`.toLowerCase()) return { kind: "revoked" as const }; - const [publication] = await db.select({ id: chatActions.id }).from(chatActions).where(and( - eq(chatActions.companyId, run.companyId), eq(chatActions.endpointId, review.endpointId), - eq(chatActions.kind, "github_review_publication"), eq(chatActions.status, "processed"), - eq(chatActions.providerActionId, `github_publication:${run.nativeIssueId}:assessment:${createHash("sha256").update(JSON.stringify(review.id)).digest("hex")}`), - )).limit(1); - if (!publication) return { kind: "revoked" as const }; + return commentId ? { commentId } : null; +} + +function inheritedReviewRevoked(run: WaitRun, review: InheritedReviewRow) { + return !review.connectionEnabled || review.connectionStatus !== "active" || review.state !== "completed" || + review.reviewCompanyId !== run.companyId || review.reviewAgentId !== run.agentId || + review.reviewedCommit !== review.headSha || + review.resourceRepository.toLowerCase() !== review.repository.toLowerCase() || + review.resourceRepositoryId !== review.repositoryId || + review.thread.toLowerCase() !== `github:${review.repository}:${review.pullNumber}`.toLowerCase(); +} + +function publishedInheritedWait(run: WaitRun, commentId: string, review: InheritedReviewRow) { // The caller must still verify live task ownership, destination and principal // policy. This normalized source is used only by the passive-wait boundary. return { kind: "published" as const, endpointId: review.endpointId, reviewId: review.id, reviewRunId: review.reviewRunId, @@ -113,3 +161,74 @@ export async function readInheritedGitHubReviewWait(db: Db, run: WaitRun) { issue: { id: run.nativeIssueId }, commentIds: [commentId] }, } }; } + +export type InheritedGitHubReviewWait = { kind: "revoked" } | ReturnType | null; + +/** Passive review waits inherit the same accepted requester lineage as GitHub + * tools. This is not a grant to publish, run a monitor, or reuse attachments. */ +export async function readInheritedGitHubReviewWait(db: Db, run: WaitRun): Promise { + const source = await inheritedSourceComment(db, run); + if (!source || !("commentId" in source)) return source; + const { commentId } = source; + const [review] = await inheritedReviewQuery(db).execute({ + companyId: run.companyId, issueId: run.nativeIssueId, agentId: run.agentId, commentId, + }); + // A newer unreviewed head cannot inherit the prior head's publication. + if (!review) return null; + if (inheritedReviewRevoked(run, review)) return { kind: "revoked" }; + const [publication] = await db.select({ id: chatActions.id }).from(chatActions).where(and( + eq(chatActions.companyId, run.companyId), eq(chatActions.endpointId, review.endpointId), + eq(chatActions.kind, "github_review_publication"), eq(chatActions.status, "processed"), + eq(chatActions.providerActionId, publicationActionId(run.nativeIssueId!, review.id)), + )).limit(1); + if (!publication) return { kind: "revoked" }; + return publishedInheritedWait(run, commentId, review); +} + +/** `readInheritedGitHubReviewWait` for the runs of one read-only pass, such + * as the waits of an issue page. Each run gets the same result as a separate + * call. The source lineage is still checked for each run. The reviews and the + * publications of all the runs of one company are read with one statement + * each, not with two statements for each run. */ +export async function readInheritedGitHubReviewWaits(db: Db, runs: WaitRun[]): Promise { + const sources = await Promise.all(runs.map(run => inheritedSourceComment(db, run))); + const results: InheritedGitHubReviewWait[] = sources.map(source => source && !("commentId" in source) ? source : null); + const byCompany = new Map>(); + runs.forEach((run, index) => { + const source = sources[index]; + if (!source || !("commentId" in source)) return; + const entries = byCompany.get(run.companyId) ?? []; + entries.push({ index, run, commentId: source.commentId }); + byCompany.set(run.companyId, entries); + }); + for (const [companyId, entries] of byCompany) { + const keyOf = ({ run, commentId }: { run: WaitRun; commentId: string }) => + ({ commentId, issueId: run.nativeIssueId!, agentId: run.agentId }); + const reviews = await readInheritedReviewsForKeys(db, companyId, entries.map(keyOf)); + const reviewed: Array<{ index: number; run: WaitRun; commentId: string; review: InheritedReviewRow; actionId: string }> = []; + for (const entry of entries) { + const review = reviews.get(inheritedReviewKey(keyOf(entry))); + // A newer unreviewed head cannot inherit the prior head's publication. + if (!review) continue; + if (inheritedReviewRevoked(entry.run, review)) { + results[entry.index] = { kind: "revoked" }; + continue; + } + reviewed.push({ ...entry, review, actionId: publicationActionId(entry.run.nativeIssueId!, review.id) }); + } + if (!reviewed.length) continue; + const publications = await db.select({ endpointId: chatActions.endpointId, providerActionId: chatActions.providerActionId }) + .from(chatActions).where(and( + eq(chatActions.companyId, companyId), + sql`${chatActions.endpointId} = any(${sql.param([...new Set(reviewed.map(entry => entry.review.endpointId))])}::uuid[])`, + eq(chatActions.kind, "github_review_publication"), eq(chatActions.status, "processed"), + sql`${chatActions.providerActionId} = any(${sql.param([...new Set(reviewed.map(entry => entry.actionId))])}::text[])`, + )); + const processed = new Set(publications.map(publication => `${publication.endpointId}:${publication.providerActionId}`)); + for (const { index, run, commentId, review, actionId } of reviewed) { + results[index] = processed.has(`${review.endpointId}:${actionId}`) + ? publishedInheritedWait(run, commentId, review) : { kind: "revoked" }; + } + } + return results; +} diff --git a/server/src/services/native-runtime/external-review-wait.ts b/server/src/services/native-runtime/external-review-wait.ts index 5d05c779cb1..2b3e05cd2ba 100644 --- a/server/src/services/native-runtime/external-review-wait.ts +++ b/server/src/services/native-runtime/external-review-wait.ts @@ -1,6 +1,6 @@ import { and, eq, inArray, sql } from "drizzle-orm"; import { chatConversations, chatEndpoints, heartbeatRuns, issues, statusDecisions, type Db } from "@paperclipai/db"; -import { readInheritedGitHubReviewWait } from "../chat-channels/github/review-wait.js"; +import { readInheritedGitHubReviewWaits } from "../chat-channels/github/review-wait.js"; import { authorizeChatConversationsForBoundRuns } from "./chat-attachment-reuse.js"; import { EXTERNAL_CHAT_QUESTION_RESPONSE_KEY } from "./external-chat-question-response.js"; @@ -61,15 +61,19 @@ export async function listExternalReviewWaits(db: Db, companyId: string, issueId eq(chatEndpoints.status, "active"), )) .where(and(eq(issues.companyId, companyId), inArray(issues.id, issueIds), eq(issues.status, "in_review"))); - const authorizable = (await Promise.all(candidates.map(async ({ runId, agentId, contextSnapshot, responsibleUserId, activeIdentityContextId, ...wait }) => { - const inheritedWait = await readInheritedGitHubReviewWait(db, { - id: runId, companyId, agentId, responsibleUserId, activeIdentityContextId, - nativeIssueId: wait.issueId, issueId: wait.issueId, contextSnapshot, - }); - if (inheritedWait?.kind === "revoked") return null; - return { wait, binding: { companyId, issueId: wait.issueId, runId, agentId }, - contextSnapshot: inheritedWait?.context ?? contextSnapshot }; - }))).filter((candidate): candidate is NonNullable => candidate !== null); + // One review read and one publication read for every wait of the page, not + // two reads per wait. Each wait gets the same inherited result as before. + const inheritedWaits = await readInheritedGitHubReviewWaits(db, candidates.map(candidate => ({ + id: candidate.runId, companyId, agentId: candidate.agentId, responsibleUserId: candidate.responsibleUserId, + activeIdentityContextId: candidate.activeIdentityContextId, nativeIssueId: candidate.issueId, + issueId: candidate.issueId, contextSnapshot: candidate.contextSnapshot, + }))); + const authorizable = candidates.flatMap(({ runId, agentId, contextSnapshot, responsibleUserId: _user, activeIdentityContextId: _context, ...wait }, index) => { + const inheritedWait = inheritedWaits[index]; + if (inheritedWait?.kind === "revoked") return []; + return [{ wait, binding: { companyId, issueId: wait.issueId, runId, agentId }, + contextSnapshot: inheritedWait?.context ?? contextSnapshot }]; + }); // One authorization read for every wait of the page, not one per wait: the // per-wait reads each held a pool connection at the same moment. const authorized = await authorizeChatConversationsForBoundRuns(db, companyId, authorizable); From ad0543ae90851da610de8df5ee0b4128ea6b1185 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 18:47:29 -0600 Subject: [PATCH 05/38] test(recovery): re-arm a capture-policy save whose finished coordinator names a lapsed owner (#20672) 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 > - Workspace recovery re-arms a save that an older capture policy exhausted (#20569), so the files are saved without a person > - On staging, one save of this kind was not re-armed after the deploy. Its export hold also carries a workspace finalization block, and it has a resolved no-replay sibling for the same run > - #20661 found that discovery skipped a hold when the run's finished coordinator still named a lease owner whose lease had lapsed. The same discovery clause gates the capture-policy re-arm > - This pull request adds a regression test for that exact capture-policy shape. It shows that #20661 alone makes the worker re-arm and save it > - The benefit is that the capture-policy path keeps this guarantee in later changes ## Linked Issues or Issue Description Refs #20661 Refs #20569 **What happened?** An exhausted capture-policy save (`export_interrupted`, cause `provider_error`, 6 of 6 attempts, phase `preserve_files`) was not re-armed on the worker's first pass after #20569 was deployed. **What did you expect to happen?** The worker re-arms the save once under the current capture policy, saves the files, and returns the hold to the system. **Steps to reproduce** 1. Exhaust a save under capture policy 1 with `export_interrupted`. Add a workspace finalization block and a resolved no-replay sibling for the same run. 2. Leave a lapsed `native-finalizer:` lease owner on the run's `terminal_failure` coordinator. 3. Run the workspace recovery worker. Before #20661, `nextWorkspaceRecoveryAt` returns null and the hold is never selected. ## What Changed - `workspace-recovery-capture-policy.test.ts`: add "re-arms a save whose finished coordinator still names a lapsed finalizer owner". The test uses the staging record: export hold with `historicalWorkspaceSource` and `workspaceFinalizationBlock`, a resolved no-replay sibling, waiting user input, and a lapsed finalizer owner. It drives the worker's own discovery loop until the worker is idle. - No production code changes. ## Verification - Red: with the source files from before #20661 (`git checkout 686893636d^ -- `), the new test fails. `nextWorkspaceRecoveryAt` returns null, so the worker is never woken. - Green: on current master, `pnpm --filter @paperclipai/server exec vitest run src/services/workspace-recovery-capture-policy.test.ts` passes (5 tests). The file passed 4 runs in a row. - The test asserts that the save completes under policy 2, the hold returns to the system, `releasedLapsedOwner` is recorded, and the lapsed owner is released. ## Risks - Low risk. This change adds a test only. - Previous-release story: the test uses rows in the shape an older release saved, with no capture-policy marker. No migration is needed. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell, code editing, browser GET reads) in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../workspace-recovery-capture-policy.test.ts | 37 ++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/server/src/services/workspace-recovery-capture-policy.test.ts b/server/src/services/workspace-recovery-capture-policy.test.ts index 0cf7c81b8ad..1440c960272 100644 --- a/server/src/services/workspace-recovery-capture-policy.test.ts +++ b/server/src/services/workspace-recovery-capture-policy.test.ts @@ -3,7 +3,7 @@ import { mkdir, readFile, symlink, writeFile } from "node:fs/promises"; import path from "node:path"; import { eq } from "drizzle-orm"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { activityLog, agentWakeupRequests, executionWorkspaces, heartbeatRuns, issueRecoveryActions, issues } from "@paperclipai/db"; +import { activityLog, agentWakeupRequests, executionWorkspaces, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations } from "@paperclipai/db"; import type { AdapterSandboxExecutionTarget } from "@paperclipai/adapter-utils/execution-target"; import { readRemoteWorkspaceAuthority } from "@paperclipai/shared"; import { getExecutionBlocker } from "./execution-blocker.js"; @@ -215,6 +215,41 @@ describe("saves exhausted under an older workspace capture policy", () => { expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toBeNull(); }, 90_000); + it("re-arms a save whose finished coordinator still names a lapsed finalizer owner", async () => { + const f = await stagingIncident(false); + const exportHold = await action(f.actionId); + const source = (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0]!; + await db.update(issueRecoveryActions).set({ evidence: { ...exportHold.evidence, workspaceFinalizationBlock: { + schema: "paperclip.native-workspace-finalization-block.v1", runId: f.runId, agentId: source.agentId, issueId: f.issueId, + companyId: f.companyId, resultId: f.resultId, contractId: source.completionContractId, resultSha256: "5".repeat(64), + contractSha256: "0".repeat(64), statusVersion: 7, priorDecisionId: null, identityContextId: randomUUID(), + responsibleUserId: "board" } } }).where(eq(issueRecoveryActions.id, f.actionId)); + const lapsedOwner = `native-finalizer:${randomUUID()}`; + await db.update(nativeRunFinalizations).set({ leaseOwner: lapsedOwner, leaseExpiresAt: new Date(Date.now() - 8 * 60 * 60_000), + controllerBootId: randomUUID(), controllerPid: 2_147_000_000 }).where(eq(nativeRunFinalizations.runId, f.runId)); + expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0]) + .toMatchObject({ phase: "terminal_failure" }); + + expect(await nextWorkspaceRecoveryAt(db)).toBeLessThanOrEqual(Date.now()); + expect((await retainedWorkspaceCandidates(db, undefined, false, true)).map(row => row.action.id)).toContain(f.actionId); + let passes = 0; + for (; passes < 6; passes += 1) { + const due = await nextWorkspaceRecoveryAt(db); + if (due === null || due > Date.now()) break; + await Promise.all(await reconcileRetainedWorkspaces(db, f.environmentRuntime, async () => undefined, true) ?? []); + } + expect(passes).toBeLessThan(6); + + const saved = await action(f.actionId); + expect(readSystemRecovery(saved.evidence)).toMatchObject({ state: "complete", capturePolicyVersion: REMOTE_WORKSPACE_CAPTURE_POLICY_VERSION }); + expect(readWorkspaceRecovery(saved.evidence)?.status).toBe("recovered"); + expect(saved.evidence.capturePolicyRecovery).toMatchObject({ releasedLapsedOwner: true }); + expect(saved.ownerType).toBe("system"); + expect(String(saved.nextAction)).not.toMatch(adminText); + expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0]?.leaseOwner) + .not.toBe(lapsedOwner); + }, 90_000); + it("does not re-arm a save that the current policy already exhausted", async () => { const f = await exhaustedCaptureHold(REMOTE_WORKSPACE_CAPTURE_POLICY_VERSION); expect((await retainedWorkspaceCandidates(db, undefined, false, true)).map(row => row.action.id)).not.toContain(f.actionId); From cec903c6f01e492042ca3664958ffef3e69fc4df Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 18:49:26 -0600 Subject: [PATCH 06/38] fix(native): retire a finished remote owner whose gone Runner left a delivery unacknowledged (#20677) 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 > - A native follow-up run on a remote sandbox first proves that the previous per-turn owner finished. Then it retires that owner's controller journal and starts a new Runner. > - The proof requires a settled journal. A command that the Runner did not acknowledge holds the owner. > - On staging, a per-turn owner committed its result and its Daytona sandbox was destroyed after the turn (`paperclip_runner_destroy_after_turn`, cleanup `success`). Its journal still held a `run.attach` or a `semantic_tool.result` that the Runner never acknowledged. > - The next run failed with `prior_owner_terminal_state_indeterminate; retirement_refused=journal_commands_unsettled(run.attach.pending)` (or `semantic_tool.result.pending`). A Retry or a new message gets the same journal, so it fails the same way. The task stays blocked. > - Retirement already excuses the Runner's own lifecycle commands when the prior sandbox lease ended on another sandbox. This pull request applies the same rule to deliveries that only that gone Runner could receive. > - The benefit is that these follow-ups start by themselves. Commands that carry user intent still hold the owner. ## Linked Issues or Issue Description **What happened?** A census of staging failures (48 h, Nov 9–10) found 6 failed runs with `prior_owner_terminal_state_indeterminate` and `retirement_refused=journal_commands_unsettled(run.attach.pending | semantic_tool.result.pending)`. The last one was at 18:56 UTC on Nov 10. In two examples that I checked: - The previous run succeeded. Its result was committed and its coordinator lease was released. - Its lease policy was `ephemeral`. The lease is `expired`, with `failureReason=paperclip_runner_destroy_after_turn` and `cleanupStatus=success`. - The follow-up got a new sandbox (a different provider lease) and refused in about 11 s. It started no Runner. The task became `blocked`, and the next action was "Send a message to continue". **Expected behavior** When the record proves that the previous Runner is gone, an undelivered attachment, tool answer or read cannot run. The follow-up retires the finished owner and starts a new Runner. Retirement replays no command. **Steps to reproduce** 1. Finish a per-turn remote native run whose controller journal keeps a `run.attach` or `semantic_tool.result` command in `pending`. 2. Let the sandbox lease of that run end (`expired` or `released`) on its own sandbox. 3. Start a follow-up run that gets a new sandbox. 4. Observe `retirement_refused=journal_commands_unsettled(run.attach.pending)`. **Paperclip version or commit** Staging builds of Nov 10. The refusal still reproduces on `master` at `48c6e996da` (the new tests fail there). ## What Changed - `native-session-executor.ts` (`readSettledRunnerdProjection`): when the prior run's sandbox leases ended on another sandbox (`remoteRunnerGone`, the existing proof), unfinished `run.attach`, `semantic_tool.result`, `session.snapshot` and `session.goal.get` commands no longer hold the retirement. These join the lifecycle commands that the rule already excused. - In the same case, a journaled `semantic_tool.result` answers its `semantic_tool.input`. The controller journals the answer after the tool ran. Only its delivery was outstanding. - No other proof changes. The prior run must still be terminal, with a committed result, a released coordinator lease, no recovery state, a stopped or fenced controller, a delivered `run.terminal`, and no live work after it. Quarantine copies must pass the same checks. - `doc/execution-semantics.md`: describe the rule. ## Verification - `server/src/services/native-runtime/native-recovered-owner-followup.test.ts` (real Postgres): - New: "retires a finished remote owner with an unacknowledged pending-attach / pending-tool-result when its sandbox lease ended on another sandbox". It fails on `master` with the exact staging errors `journal_commands_unsettled(run.attach.pending)` and `journal_commands_unsettled(semantic_tool.result.pending)`. It passes with this change, and the log shows the retirement. - Held cases stay held: a lease that is still retained, a lease on this run's sandbox, no lease record, and a tool input with no journaled answer (`journal_tool_input_unanswered`). - New: "keeps a stopped local owner held by an unacknowledged run.attach". A local Runner is not gone by record. - Whole file: 95 passed. - Neighbouring suites pass: `explicit-native-continuation.test.ts` and `native-controller-recovery.integration.test.ts` (460 tests). - `npx tsc --noEmit -p server/tsconfig.json` passes. - `pnpm verify` exits 2: a global CI input changed (`doc/execution-semantics.md`). Required CI supplies the broad coverage. - Live proof: not done. The redeploy chaos scenario (K15) is not on `master` yet. Tests only. ## Risks - The rule applies only when every sandbox lease of the prior run is `released` or `expired`, has a release time, and names a different provider lease than this run's. A reusable sandbox that this run resumed keeps the existing hold. - A command that carries user intent (`turn.start`, `turn.steer`, `request.resolve`, `interaction.receipt`, `external_provider.operation`, `session.goal.set`/`clear`, `session.close`, `run.cancel` and others) still holds the owner. - Retirement archives the old journal under `continuity-breaks` and replays nothing, as before. - No persisted shape changes. Old saved journals are read by the same rule. > 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, used through Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude --- doc/execution-semantics.md | 20 +++++++ .../native-recovered-owner-followup.test.ts | 53 ++++++++++++++++++- .../native-runtime/native-session-executor.ts | 16 +++++- 3 files changed, 85 insertions(+), 4 deletions(-) diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 67d40550fab..aaf5361224e 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -3258,6 +3258,26 @@ admission applies the same checks as for a per-turn owner. The journal of a warm owner has no `runner.suspend` command. A local warm Runner and a resumed sandbox that still holds the Runner keep the live adoption path. +A remote Runner whose sandbox lease for the prior run ended (`released` or +`expired`, with a release time) on a different sandbox than this run's is gone +by record. No process remains that could act on a command it never +acknowledged. For such an owner, these unfinished commands do not hold the +retirement: + +- its own lifecycle commands (`runner.suspend`, `runner.drain`, + `runner.shutdown`); +- deliveries that only that Runner could receive: `run.attach`, + `semantic_tool.result`, `session.snapshot` and `session.goal.get`. A + journaled `semantic_tool.result` also answers its tool input, because the + controller journals the answer after the tool ran. + +Retirement replays none of these commands. Any other unfinished command, such +as `turn.start`, `turn.steer`, `request.resolve` or +`external_provider.operation`, still holds the owner. A tool input with no +journaled answer still holds it with `journal_tool_input_unanswered`. A +retained lease, a lease on this run's sandbox, or a missing lease record keeps +every unfinished command decisive. + The provider session then follows the normal resume-or-replace policy. A resumed sandbox, a local warm session, a plugin task, a restart claim, or any missing proof keeps the existing `prior_owner_terminal_state_indeterminate` diff --git a/server/src/services/native-runtime/native-recovered-owner-followup.test.ts b/server/src/services/native-runtime/native-recovered-owner-followup.test.ts index 271da7146e4..15562311197 100644 --- a/server/src/services/native-runtime/native-recovered-owner-followup.test.ts +++ b/server/src/services/native-runtime/native-recovered-owner-followup.test.ts @@ -92,7 +92,7 @@ describe.skipIf(!recoveryPostgresSupport.supported)("follow-up after a recovered * Only the database controller checkpoint and recovery pointer survive. */ async function seedRecoveredPriorRun(control: "settled" | "pending-command" | "unanswered-tool" | "failed-turn-start" | "rejected-turn-start" | "indeterminate-turn-start" | "unknown-outcome-turn-start" - | "unsuperseded-unknown-outcome-turn-start" | "failed-suspend" = "settled", + | "unsuperseded-unknown-outcome-turn-start" | "failed-suspend" | "pending-attach" | "pending-tool-result" = "settled", options: { controller?: { bootId: string; pid: number; processStartedAt: Date }; provider?: "codex" | "acpx" | "opencode"; lifecycle?: "warm" } = {}) { const issueId = randomUUID(), workspaceId = randomUUID(), runId = randomUUID(); @@ -150,10 +150,16 @@ describe.skipIf(!recoveryPostgresSupport.supported)("follow-up after a recovered Object.assign(commands.find(command => command.type === "turn.start")!, unknownOutcome); } if (control === "failed-suspend") Object.assign(commands.at(-1)!, { status: "failed", result: { status: "failed" } }); + // Staging PAP-4196 and PAP-3443: the controller journaled a delivery to the + // per-turn Runner that the Runner never acknowledged before its sandbox was + // destroyed after the turn. + if (control === "pending-attach") controller.queueCommand("run.attach", { provider: "fixture" }); + const toolInput = control === "unanswered-tool" || control === "pending-tool-result"; + if (control === "pending-tool-result") controller.queueCommand("semantic_tool.result", { sourceEventId: "unanswered-tool-input" }); const event = (sourceSeq: number, sourceEventId: string, eventType: string) => ({ sourceSeq, sourceEventId, eventType, priority: 0 as const, envelope: { ...identity }, deliveryCount: 1, logicalEffectCount: 1 }); controller.store.state.committedEvents.push( - ...(control === "unanswered-tool" ? [event(1, "unanswered-tool-input", "semantic_tool.input")] : []), + ...(toolInput ? [event(1, "unanswered-tool-input", "semantic_tool.input")] : []), event(2, "recovered-terminal", "run.terminal")); controller.store.state.ackedSourceSeq = 2; controller.setCheckpointPersistence(nativeRunnerCheckpointWriter(db, owner)); @@ -760,6 +766,38 @@ describe.skipIf(!recoveryPostgresSupport.supported)("follow-up after a recovered expect(await followUp.start()).toBe(outcome); }, 60_000); + // Staging PAP-4196 (run.attach) and PAP-3443 (semantic_tool.result): the + // per-turn owner committed its result and its sandbox was destroyed after the + // turn, but its journal still held a delivery that its Runner never + // acknowledged. No process remains to receive it, so the follow-up retires + // the owner. A Runner whose sandbox may still exist keeps the owner held. + it.each([ + { control: "pending-attach", label: "ended on another sandbox", status: "expired", sameSandbox: false, recorded: true, + outcome: ADMITTED }, + { control: "pending-tool-result", label: "ended on another sandbox", status: "expired", sameSandbox: false, recorded: true, + outcome: ADMITTED }, + { control: "pending-attach", label: "still retained", status: "retained", sameSandbox: false, recorded: true, + outcome: stranded("journal_commands_unsettled(run.attach.pending)") }, + { control: "pending-tool-result", label: "ended on this sandbox", status: "expired", sameSandbox: true, recorded: true, + outcome: stranded("journal_commands_unsettled(semantic_tool.result.pending)") }, + { control: "pending-tool-result", label: "not recorded", status: "expired", sameSandbox: false, recorded: false, + outcome: stranded("journal_commands_unsettled(semantic_tool.result.pending)") }, + { control: "unanswered-tool", label: "ended on another sandbox", status: "expired", sameSandbox: false, recorded: true, + outcome: stranded("journal_tool_input_unanswered") }, + ] as const)("retires a finished remote owner with an unacknowledged $control when its sandbox lease $label", + async ({ control, status, sameSandbox, recorded, outcome }) => { + const prior = await seedRecoveredPriorRun(control, { provider: "opencode" }); + const followUp = await admitFollowUp(prior); + if (recorded) { + await db.insert(environments).values({ id: followUp.environmentId, name: `ended-${followUp.environmentId}`, driver: "sandbox" }); + await db.insert(environmentLeases).values({ companyId, environmentId: followUp.environmentId, issueId: prior.issueId, + heartbeatRunId: prior.runId, provider: "daytona", providerLeaseId: sameSandbox ? followUp.providerLeaseId : `sandbox-${prior.runId}`, + status, releasedAt: status === "retained" ? null : new Date(), metadata: { remoteCwd: "/workspace" } }); + } + expect(await followUp.start()).toBe(outcome); + if (outcome === ADMITTED) expect(followUp.logs.join("")).toContain("finished without a saved runner checkpoint"); + }, 60_000); + it("admits again when a retry rebuilds the same projection from the database", async () => { const prior = await seedRecoveredPriorRun(); const followUp = await admitFollowUp(prior); @@ -1072,6 +1110,17 @@ describe.skipIf(!recoveryPostgresSupport.supported)("follow-up after a recovered expect(await followUp.startLocal()).toBe(stranded("journal_commands_unsettled(turn.start.pending)")); }, 60_000); + it("keeps a stopped local owner held by an unacknowledged run.attach", async () => { + // Only a remote Runner whose sandbox lease ended elsewhere is gone by record. + const { followUp, root } = await seedUnsuspendedLocalOwner(await stoppedRunnerProcess()); + const path = join(root, "control-plane", "control-plane-state.json"); + const state = JSON.parse(await readFile(path, "utf8")); + state.commands.push({ ...state.commands.at(-1), commandId: "command_unacknowledged_attach", + controllerSeq: state.commands.length + 1, type: "run.attach", status: "pending", result: null }); + await writeFile(path, JSON.stringify(state)); + expect(await followUp.startLocal()).toBe(stranded("journal_commands_unsettled(run.attach.pending)")); + }, 60_000); + it.each(["uncommitted result", "committed without result", "live controller lease", "unexpired controller lease", "recovery pending", "pending command", "unanswered tool input", "foreign quarantine"] as const)("keeps the prior owner held with %s", async scenario => { const prior = await seedRecoveredPriorRun(scenario === "pending command" ? "pending-command" diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index dafc06da83e..37a7a8631d2 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -5668,6 +5668,12 @@ function moveNativeContinuityState(root: string, archiveRoot: string): void { type SettledRunnerdProjection = { bytes: string; refused?: never } | { bytes?: never; refused: string }; const LOCAL_RUNNER_LIFECYCLE_COMMANDS = new Set(["runner.suspend", "runner.drain", "runner.shutdown"]); +/** Commands that only deliver something to the Runner that held this journal: + * its attachment, an answer to a tool it already called, or a read. None + * carries new user intent, and none can run without that Runner. When its + * sandbox lease ended on another sandbox, no process remains to receive them. */ +const GONE_REMOTE_RUNNER_DELIVERY_COMMANDS = new Set(["run.attach", "semantic_tool.result", "session.snapshot", + "session.goal.get"]); function readSettledRunnerdProjection(root: string, identity: Record, options: { localRunner?: boolean; controlBytes?: string; remoteRunnerGone?: boolean } = {}): SettledRunnerdProjection { @@ -5690,12 +5696,18 @@ function readSettledRunnerdProjection(root: string, identity: Record !LOCAL_RUNNER_LIFECYCLE_COMMANDS.has(String(command.type)) || command.status === "completed") + ? commands.filter(command => !goneCommandTypes.has(String(command.type)) || command.status === "completed") : commands; const settledControl = settledCommands === commands ? control : { ...control, commands: settledCommands }; + // The controller journals a tool's answer after the tool ran. Only its + // delivery can be outstanding, and only to a Runner that is gone. const answered = new Set(commands - .filter(command => command.type === "semantic_tool.result" && command.status === "completed") + .filter(command => command.type === "semantic_tool.result" && (command.status === "completed" || options.remoteRunnerGone)) .map(command => record(command.payload).sourceEventId)); if (!RUNNERD_CONTROL_PLANE_STATE_SCHEMAS.has(String(control.schema))) return refuse("journal_schema_unsupported"); if (control.warmTransition != null) return refuse("journal_warm_transition"); From e33ede9a8add1fd83b4ea16c8a803d943c74204a Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:05:15 -0600 Subject: [PATCH 07/38] fix(native): settle a restart-orphaned write_document from its transactional receipt (#20674) 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 > - A native run calls Paperclip tools such as `write_document`. The runner saves each tool input durably before the server runs the tool, and the server saves a result receipt > - A control-plane restart can cut a `write_document` call after the runner saved its input and before any result was saved > - Recovery then has no proof of the outcome. A call from an earlier server process settles as "unknown outcome" (#20628). A call the current server process admitted stays pending, close cannot prove that the provider drained, and the session quarantines (`native_session_cleanup_quarantined`). A person must click Retry > - `write_document` saves its revision and its idempotency receipt in one database transaction, under the run and issue row locks. The revision is also compare-and-swap on `baseRevisionId`. So the receipt is a durable outcome record: present means applied, absent means not applied > - This pull request makes recovery use that proof. Recovery runs the same receipt-guarded write. It replays the saved result, or it applies the write exactly once > - The benefit is that an orphaned `write_document` settles with its real result. The document is never written twice, and the run does not need Retry for this call ## Linked Issues or Issue Description **What happened?** Daytona restart-chaos wave `w-20261110T174930-s9205`, task t01 (codex, workload C1, fault RR2). A restart cut a `write_document` call. The close settlement showed `semanticTools.pending: [{ operationId: "write_document", callId: "exec-8b79ab78-…" }]` and `providerDrained: false`. The session quarantined with `native_session_cleanup_quarantined`, and the task needed Retry. Since #20628, a call that an earlier server process admitted settles as `tool_call_interrupted_by_restart` with an unknown outcome. The agent then has to guess whether the write applied. **Expected behavior** When a durable record proves the outcome, recovery uses it. A write that applied returns its saved result. A write that did not apply runs once. When the record cannot prove it, the call stays as it is today. **Steps to reproduce** 1. On master, run `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/paperclip-runner-tool-authority.test.ts -t "orphaned"`. 2. `authority.recover()` returns `null` for a `write_document` that has no receipt, so the call stays unsettled. Refs #20628, #20639, #20507 ## What Changed - `PaperclipRunnerToolAuthority.recover()` now settles `write_document` through its transactional receipt (`#recoverTransactionalWrite`). It runs the same receipt-guarded mutation as an ordinary call. If the receipt exists, it returns the saved result and writes nothing. If no receipt exists, it applies the write once. - A definite refusal that rolls the transaction back (a 4xx such as a stale `baseRevisionId`, a reused idempotency key, invalid input) settles as a tool error. Any other failure leaves the call unsettled, as before. - The set of operations with this proof is explicit: `TRANSACTIONAL_RECEIPT_OPERATIONS` contains only `write_document`. Other tools keep their current recovery rules. - New test: an orphaned `write_document` with no receipt applies once; a second recovery and a late original call replay the receipt; an applied write recovers its saved result; a stale base settles as a tool error with no change. - Updated test: a reused idempotency key with other input now settles as an `paperclip_runner_tool_idempotency_conflict` tool error instead of staying pending. The receipt proves that this call can never apply under that key. - Docs: `packages/paperclip-runner/docs/durable-recovery.md` (semantic operations that outlive a turn) and a new design note, `doc/plans/2026-11-10-durable-turn-start-and-tool-call-records.md`. The note also covers the second change (an ACPX turn start cut off before the prompt reached the provider), which comes in a separate pull request. ## Verification - Red on master, green here: `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/paperclip-runner-tool-authority.test.ts` (43 passed). - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-runner-restart-recovery.integration.test.ts`: 178 passed. One unrelated ACPX timing test failed once under load and passed when run alone. - Server typecheck: `npx tsc --noEmit -p server/tsconfig.json` passes. - `pnpm verify` exits 2 (a runner doc changed), so required CI supplies the broad coverage. - Live restart-chaos wave: see the comment on this pull request. ## Risks - Recovery can now apply a write that never applied before the restart. This is the call the agent made, applied once. The write is compare-and-swap on `baseRevisionId`, so it cannot overwrite a revision that someone wrote after the agent read the document. That case settles as a conflict error. - Upgrade safety: no saved shape changes. Receipts saved by the previous release have the same shape. A server on the previous release keeps its current recovery for these calls. - Time to first token: no change. This code runs only during recovery. - No runner source changes, so no new runner image is needed. ## Model Used Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell, file editing) in Claude Code. Extended reasoning was used. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- ...urable-turn-start-and-tool-call-records.md | 56 ++++++++++++++++ .../paperclip-runner/docs/durable-recovery.md | 12 ++++ .../control-plane/orphaned-tool-callback.ts | 7 ++ ...unner-restart-recovery.integration.test.ts | 5 +- .../paperclip-runner-tool-authority.test.ts | 66 +++++++++++++++++++ .../paperclip-runner-tool-authority.ts | 48 +++++++++++++- 6 files changed, 192 insertions(+), 2 deletions(-) create mode 100644 doc/plans/2026-11-10-durable-turn-start-and-tool-call-records.md diff --git a/doc/plans/2026-11-10-durable-turn-start-and-tool-call-records.md b/doc/plans/2026-11-10-durable-turn-start-and-tool-call-records.md new file mode 100644 index 00000000000..a7828ba4e0f --- /dev/null +++ b/doc/plans/2026-11-10-durable-turn-start-and-tool-call-records.md @@ -0,0 +1,56 @@ +# Durable records for cut-off turn starts and orphaned tool calls + +Status: approved by Dotta (2026-11-10), being implemented in two PRs +Goal: after a control-plane restart or freeze, 0% of tasks need Retry, and Retry still works whenever it is shown. +Parent plan: `2026-11-07-durable-ownership-and-reconciliation.md`, section B (write-ahead intents) and section F (charge only on recorded outcomes). + +## Rule + +Recovery may resend, replay or continue only when a durable record proves that no provider work and no tool effect can be duplicated or lost. A duplicated prompt or a second write is worse than a Retry click. When the record cannot prove it, the existing behaviour stays: a working Retry. + +## Change 1: a turn start cut off before the prompt reached the provider + +**What happens today.** Restart-chaos wave `w-20261110T185315-s9107`, task t05 (claude, workload C1, fault TM2). A follow-up run's `turn.start` reaches the Runner, which saves the ACPX session as `turn_starting` and asks the ACPX sidecar to start the turn. For a resumed Claude session the sidecar first starts Claude and loads the conversation; the prompt is sent only after that. Under load this took more than 24 s. Then the harness froze the server, the Runner, the sidecar and Claude together (SIGSTOP) for 33 s. On thaw the Runner's 30 s sidecar request deadline had passed, so it reaped the sidecar and saved the session as `closed`. Every same-run resume then failed with `ACPX session is not open`, recovery stopped with `native_session_retry_exhausted`, and a person had to click Retry. + +The Runner cannot tell from its own state whether Claude received the prompt. Resending could duplicate it; a continuation could lose it. + +**The record: a sidecar prompt-dispatch journal.** The ACPX sidecar writes one small file in the session's private runtime directory (`0700`) for each turn: + +1. When the runtime port starts the turn, before any provider work: one line `{"schema":…,"turnId":X,"phase":"received"}`, truncating the previous turn's file. No fsync. +2. When ACPX is about to write that turn's first `session/prompt` request to the provider's stdin: one appended line `{"phase":"dispatched"}`, then `fsync`, and only then the write. ACPX calls the host's `onAcpMessage("outbound", …)` hook synchronously before it hands the bytes to the provider stream, so a failed journal write aborts the prompt write. + +The file name and record shape are declared in `protocol/provider-schemas/acpx-sidecar.schema.json` and generated into TypeScript and Rust, so the pack contract digest covers them. + +**What it proves.** The Runner reads the journal only after it has proved that the sidecar and the provider are gone (it terminated the sidecar and acquired the provider lifetime fence, the same proof the existing lost-turn restore uses). A dead sidecar cannot write or send anything more. + +| Journal for the active turn | Meaning | Recovery | +|---|---|---| +| exactly one complete `received` line | the prompt was never written to the provider | restore the session with no active turn; emit `harness.diagnostic` `acpx_turn_start_not_dispatched`; the same-run resume sends the run's `turn.start` once | +| a `dispatched` line | the provider may have the prompt | unchanged: the existing lost-turn path (restore and continue in the same conversation, or close) | +| missing, another turn, malformed, torn | unknown | unchanged | + +Both cut-off shapes use it: a sidecar request that failed in flight (timeout or sidecar exit), and a Runner killed while the session was `turn_starting`. + +**Resend exactly once.** The cut-off `turn.start` command stays failed; it is never executed again. The restored session has no active turn, so the next same-run resume starts the turn with the run's own input. If that start is cut off too, the journal decides again. + +## Change 2: a tool call orphaned by a restart + +**What happens today.** Daytona wave `w-20261110T174930-s9205`, task t01 (codex, C1, RR2): a restart cut a `write_document` callback after the Runner journaled its input and before a result was saved. Close could not prove the provider drained, so the session quarantined (`native_session_cleanup_quarantined`). Since #20628 a callback admitted by an earlier controller settles as `tool_call_interrupted_by_restart` (unknown outcome, never executed again); a callback the current controller admitted still stays pending. + +**The record already exists.** The intent is the Runner's durable semantic input (committed before dispatch, keyed by call ID). The outcome is the server's idempotency receipt in `heartbeat_runs.result_json.semanticToolReceipts`. For `write_document` the revision, the activity row and the receipt commit in one transaction under the run and issue row locks, and the revision is compare-and-swap on `baseRevisionId`. + +**What it proves.** Receipt present: applied. Receipt absent: not applied, because the effect cannot commit without it. So recovery runs the same receipt-guarded mutation. It replays the saved result or applies the write for the first time, never twice. A late original callback then replays the receipt. A stale base, a reused key or invalid input is the call's definite outcome and settles as a tool error. Any other failure leaves the call unsettled, as before. The set of operations with this proof is explicit (`TRANSACTIONAL_RECEIPT_OPERATIONS`, `write_document` only); other tools keep their current rules. + +This makes the gateway call idempotent on its durable input, which is the cleaner proof the brief allowed. It needs no Runner change and no new image. + +**Not done.** Exposing the cleanup-gate owner's run id so the server can drop the 50-run scan bound from #20639 (optional in the brief) is left out to keep scope. + +## Upgrade safety + +- Old saved state, new code. A `turn_starting` session saved by an older Runner has no journal (or one for another turn): unknown, so the old lost-turn path runs unchanged. Old receipts already have the shape the transactional recovery reads. +- New state, old code mid-deploy. Change 1 adds no field to `acpx-provider-state.json` (its decoder denies unknown fields). It only saves lifecycles an old Runner already handles (`prepared`, then `suspended`/`session_open`). An old Runner ignores the journal file. Change 2 changes no saved shape. +- New Runner, old sidecar. Possible only with a stale pack; the contract digest prevents reuse. If it happens anyway, an old sidecar writes no `received` line, so the proof never forms. + +## Time to first token + +Change 2 touches only recovery. Change 1 adds to every turn, before the prompt reaches the provider: one small unsynced file write when the turn starts, and one append plus `fsync` immediately before the prompt write. It adds no wait, no file transfer and no round trip. The measured cost is in the change 1 PR (target: well under 5 ms p95 on local disks, against a 9.5–16.5 s TTFT p50 budget). Recovery-time work (fence proof, journal read) runs only after a failure. diff --git a/packages/paperclip-runner/docs/durable-recovery.md b/packages/paperclip-runner/docs/durable-recovery.md index 84c8e0101bc..d62874891e0 100644 --- a/packages/paperclip-runner/docs/durable-recovery.md +++ b/packages/paperclip-runner/docs/durable-recovery.md @@ -603,6 +603,18 @@ callback that this process is not running (`dispatchToolCallback`) as earlier controller can never record a result, so this is the callback's only settlement, and it never executes the operation again. Every other unresolved input stays unsettled. + +`write_document` needs neither fallback. Its revision and its idempotency +receipt commit in one transaction under the run and issue row locks, and the +revision is compare-and-swap on `baseRevisionId`. The receipt is therefore the +durable outcome record: present means the write applied, absent means it did +not. Recovery runs the same receipt-guarded mutation, whichever controller +admitted the callback. It returns the saved result when the receipt exists and +applies the write once when it does not. A stale base, a reused key or invalid +input is the call's real outcome and settles as a tool error. Any other failure +leaves the call unsettled. A late original callback then replays the receipt, +so the document is never written twice. + A different case is a runner crash after the controller saved the result but before its delivery command completed. Codex/OpenCode explicitly opt in to reconciling that exact `semantic_tool.result` command through their durable tool diff --git a/packages/paperclip-runner/src/control-plane/orphaned-tool-callback.ts b/packages/paperclip-runner/src/control-plane/orphaned-tool-callback.ts index ef0ce5bf10a..b187c0bb13f 100644 --- a/packages/paperclip-runner/src/control-plane/orphaned-tool-callback.ts +++ b/packages/paperclip-runner/src/control-plane/orphaned-tool-callback.ts @@ -15,6 +15,13 @@ * callback settles as interrupted with an unknown outcome. It is never * executed again. A callback that this process is still running, or that this * process dispatched and saw fail, stays pending. + * + * Exception: an authority may settle a transactional write itself, for any + * admission, when its effect and receipt commit in one locked transaction + * (server `TRANSACTIONAL_RECEIPT_OPERATIONS`, today only `write_document`). + * Its `recover` then runs the receipt-guarded write, which replays the saved + * result or applies it once; the owner-gone guard here is not what makes that + * safe. */ import type { SemanticInputAdmission } from "./durable-prp-control-plane.js"; 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 7dcb86f8345..0e401700d39 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 @@ -929,8 +929,11 @@ process.on("SIGTERM", () => child.kill("SIGTERM")); } } }).where(eq(heartbeatRuns.id, fixture.runId)); await expect(recover(call)) .resolves.toEqual({ result: { revision: "revision-1" } }); + // write_document's receipt commits with its revision, so a key whose + // receipt holds other input proves this call can never apply under it. await expect(recover({ ...call, input: { ...call.input, body: "changed" } })) - .resolves.toBeNull(); + .resolves.toMatchObject({ isError: true, result: { success: false, contentItems: [ + { type: "inputText", text: expect.stringContaining("paperclip_runner_tool_idempotency_conflict") }] } }); await expect(recover({ ...call, operationId: "unknown_external_write" })) .resolves.toBeNull(); expect(executeRead).not.toHaveBeenCalled(); diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts index a7efadbf80a..262c166c0b2 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts @@ -1314,6 +1314,72 @@ describe("PaperclipRunnerToolAuthority", () => { ).rejects.toThrow("paperclip_runner_tool_idempotency_conflict"); }); + it("settles a write_document a restart orphaned from its transactional receipt, applying it at most once", async () => { + // A restart can cut a write_document callback after the runner journaled + // its input but before any result was saved. The revision and its receipt + // commit in one transaction, so recovery can prove which side it is on. + const authority = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId }); + const notApplied = { + tool: "write_document", + callId: "orphaned-write-not-applied", + arguments: { idempotencyKey: "orphaned-write-not-applied", key: "orphan-brief", title: "Brief", + body: "Recovered once.", baseRevisionId: null, changeSummary: "Initial brief" }, + }; + // No receipt: the write provably never applied. Recovery applies it once. + const recovered = await authority.recover(notApplied); + expect(recovered).toMatchObject({ result: { disposition: "applied", created: true, document: { key: "orphan-brief" } } }); + expect(recovered?.isError).not.toBe(true); + const applied = await documentService(db).getIssueDocumentByKey(issueId, "orphan-brief"); + expect(applied).toMatchObject({ body: "Recovered once.", latestRevisionNumber: 1 }); + // A second recovery, and the original callback arriving late, both replay + // the receipt instead of writing again. + expect(await authority.recover(notApplied)).toEqual(recovered); + expect(await authority.execute(notApplied)).toEqual(recovered!.result); + expect(await documentService(db).getIssueDocumentByKey(issueId, "orphan-brief")) + .toMatchObject({ latestRevisionNumber: 1 }); + + // Receipt present: the write applied before the restart. Recovery returns + // the saved result and writes nothing. + const update = { + tool: "write_document", + callId: "orphaned-write-applied", + arguments: { idempotencyKey: "orphaned-write-applied", key: "orphan-brief", title: "Brief", + body: "Second revision.", baseRevisionId: applied!.latestRevisionId, changeSummary: "Update" }, + }; + const original = await authority.execute(update); + expect(await authority.recover(update)).toEqual({ result: original }); + expect(await documentService(db).getIssueDocumentByKey(issueId, "orphan-brief")) + .toMatchObject({ body: "Second revision.", latestRevisionNumber: 2 }); + + // A write whose base moved on cannot apply. Recovery reports the definite + // conflict as a tool error and changes nothing. + const stale = { + tool: "write_document", + callId: "orphaned-write-stale", + arguments: { idempotencyKey: "orphaned-write-stale", key: "orphan-brief", title: "Brief", + body: "Stale.", baseRevisionId: applied!.latestRevisionId, changeSummary: "Stale" }, + }; + // A task switched to ask mode refuses a write that never applied, while + // a write that did apply still replays its receipt. + await db.update(issues).set({ workMode: "ask" }).where(eq(issues.id, issueId)); + try { + const askMode = await authority.recover({ ...notApplied, callId: "orphaned-write-ask", + arguments: { ...notApplied.arguments, idempotencyKey: "orphaned-write-ask", key: "orphan-ask" } }); + expect(JSON.stringify(askMode)).toContain("paperclip_runner_tool_mode_denied"); + expect(askMode).toMatchObject({ isError: true }); + expect(await documentService(db).getIssueDocumentByKey(issueId, "orphan-ask")).toBeNull(); + expect(await authority.recover(update)).toEqual({ result: original }); + } finally { + await db.update(issues).set({ workMode: "standard" }).where(eq(issues.id, issueId)); + } + + const conflict = await authority.recover(stale); + expect(conflict).toMatchObject({ isError: true, result: { success: false } }); + expect(JSON.stringify(conflict)).toContain("Document was updated by someone else"); + expect(await documentService(db).getIssueDocumentByKey(issueId, "orphan-brief")) + .toMatchObject({ body: "Second revision.", latestRevisionNumber: 2 }); + }); + it("returns the exact accepted plan revision in task context", async () => { const plan = await documentService(db).getIssueDocumentByKey( issueId, diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts index c3ed5300321..7a718df59be 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts @@ -174,6 +174,19 @@ const RECOVERABLE_READ_OPERATIONS = new Set([ READ_CURRENT_WAKE_COMMENTS_TOOL_NAME, LIST_CHAT_ATTACHMENTS_TOOL_NAME, READ_CHAT_ATTACHMENT_TOOL_NAME, READ_TOOL_RESULT, "connections_search", ]); +// Writes whose effect and idempotency receipt commit in one transaction, with +// no outside effect before commit, and whose effect is compare-and-swap on the +// state it read. Recovery may run them again: the receipt proves whether the +// first attempt applied (see #recoverTransactionalWrite). +const TRANSACTIONAL_RECEIPT_OPERATIONS = new Set(["write_document"]); +const TRANSACTIONAL_RECOVERY_REFUSALS = new Set([ + "paperclip_runner_tool_idempotency_conflict", "paperclip_runner_tool_input_invalid", + "paperclip_runner_tool_mode_denied", +]); +function nativeToolAllowedInMode(operationId: string, workMode: string): boolean { + return CAPABILITY_SEMANTIC_TOOL_CATALOG.some(candidate => candidate.operationId === operationId + && candidate.allowedModes.includes(workMode as "standard" | "planning" | "ask")); +} const RECOVERABLE_READ_ERRORS = new Set([ "paperclip_runner_document_not_found", "paperclip_runner_agent_not_found", "paperclip_runner_approval_not_found", "paperclip_runner_tool_input_invalid", @@ -477,6 +490,7 @@ export class PaperclipRunnerToolAuthority { if (!Object.hasOwn(receipt, "result")) return null; return { result: await this.#withInstructionMutationReceipt(call.tool, call.callId, input, true) }; } + if (TRANSACTIONAL_RECEIPT_OPERATIONS.has(call.tool)) return this.#recoverTransactionalWrite(call.tool, input); // Recovery goes through the receipt owner: it must use the same parsed // input, current authority and safe post-commit dispatch as an ordinary // retry, without ever falling through to an uncertain mutation. @@ -541,6 +555,32 @@ export class PaperclipRunnerToolAuthority { + " Call list_agents and copy a valid id exactly; nothing was created or changed."); } + /** + * Settle a transactional write whose callback a restart cut off. The effect + * and its idempotency receipt commit in one transaction under the run and + * issue row locks, so the receipt is the durable outcome record: present + * means applied, absent means not applied. Running the same receipt-guarded + * mutation therefore either replays the saved result or applies the write + * for the first time, never twice. A definite pre-commit refusal (a stale + * base, a reused key, invalid input) is the call's real outcome and returns + * as a tool error; any other failure stays unsettled. + */ + async #recoverTransactionalWrite(tool: string, input: Record) { + try { + if (tool === "write_document") return { result: await this.#writeDocument(input, true) }; + throw new Error(`paperclip_runner_transactional_recovery_unsupported: ${tool}`); + } catch (error) { + // Each of these is raised before the transaction commits, so it rolls the + // write back: the call's outcome is this refusal, not an unknown one. + const definite = error instanceof HttpError ? error.status >= 400 && error.status < 500 + : error instanceof Error && TRANSACTIONAL_RECOVERY_REFUSALS.has(error.message); + if (!definite) throw error; + return { isError: true, result: { + success: false, contentItems: [{ type: "inputText", text: (error as Error).message }], + } }; + } + } + async #recoverRead(call: Parameters[0]) { try { return { result: await this.execute(call) }; @@ -1850,10 +1890,16 @@ export class PaperclipRunnerToolAuthority { return result; } - async #writeDocument(input: Record): Promise { + async #writeDocument(input: Record, recovering = false): Promise { const idempotencyKey = requiredString(input.idempotencyKey); let publication: Awaited>["publication"] | null = null; const result = await this.#withMutationReceipt("write_document", idempotencyKey, input, async (tx, context) => { + // execute() checks the work mode before dispatch. A recovered write + // applies later, so it checks the mode it locked; a saved receipt + // still replays without this check because its effect already applied. + if (recovering && !nativeToolAllowedInMode("write_document", context.issue.workMode)) { + throw new Error("paperclip_runner_tool_mode_denied"); + } const sourceTrust = this.binding.museRuntime ? await resolveActorSourceTrustForIssue({ db: tx, issue: context.issue, actor: { actorType: "agent", actorId: this.binding.agentId, agentId: this.binding.agentId, runId: this.binding.runId } }) : undefined; const write = await documentService(tx).upsertIssueDocument({ From 2eede8b3183f877f9afbf06655aa1eee07590d28 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:14:43 -0600 Subject: [PATCH 08/38] fix(native): give a relaunched settled runner its admitted provider pack (#20683) 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. > - After a server restart or a same-run retry, a remote native run reattaches to its runner in the sandbox (`reattach_remote_runner`). > - When the controller saved the runner artifact, the executor prepares that run as an adoption. It skips provider-pack selection, because a live adopted runner keeps its launched provider. > - The reattach probe can instead find the runner settled and exited (`verifyRemoteRunnerOrSettledExit`). Then nothing is adopted, and the transport relaunches the runner from its durable state. That relaunch must start the provider again, so it needs the provider-pack launch inputs. > - The executor did not give them. OpenCode failed with "OpenCode executable is missing from the provider pack". ACPX failed with "ACPX launch profile omitted its provider-pack authority or verified artifact digests". Both ended the run. > - This pull request selects the saved (admitted) provider-pack authority on that settled-exit relaunch and verifies it as an exact installed identity, as an ordinary reattach does. > - The benefit is that a restart or a same-run retry can resume an exited runner with the same provider pack, instead of failing. ## Linked Issues or Issue Description **What happened?** On a hosted staging instance, two OpenCode runs and one ACPX (Claude) run were interrupted by a deploy (SIGTERM) or ended a turn without a result. The server scheduled a same-run retry that reattached to the existing remote runner. The runner had exited cleanly (`runner_remote_process_exited lifecycle=suspended`). The retry then failed within three seconds with `runner_remote_provider_artifact_incompatible`. **Steps to reproduce** 1. Prepare a remote OpenCode or ACPX run with a persisted runner artifact (`controllerPersistence.runnerArtifact`). 2. Reattach with `restartRecovery.kind = "reattach_remote_runner"`, where the runner process is not running and its state is `suspended` and settled. 3. Observe that the transport options have no `adoptExistingRunner`, no `providerPackAuthorityDigest` and no `opencodeCommand` / `acpxSidecarSha256`. **Expected behavior** The relaunch gets the admitted provider pack's launch inputs, or it fails with a clear pack-identity error. ## What Changed - `createRunnerdBackend` (native session executor): when a persisted-runner reattachment finds no live runner to adopt, select the saved provider-pack authority (`reattach: true`), so `expectedProviderPackManifest` is the admitted pack. - `prepareRemoteRunnerAssets` no longer returns early for that relaunch. It verifies the installed pack as an exact identity and sets the active pack root, the same path as a reattach without a persisted artifact. - A live adopted runner is unchanged: it still skips pack selection. - The test `uses the bundled Linux image authority for remote opencode|claude-x64` now also covers the settled-exit relaunch for OpenCode and ACPX. ## Verification - RED on `origin/master` (`c444da7d05`): the extended test fails for `opencode` and `claude-x64` (the relaunch options have no provider-pack inputs). - GREEN with this change: `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-session-executor.test.ts -t "uses the bundled Linux image authority"` (14 passed). - `pnpm --filter @paperclipai/server typecheck` passes. - `pnpm verify`: see the result below. ## Risks - Upgrade safety: the relaunch reads the saved authority, so a newer controller does not select a newer pack for an older session. It requires an exact installed identity. If the sandbox no longer has that pack, the relaunch fails with a pack-identity error, and the existing Retry path applies, as before. - No change to a live adoption, to fresh runs or to the normal path before `turn.start`. > 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, read-only staging API reads). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude --- .../native-session-executor.test.ts | 24 +++++++++++++++++++ .../native-runtime/native-session-executor.ts | 13 +++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index 928353e57be..b67247d57a4 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -2650,6 +2650,30 @@ describe("remote provider pack manifest", () => { leaseOwner: "controller", controllerGeneration: 2, providerAttempt: 1, restartKind: "graceful", recoveryRequestId: null, remote: { providerLeaseId: "sandbox", remoteCwd: "/workspace" } }, }; + // Staging failure (OpenCode and ACPX): a same-run + // retry under a persisted runner artifact found the runner settled and + // exited. Nothing is adopted, so the transport relaunches it from its + // durable state and needs the admitted provider pack's launch inputs. + const settledExecute = vi.fn(async (request: { args: string[] }) => { + if (request.args[2] === "paperclip-runner-recovery-check") return { exitCode: 45, timedOut: false, stderr: "", stdout: "" }; + if (request.args[1]?.includes("base64")) return { exitCode: 0, timedOut: false, stderr: "", stdout: Buffer.from(JSON.stringify({ + ...identity, lifecycle: "suspended", outbox: [], pendingTerminalDelivery: null, pendingProviderCleanup: null, warmTransition: null, + })).toString("base64") }; + return recoveryExecute(request); + }); + const settledTarget = { ...(recoveryInput.runnerExecutionTarget as unknown as Record), + runner: { execute: settledExecute, syncIn: vi.fn(async () => undefined), syncOut: vi.fn(async () => undefined) } }; + await createRunnerdBackend({ ...recoveryInput, runnerExecutionTarget: settledTarget as never, + controllerPersistence: { bootId: "replacement-controller", runnerArtifact: artifact } }); + state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!(); + const relaunched = state.createTransport.mock.calls.at(-1)![0] as RunnerTransportOptions; + expect(relaunched.adoptExistingRunner).toBeUndefined(); + expect(relaunched).toMatchObject({ providerPackAuthorityDigest: admitted.digest, runnerArtifact: artifact, + providerNodeCommandSha256: admitted.payload.artifacts.nodeCommand.sha256, + ...(opencode + ? { opencodeCommand: `/opt/paperclip-runner/provider-pack/${admitted.payload.artifacts.opencodeExecutable.path}`, + opencodeCommandSha256: admitted.payload.artifacts.opencodeExecutable.sha256 } + : { acpxSidecarSha256: (admitted.payload.artifacts as Record).acpxSidecar.sha256 }) }); const recoveredBackend = await createRunnerdBackend(recoveryInput); state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!(); const recovered = state.createTransport.mock.calls.at(-1)![0]; diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 37a7a8631d2..fb5c533b658 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -15435,6 +15435,10 @@ async function createRunnerdBackendWithinSessionClaim( let expectedProviderPackManifest: RemoteProviderPackManifest | null = providerPackAuthority?.manifest ?? providerArtifacts?.manifest as RemoteProviderPackManifest ?? null; let providerPackVerified = false; + // Set when a persisted-runner reattachment finds that runner settled and + // exited. The transport then relaunches it from durable state, which needs + // the admitted provider pack's launch inputs that adoption does not. + let relaunchesSettledRemoteRunner = false; const explicitRemoteCodex = input.runnerRemoteCodexPath?.trim() || null; const remoteCodexNpmSpec = input.runnerRemoteCodexNpmSpec?.trim() || null; if (explicitRemoteCodex && remoteCodexNpmSpec) { @@ -15595,7 +15599,7 @@ async function createRunnerdBackendWithinSessionClaim( return; selectedRemoteMode = requiredMode; if (input.restartRecovery?.kind === "reattach_remote_runner" || input.remoteWarmRecovery) { - if (input.controllerPersistence?.runnerArtifact) { + if (input.controllerPersistence?.runnerArtifact && !relaunchesSettledRemoteRunner) { remotePrepared = true; return; } @@ -16690,6 +16694,13 @@ async function createRunnerdBackendWithinSessionClaim( signalVerifiedRecoveryProcess(localRecoveryProcess, signal), } : undefined; + if (adoptingPersistedRemoteRunner && !adoptedProcess && requiresRemoteProviderPack) { + // Bind the relaunch to the pack this session was admitted with (the saved + // authority, verified as an exact installed identity), never a newer one. + relaunchesSettledRemoteRunner = true; + providerPackAuthority = selectProviderPackAuthority(true); + expectedProviderPackManifest = providerPackAuthority?.manifest ?? expectedProviderPackManifest; + } if (adoptedProcess && remoteTarget) { const markSpawned = resolveRemoteRunnerProcessSpawned as (() => void) | null; markSpawned?.(); From 4a61a2501e424698fb9e711a5fad7a8ff4448efd Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:22:26 -0600 Subject: [PATCH 09/38] fix(storage): never promise a storage retry no storage wait owns (#20676) 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 > - A run that hits a file-storage outage gets a bounded storage wait: a retry that starts again after storage is back > - The run error says "Paperclip will retry automatically when storage is back" > - On staging, a server restart reattached a remote native runner while its turn was still running. A storage outage then failed the reattachment > - Restart recovery kept the workspace under a no-replay hold, so the run took the code `native_continuation_requires_reconciliation`. Only a `storage_unavailable` run gets a storage wait, so no retry was scheduled. The run still showed the storage retry promise, and the task stayed blocked for about 15 hours > - This pull request makes the storage text follow the run's final code and the real storage wait outcome, and reads old rows truthfully > - The benefit is that every storage message is true: it promises a retry only when one is scheduled, and it offers a working Retry when nothing retries the run ## Linked Issues or Issue Description **What happened?** A native run on a remote sandbox was reattached after a server restart. Its provider turn was still in flight. File storage failed during the reattachment. Restart recovery settled the run as `native_continuation_requires_reconciliation`, kept its files, and did not replay the unfinished turn (this is the existing policy for a turn with an unknown outcome). The run error said "Paperclip will retry automatically when storage is back". No storage wait was scheduled, so nothing retried. The task stayed blocked until an operator clicked Retry. **Root cause** `server/src/services/heartbeat/run-completion.ts` chose the message and the error code separately. The message used `isStorageUnavailableError(err)`. The code used a chain where `nativeTerminalFailureCode` wins over `storage_unavailable`. The storage wait is scheduled only when the code is `storage_unavailable` (and no native terminal failure is recorded). So the message promised a wait that the code made impossible. The same false promise stayed when the storage wait was refused (`not_scheduled`) or its write failed. **Expected behavior** A storage failure promises an automatic retry only when the storage wait is scheduled. Otherwise it offers Retry. Rows saved by earlier releases read the same way after deploy, with no migration. **Steps to reproduce** Fail a native run with a storage-unavailable error after its native coordinator is settled as `terminal_failure` / `native_continuation_requires_reconciliation`. See the new regression in `run-completion.test.ts`. ## What Changed - `storage-unavailable.ts`: add the held messages (outage and rejected credentials). They say Paperclip is not retrying automatically and offer Retry or a message. Add `storageUnavailableHeldMessage()` and `presentStorageFailureMessage()`. - `run-completion.ts` (`failRun`): compute the error code first. Use the storage retry promise only when the code is `storage_unavailable`. Under any other code (for example a native recovery hold), use the held message. No storage wait is created for such a run, because it could only be refused. - `run-completion.ts` (`failRun` and `failRunSetup`): replace `markStorageWaitExhausted` with `settleStorageWaitMessage`. It keeps the promise only when a retry is scheduled. It writes the exhausted text when the budget is spent, and the held text when the wait was refused, its write failed, or a case handoff took over. - `run-completion.ts`: when the promise is withdrawn, the failure's `error` event (written before the retry decision) gets the same final text, so the transcript does not keep the promise after reload. - `run-completion.ts` (`failRunSetup`): a lost controller lease keeps its own code and text, not the storage promise. - `run-lifecycle.ts`: `decorateHeartbeatRunRuntimeStatus` presents a saved storage retry promise under a code other than `storage_unavailable` with the held text. This covers run detail and issue run presence. `listRuns` in `run-state.ts` applies the same projection, so the company run list and the Inbox failure read agree. Rows from earlier releases read truthfully with no migration. - `doc/run-log-events.md`: document which runs get a storage wait and what each message means. Previous-release story (upgrade-safe run state): this change adds no persisted shape. Rows saved by the previous release carry forward. A row with the storage promise under another code reads with the held text. A `storage_unavailable` row keeps its text. The native hold policy is unchanged: an unfinished turn with an unknown outcome is not replayed automatically, and the existing Retry continues it. ## Verification - Red before the fix (assertion failures, not setup errors): the new `run-completion.test.ts` cases received "Paperclip will retry automatically when storage is back" under `native_continuation_requires_reconciliation`, and the `run-lifecycle.test.ts` cases read the saved promise unchanged. - Green after the fix: - `cd server && npx vitest run src/services/heartbeat/run-completion.test.ts src/services/heartbeat/run-lifecycle.test.ts -t storage` (13 passed) - `cd server && npx vitest run src/services/heartbeat/run-completion.test.ts src/services/heartbeat/run-lifecycle.test.ts src/storage/storage-unavailable.test.ts` (213 passed) - `cd server && npx tsc --noEmit -p tsconfig.json` (clean) - Existing storage cases still pass: a scheduled storage wait keeps its promise and suppresses rapid recovery; an exhausted wait writes the exhausted text. - `pnpm verify` exited 2 (a doc is a global CI input), so required CI supplies the broad coverage. - The full `run-completion.test.ts` file passed every test locally. Its `afterAll` hook timed out under machine load (load average about 17), also with the new tests skipped. ## Risks - Low risk. The change affects only the text of failed runs and one read projection. It does not change retry scheduling, recovery ownership, or replay policy. - The read projection matches this repository's own two promise constants under a code other than `storage_unavailable`. A future change to those constants must keep the projection in sync. - Error events already written by earlier releases keep their original text in the run log. Live events already published before a withdrawn promise are not resent. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits, browser reads for GET-only diagnostics). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] 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 --- doc/run-log-events.md | 14 +++++ .../services/heartbeat/run-completion.test.ts | 60 ++++++++++++++++++- .../src/services/heartbeat/run-completion.ts | 56 ++++++++++++----- .../services/heartbeat/run-lifecycle.test.ts | 21 ++++++- .../src/services/heartbeat/run-lifecycle.ts | 3 + .../src/services/heartbeat/run-state.test.ts | 14 +++++ server/src/services/heartbeat/run-state.ts | 3 + server/src/storage/storage-unavailable.ts | 25 ++++++++ 8 files changed, 180 insertions(+), 16 deletions(-) diff --git a/doc/run-log-events.md b/doc/run-log-events.md index fd7624cb8f9..c0e89d5da38 100644 --- a/doc/run-log-events.md +++ b/doc/run-log-events.md @@ -658,6 +658,20 @@ for file storage before ; it was still unavailable." Its payload holds `reason: "storage_outage_wait"`, `purpose` (the step), `waitedMs`, and `recovered`. The record stays in the instance run log. +When the outage outlasts that wait, the run fails. Only a run recorded with +`errorCode: "storage_unavailable"` gets a storage wait: a bounded retry +(`retryReason: "storage_unavailable_wait"`) that starts again after storage is +back. Its error says "Paperclip will retry automatically when storage is back" +only while that retry is scheduled. When the retry budget is spent, the error +says so and asks for Retry. When no storage wait follows, the error says +"Paperclip is not retrying it automatically. Retry or send a message to +continue." That happens when a native recovery already holds the run under +another code (for example `native_continuation_requires_reconciliation`, where +its files are kept and its unfinished turn is not replayed), or when the retry +is refused or cannot be written. A run saved by an earlier release with the +retry promise under another code reads with the same Retry text, with no +migration. + ## Durable storage timing A saved remote workspace is one encrypted archive in durable object storage. diff --git a/server/src/services/heartbeat/run-completion.test.ts b/server/src/services/heartbeat/run-completion.test.ts index 77458f2a094..89ae9892542 100644 --- a/server/src/services/heartbeat/run-completion.test.ts +++ b/server/src/services/heartbeat/run-completion.test.ts @@ -33,7 +33,7 @@ import { PluginWorkerUnavailableError } from "../plugin-worker-unavailable-error import { ReviewedChatBindingDeniedError, ReviewedChatBindingNotReadyError } from "../reviewed-chat-binding-diagnostics.js"; import { environmentTaskErrorCodeData, JsonRpcCallError, PluginEnvironmentTaskError, PluginWorkspaceOperationError, workspaceOperationErrorData } from "@paperclipai/plugin-sdk"; import { RUNNER_REVISION_MISMATCH_RETRY } from "../runner-revision-mismatch.js"; -import { STORAGE_UNAVAILABLE_CODE, STORAGE_UNAVAILABLE_EXHAUSTED_MESSAGE, STORAGE_UNAVAILABLE_MESSAGE, STORAGE_UNAVAILABLE_RETRY } from "../../storage/storage-unavailable.js"; +import { STORAGE_CREDENTIALS_REJECTED_HELD_MESSAGE, STORAGE_UNAVAILABLE_CODE, STORAGE_UNAVAILABLE_EXHAUSTED_MESSAGE, STORAGE_UNAVAILABLE_HELD_MESSAGE, STORAGE_UNAVAILABLE_MESSAGE, STORAGE_UNAVAILABLE_RETRY } from "../../storage/storage-unavailable.js"; import { withS3FailureDiagnostics } from "../../storage/s3-failure.js"; import { workspaceProviderCallFailure } from "../workspace-provider-failure.js"; import { logger } from "../../middleware/logger.js"; @@ -857,6 +857,64 @@ describe.skipIf(!support.supported && !process.env.PAPERCLIP_TEST_DATABASE_URL)( error: STORAGE_UNAVAILABLE_EXHAUSTED_MESSAGE }); }); + // Staging incident shape: a server restart reattached a remote native runner whose turn was + // still in flight. A storage outage then failed the reattachment, restart + // recovery kept the workspace under a no-replay hold, and the run reported + // "Paperclip will retry automatically when storage is back" with no storage + // wait scheduled. The task sat blocked for 15 hours behind a false promise. + it.each([ + ["an outage", "ServiceUnavailable", 503, STORAGE_UNAVAILABLE_HELD_MESSAGE], + ["rejected credentials", "ExpiredToken", 403, STORAGE_CREDENTIALS_REJECTED_HELD_MESSAGE], + ] as const)("never promises a storage retry when native recovery holds the run after %s", async (_label, name, status, expected) => { + const f = await fixture({ runtimeMode: "native" }); + const [issue] = await db.insert(issues).values({ companyId: f.run.companyId, title: "Daily staging review", + assigneeAgentId: f.agent.id, status: "in_progress" }).returning(); + await db.update(agentWakeupRequests).set({ runId: f.run.id, reason: "issue_monitor_due", requestedByActorType: "system" }) + .where(eq(agentWakeupRequests.id, f.wake.id)); + const [run] = await db.update(heartbeatRuns).set({ nativeIssueId: issue.id, + contextSnapshot: { issueId: issue.id, wakeReason: "issue_monitor_due", wakeSource: "automation" } }) + .where(eq(heartbeatRuns.id, f.run.id)).returning(); + await appendHeartbeatRunEvent(db, { companyId: run.companyId, runId: run.id, agentId: run.agentId, + eventType: "turn.started", stream: "system", level: "info", message: "Provider turn started" }); + // Restart recovery's workspace preservation already settled the coordinator. + await db.insert(nativeRunFinalizations).values({ companyId: run.companyId, issueId: issue.id, runId: run.id, + phase: "terminal_failure", attempt: 1, controllerGeneration: 3, recoveryState: "blocked", + failureCode: "native_continuation_requires_reconciliation" }); + const outage = await withS3FailureDiagnostics("put_object", async () => { + throw Object.assign(new Error("Injected storage outage"), { name, $metadata: { httpStatusCode: status, attempts: 3 } }); + }).catch(error => error as Error); + await f.completion.failRun({ ...f.failure(outage), run, issueId: issue.id, requiredWorkspaceRestoreEvidence: {}, legacyAdapterEntered: false }); + const failed = await read(run.id); + expect(failed).toMatchObject({ status: "failed", errorCode: "native_continuation_requires_reconciliation", error: expected }); + expect(failed.error).not.toMatch(/retry automatically/i); + expect(failed.error).toContain("Retry"); + // No storage wait is created for a run native recovery owns: it could only be refused. + expect(f.deps.scheduleBoundedRetryForRun).not.toHaveBeenCalled(); + const events = await db.select().from(heartbeatRunEvents).where(and(eq(heartbeatRunEvents.runId, run.id), + eq(heartbeatRunEvents.eventType, "error"))); + expect(events.map(event => event.message)).toEqual([expected]); + }); + + it.each([ + ["run", "not scheduled"], ["setup", "not scheduled"], ["run", "scheduling failed"], ["setup", "scheduling failed"], + ] as const)("withdraws the storage retry promise when no storage wait could be scheduled (%s, %s)", async (phase, mode) => { + const f = await fixture(); + const outage = await withS3FailureDiagnostics("put_object", async () => { + throw Object.assign(new Error("Injected storage outage"), { name: "ServiceUnavailable", $metadata: { httpStatusCode: 503 } }); + }).catch(error => error as Error); + if (mode === "not scheduled") f.deps.scheduleBoundedRetryForRun.mockResolvedValueOnce({ outcome: "not_scheduled", + reason: "Scheduled retry suppressed because the agent is not invokable", errorCode: "agent_not_invokable", issueId: null } as never); + else f.deps.scheduleBoundedRetryForRun.mockRejectedValueOnce(new Error("retry write failed")); + if (phase === "setup") await f.completion.failRunSetup(f.setup(outage)); + else await f.completion.failRun(f.failure(outage)); + expect(f.deps.scheduleBoundedRetryForRun).toHaveBeenCalledWith(expect.objectContaining({ id: f.run.id }), f.agent, STORAGE_UNAVAILABLE_RETRY); + expect(await read(f.run.id)).toMatchObject({ status: "failed", errorCode: STORAGE_UNAVAILABLE_CODE, + error: STORAGE_UNAVAILABLE_HELD_MESSAGE }); + const events = await db.select().from(heartbeatRunEvents).where(and(eq(heartbeatRunEvents.runId, f.run.id), + eq(heartbeatRunEvents.eventType, "error"))); + expect(events.map(event => event.message)).toEqual([STORAGE_UNAVAILABLE_HELD_MESSAGE]); + }); + it.each(["execution", "setup"] as const)("names the nested cause of a generic %s failure and keeps SQL text off the board", async phase => { const f = await fixture(); const logged = vi.spyOn(logger, "error"); diff --git a/server/src/services/heartbeat/run-completion.ts b/server/src/services/heartbeat/run-completion.ts index 847d63bda94..08a95dc55a5 100644 --- a/server/src/services/heartbeat/run-completion.ts +++ b/server/src/services/heartbeat/run-completion.ts @@ -24,7 +24,7 @@ import { ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE, findEnvironmentProviderUnavailab import { REPOSITORY_CATALOG_UNAVAILABLE_CODE, findRepositoryCatalogUnavailableError } from "../repository-catalog-unavailable-error.js"; import { findWorkspaceProviderFailure } from "../workspace-provider-failure.js"; import { isRunnerRevisionMismatch, RUNNER_REVISION_MISMATCH_CODE, RUNNER_REVISION_MISMATCH_RETRY } from "../runner-revision-mismatch.js"; -import { isStorageUnavailableError, STORAGE_UNAVAILABLE_CODE, STORAGE_UNAVAILABLE_EXHAUSTED_MESSAGE, STORAGE_UNAVAILABLE_RETRY, storageUnavailableMessage } from "../../storage/storage-unavailable.js"; +import { isStorageUnavailableError, STORAGE_CREDENTIALS_REJECTED_MESSAGE, STORAGE_UNAVAILABLE_CODE, STORAGE_UNAVAILABLE_EXHAUSTED_MESSAGE, STORAGE_UNAVAILABLE_MESSAGE, STORAGE_UNAVAILABLE_RETRY, storageUnavailableHeldMessage, storageUnavailableMessage } from "../../storage/storage-unavailable.js"; import { type RunSessionOutcome, resolveNextSessionState, normalizeUsageTotals, resolveCacheAdjustedCostUsd, resolveLedgerBiller, resolveLedgerCostStatus, normalizeLedgerBillingType } from "./run-state.js"; import { readGitConnectionFailure } from "../git-connection-failure.js"; import { CONFIGURATION_INCOMPLETE_FAILURE_CODE, ConfigurationIncompleteFailure } from "./run-preparation.js"; @@ -38,8 +38,8 @@ import { accountRunCost } from "../run-cost-accounting.js"; import { isConversation, settleConversationTurn } from "../agent-conversations.js"; import { legacyExecutionNeedsReconciliationWithEvidence } from "../legacy-execution-recovery.js"; import { isWorkspaceGitScanError } from "../workspace-git-operation-scheduler.js"; -import { and, eq, isNull, sql } from "drizzle-orm"; -import { heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults } from "@paperclipai/db"; +import { and, eq, inArray, isNull, sql } from "drizzle-orm"; +import { heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults } from "@paperclipai/db"; import { HttpError } from "../../errors.js"; import { logger } from "../../middleware/logger.js"; import { normalizeResponsibleUserDenialCode } from "../responsible-user-denial-run-outcomes.js"; @@ -1255,17 +1255,22 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC const interruptedExactResume = exactResumeCause ? { ...exactResumeCause, originalMessage: redactFailureText(exactResumeCause.originalMessage) } : null; - const message = interruptedExactResume - ? describeRefusedExactResume(interruptedExactResume, thrownMessage) - : isStorageUnavailableError(err) ? storageUnavailableMessage(err) : thrownMessage; + const storageUnavailable = isStorageUnavailableError(err); const failureErrorCode = workspaceValidationFailure?.code ?? configurationIncompleteFailure?.code ?? nonRetryablePreflightFailureCode(err) ?? recordedResponsibleUserDenialCode ?? nativeTerminalFailureCode ?? - (isStorageUnavailableError(err) ? STORAGE_UNAVAILABLE_CODE : null) ?? + (storageUnavailable ? STORAGE_UNAVAILABLE_CODE : null) ?? "adapter_failed"; + // Only a `storage_unavailable` run gets a storage wait. Under any other code + // (for example a native recovery hold that keeps the files without + // replaying an unfinished turn) nothing retries it, so offer Retry instead. + const message = interruptedExactResume + ? describeRefusedExactResume(interruptedExactResume, thrownMessage) + : !storageUnavailable ? thrownMessage + : failureErrorCode === STORAGE_UNAVAILABLE_CODE ? storageUnavailableMessage(err) : storageUnavailableHeldMessage(err); const failureCause = GENERIC_RUN_FAILURE_CODES.has(failureErrorCode) ? thrownFailureCause : null; logger.error({ err: identityRedactor.redact({ message: err instanceof Error ? err.message : String(err), stack: err instanceof Error ? err.stack : undefined }), runId, errorCode: failureErrorCode, failureCause: thrownFailureCause }, "heartbeat execution failed"); @@ -1395,6 +1400,7 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC } await measureRunPhase("completion.summary", () => refreshContinuationSummaryForRun(livenessRun, agent)); if (await pendingCaseHandoffForRun(db, livenessRun.id, livenessRun.companyId)) { + await settleStorageWaitMessage(livenessRun, null, err); await releaseIssueExecutionAndPromote(livenessRun, { suppressImmediateRecovery: true }); await settleAgent(); return; @@ -1411,14 +1417,16 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC return null; }) : null; - if (storageWait?.outcome === "retry_exhausted") await markStorageWaitExhausted(livenessRun); const nativePreDispatchRetry = storageWait === null ? await scheduleNativePreDispatchRetry(livenessRun, agent) : null; + let fallbackRetry: { outcome: string } | null | undefined = nativePreDispatchRetry; if (storageWait?.outcome !== "scheduled" && storageWait?.outcome !== "retry_exhausted" && nativePreDispatchRetry === null) { - await scheduleInteractionContinuationInfrastructureRetryIfEligible( + fallbackRetry = await scheduleInteractionContinuationInfrastructureRetryIfEligible( livenessRun, agent, ); } + // Another retry that took over after a failed storage wait keeps the promise. + await settleStorageWaitMessage(livenessRun, fallbackRetry?.outcome === "scheduled" ? fallbackRetry : storageWait, err); await releaseIssueExecutionAndPromote(livenessRun, { // Native recovery owns the original heartbeat run through // exhaustion. Once its durable coordinator has classified a @@ -1480,10 +1488,26 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC } } - async function markStorageWaitExhausted(run: typeof heartbeatRuns.$inferSelect) { - await db.update(heartbeatRuns).set({ error: STORAGE_UNAVAILABLE_EXHAUSTED_MESSAGE, updatedAt: new Date() }) + /** + * A `storage_unavailable` failure first promises its storage wait. Keep that + * promise only when the wait was scheduled. An exhausted wait says so; a wait + * that was refused, could not be written, or was preempted by a case handoff + * offers Retry instead, because nothing else will retry the run. + */ + async function settleStorageWaitMessage(run: typeof heartbeatRuns.$inferSelect, + wait: { outcome: string } | null | undefined, cause: unknown) { + if (run.errorCode !== STORAGE_UNAVAILABLE_CODE || wait?.outcome === "scheduled") return; + const error = wait?.outcome === "retry_exhausted" ? STORAGE_UNAVAILABLE_EXHAUSTED_MESSAGE : storageUnavailableHeldMessage(cause); + await db.update(heartbeatRuns).set({ error, updatedAt: new Date() }) .where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.errorCode, STORAGE_UNAVAILABLE_CODE))) - .catch((error: unknown) => logger.warn({ err: error, runId: run.id }, "failed to record an exhausted storage wait")); + .catch((writeError: unknown) => logger.warn({ err: writeError, runId: run.id }, "failed to record why no storage wait follows")); + // The failure's error event was written before the retry decision. Its + // transcript text must not keep a promise that this run no longer makes. + await db.update(heartbeatRunEvents).set({ message: error }) + .where(and(eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id), + eq(heartbeatRunEvents.eventType, "error"), + inArray(heartbeatRunEvents.message, [STORAGE_UNAVAILABLE_MESSAGE, STORAGE_CREDENTIALS_REJECTED_MESSAGE]))) + .catch((writeError: unknown) => logger.warn({ err: writeError, runId: run.id }, "failed to correct the storage failure event")); } async function failRunSetup(input: FailHeartbeatRunSetupInput) { @@ -1501,7 +1525,9 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC const storageUnavailable = isStorageUnavailableError(outerErr); // Bounded code from the error or its first three causes; never message text. const thrownFailureCause = failureCauseFromError(outerErr, providerFailure); - const message = storageUnavailable ? storageUnavailableMessage(outerErr) : withoutSqlStatementText(redactCurrentUserText( + // A lost controller lease takes the code below and its own retry, so only a + // `storage_unavailable` failure carries the storage wait's text. + const message = storageUnavailable && !controllerLeaseLost ? storageUnavailableMessage(outerErr) : withoutSqlStatementText(redactCurrentUserText( identityRedactor.redact(outerErr instanceof Error ? outerErr.message : "Unknown setup failure"), @@ -1709,6 +1735,7 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC failedRun, ).catch(() => failedRun); let storageWaitScheduled = false; + let storageWait: { outcome: string } | null = null; let nativePreDispatchRetryScheduled = false; const setupFailureIssueId = readNonEmptyString( parseObject(livenessRun.contextSnapshot).issueId, @@ -1783,12 +1810,13 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC return null; }); reviewedChatRetryScheduled = retry?.outcome === "scheduled"; - if (livenessRun.errorCode === STORAGE_UNAVAILABLE_CODE && retry?.outcome === "retry_exhausted") await markStorageWaitExhausted(livenessRun); + storageWait = retry; storageWaitScheduled = livenessRun.errorCode === STORAGE_UNAVAILABLE_CODE && (retry?.outcome === "scheduled" || retry?.outcome === "retry_exhausted"); nativePreDispatchRetryScheduled = retry?.outcome === "scheduled" && isNativePreDispatchTransientFailure(livenessRun); } } + await settleStorageWaitMessage(livenessRun, storageWait, outerErr); await releaseIssueExecutionAndPromote(livenessRun, { suppressImmediateRecovery: storageWaitScheduled || nativePreDispatchRetryScheduled || readNonEmptyString( diff --git a/server/src/services/heartbeat/run-lifecycle.test.ts b/server/src/services/heartbeat/run-lifecycle.test.ts index 7efd1c71021..21b3ed744d7 100644 --- a/server/src/services/heartbeat/run-lifecycle.test.ts +++ b/server/src/services/heartbeat/run-lifecycle.test.ts @@ -11,7 +11,9 @@ import { getHeartbeatRunRuntimeStatus } from "../heartbeat-run-runtime-status.js import { createHeartbeatRunState } from "./run-state.js"; import { heartbeatService } from "../heartbeat.js"; import { createHeartbeatRunPreparation } from "./run-preparation.js"; -import { createHeartbeatLifecycle, persistHeartbeatRunProcessMetadata, type HeartbeatLifecycleDependencies } from "./run-lifecycle.js"; +import { createHeartbeatLifecycle, decorateHeartbeatRunRuntimeStatus, persistHeartbeatRunProcessMetadata, type HeartbeatLifecycleDependencies } from "./run-lifecycle.js"; +import { STORAGE_CREDENTIALS_REJECTED_HELD_MESSAGE, STORAGE_CREDENTIALS_REJECTED_MESSAGE, STORAGE_UNAVAILABLE_CODE, + STORAGE_UNAVAILABLE_HELD_MESSAGE, STORAGE_UNAVAILABLE_MESSAGE } from "../../storage/storage-unavailable.js"; import { DELIVERY_QUEUES, subscribeDeliveryWork } from "../delivery-work-notifications.js"; vi.mock("../live-events.js", () => ({ publishLiveEvent: vi.fn() })); @@ -52,6 +54,23 @@ describe("heartbeat lifecycle module boundary", () => { for (const callback of Object.values(deps)) if (vi.isMockFunction(callback)) expect(callback).not.toHaveBeenCalled(); }); + // Rows saved by earlier releases can carry the storage retry promise + // under a code that no storage wait owns. They read truthfully after deploy, + // with no migration; a run a storage wait owns keeps its promise. + it.each([ + ["an outage", STORAGE_UNAVAILABLE_MESSAGE, STORAGE_UNAVAILABLE_HELD_MESSAGE], + ["rejected credentials", STORAGE_CREDENTIALS_REJECTED_MESSAGE, STORAGE_CREDENTIALS_REJECTED_HELD_MESSAGE], + ])("reads a previously saved storage retry promise under native recovery truthfully (%s)", (_label, saved, expected) => { + const held = decorateHeartbeatRunRuntimeStatus({ id: "held-native-run", status: "failed", + errorCode: "native_continuation_requires_reconciliation", error: saved }); + expect(held.error).toBe(expected); + const waiting = decorateHeartbeatRunRuntimeStatus({ id: "run-with-storage-wait", status: "failed", + errorCode: STORAGE_UNAVAILABLE_CODE, error: saved }); + expect(waiting.error).toBe(saved); + const other = decorateHeartbeatRunRuntimeStatus({ id: "other", status: "failed", errorCode: "adapter_failed", error: "Adapter failed" }); + expect(other.error).toBe("Adapter failed"); + }); + it("ignores absent wake requests without accessing the database", async () => { const database = guardedDatabase(); const lifecycle = createHeartbeatLifecycle(database.db, callbacks(database.db)); diff --git a/server/src/services/heartbeat/run-lifecycle.ts b/server/src/services/heartbeat/run-lifecycle.ts index 7c6189b3863..da232abd907 100644 --- a/server/src/services/heartbeat/run-lifecycle.ts +++ b/server/src/services/heartbeat/run-lifecycle.ts @@ -208,6 +208,7 @@ import type { recoveryService } from "../recovery/index.js"; import type { companySkillService } from "../company-skills.js"; import type { budgetService, BudgetServiceHooks } from "../budgets.js"; import type { issueTreeControlService } from "../issue-tree-control.js"; +import { presentStorageFailureMessage } from "../../storage/storage-unavailable.js"; type HeartbeatRun = typeof heartbeatRuns.$inferSelect; @@ -369,6 +370,8 @@ export function decorateHeartbeatRunRuntimeStatus< return { ...run, + // Saved runs from earlier releases may promise a storage retry no wait owns. + ...("error" in run ? { error: presentStorageFailureMessage(run as { error?: string | null; errorCode?: string | null }) } : {}), currentStatusMessage: currentStatus?.message ?? null, currentStatusUpdatedAt: currentStatus?.updatedAt ?? null, currentToolName: currentStatus?.currentToolName ?? null, diff --git a/server/src/services/heartbeat/run-state.test.ts b/server/src/services/heartbeat/run-state.test.ts index 956da72b4ce..e3d78e5208b 100644 --- a/server/src/services/heartbeat/run-state.test.ts +++ b/server/src/services/heartbeat/run-state.test.ts @@ -21,6 +21,7 @@ import * as legacy from "../heartbeat.js"; import * as extracted from "./run-state.js"; import { readRunCancellation } from "../run-cancellation.js"; import { decideQueuedCommentQueueSteering } from "../issue-queued-comment-queue.js"; +import { STORAGE_UNAVAILABLE_CODE, STORAGE_UNAVAILABLE_HELD_MESSAGE, STORAGE_UNAVAILABLE_MESSAGE } from "../../storage/storage-unavailable.js"; // SQL_ASCII needs a separate database cluster. Inspect its selected SQL here; // the PostgreSQL tests below exercise the session queries and transactions. @@ -397,6 +398,19 @@ describePostgres("heartbeat run state database wiring", () => { expect(await state.listRuns(companyId, foreign.agent.id)).toEqual([]); }); + it("lists a previously saved storage retry promise under native recovery truthfully", async () => { + const { companyId, agent, state } = await fixture(); + const [held] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, status: "failed", + errorCode: "native_continuation_requires_reconciliation", error: STORAGE_UNAVAILABLE_MESSAGE }).returning(); + const [waiting] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, status: "failed", + errorCode: STORAGE_UNAVAILABLE_CODE, error: STORAGE_UNAVAILABLE_MESSAGE }).returning(); + for (const summary of [false, true]) { + const rows = await state.listRuns(companyId, agent.id, 100, { summary }); + expect(rows.find(row => row.id === held.id)?.error).toBe(STORAGE_UNAVAILABLE_HELD_MESSAGE); + expect(rows.find(row => row.id === waiting.id)?.error).toBe(STORAGE_UNAVAILABLE_MESSAGE); + } + }); + it("preserves legacy context text, native issue precedence and summary privacy", async () => { const { companyId, agent, issue, state } = await fixture(); const contexts: unknown[] = [null, [], "legacy", 3, true, {}, { diff --git a/server/src/services/heartbeat/run-state.ts b/server/src/services/heartbeat/run-state.ts index 3150bff2e5e..9a0d3c04f65 100644 --- a/server/src/services/heartbeat/run-state.ts +++ b/server/src/services/heartbeat/run-state.ts @@ -57,6 +57,7 @@ import { import { isUuidLike } from "@paperclipai/shared"; import { HEARTBEAT_RUN_LIST_DEFAULT_LIMIT, HEARTBEAT_RUN_LIST_MAX_LIMIT } from "@paperclipai/shared"; import { isUnsafeSessionWorkspaceCwd } from "../session-workspace-cwd.js"; +import { presentStorageFailureMessage } from "../../storage/storage-unavailable.js"; export const EXECUTION_REVIEW_PARTICIPANT_RECOVERY_WAKE_REASON = "execution_review_participant_recovery"; @@ -1868,6 +1869,8 @@ export function createHeartbeatRunState(db: Db) { return { ...rest, + // Saved runs from earlier releases may promise a storage retry no wait owns. + ...("error" in rest ? { error: presentStorageFailureMessage(rest) ?? null } : {}), contextSnapshot: summarizeHeartbeatRunContextSnapshot({ issueId: contextIssueId, taskId: contextTaskId, diff --git a/server/src/storage/storage-unavailable.ts b/server/src/storage/storage-unavailable.ts index 2772bf7701e..111cc0649fc 100644 --- a/server/src/storage/storage-unavailable.ts +++ b/server/src/storage/storage-unavailable.ts @@ -11,6 +11,13 @@ export const STORAGE_UNAVAILABLE_MESSAGE = "File storage was unavailable, so thi export const STORAGE_CREDENTIALS_REJECTED_MESSAGE = "File storage rejected Paperclip's storage credentials (they may have expired or been rotated), so this attempt stopped before it could save its work. Paperclip will retry automatically when valid credentials are available."; +/** For a storage failure that no storage wait owns, such as a run whose native + * recovery keeps its files without replaying an unfinished turn. Nothing + * retries it automatically, so the text offers Retry instead of promising one. */ +export const STORAGE_UNAVAILABLE_HELD_MESSAGE = "File storage was unavailable, so this attempt stopped before it could save its work. Paperclip is not retrying it automatically. Retry or send a message to continue."; + +export const STORAGE_CREDENTIALS_REJECTED_HELD_MESSAGE = "File storage rejected Paperclip's storage credentials (they may have expired or been rotated), so this attempt stopped before it could save its work. Paperclip is not retrying it automatically. Retry or send a message to continue."; + export const STORAGE_UNAVAILABLE_EXHAUSTED_MESSAGE = "File storage stayed unavailable or kept rejecting Paperclip's storage credentials through every automatic retry, so Paperclip stopped retrying this task. Check the storage service and its credentials, then Retry."; export const STORAGE_UNAVAILABLE_RETRY = { @@ -66,6 +73,24 @@ export function storageUnavailableMessage(error: unknown): string { return isStorageCredentialRejection(error) ? STORAGE_CREDENTIALS_REJECTED_MESSAGE : STORAGE_UNAVAILABLE_MESSAGE; } +/** The text for a storage failure that no storage wait owns. */ +export function storageUnavailableHeldMessage(error: unknown): string { + return isStorageCredentialRejection(error) ? STORAGE_CREDENTIALS_REJECTED_HELD_MESSAGE : STORAGE_UNAVAILABLE_HELD_MESSAGE; +} + +/** + * Only a run recorded as `storage_unavailable` has a storage wait. Releases + * before this check could save the retry promise under another code (a + * native recovery hold), where nothing retries. Reads present those rows with + * the held text, so they are truthful after deploy without a migration. + */ +export function presentStorageFailureMessage(run: { error?: string | null; errorCode?: string | null }): string | null | undefined { + if (run.errorCode === STORAGE_UNAVAILABLE_CODE) return run.error; + if (run.error === STORAGE_UNAVAILABLE_MESSAGE) return STORAGE_UNAVAILABLE_HELD_MESSAGE; + if (run.error === STORAGE_CREDENTIALS_REJECTED_MESSAGE) return STORAGE_CREDENTIALS_REJECTED_HELD_MESSAGE; + return run.error; +} + export function isStorageUnavailableError(error: unknown): boolean { const recorded = recordedStorageFailure(error); if (!recorded) return false; From 6e524d8a69a5bd70ac458e329726da328d5aa926 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:31:33 -0600 Subject: [PATCH 10/38] fix(workspaces): stop retrying a copy-back that hit a full sandbox disk (#20678) 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 > - After a native run, Paperclip copies the agent's sandbox workspace back to durable storage. This is finalization. > - The copy-back builds an archive inside the sandbox. When the sandbox disk is full, the copy-back fails with `remote_workspace_sandbox_disk_full`. > - Finalization treated that failure as transient. It retried three times. Each attempt took about 15 minutes for a large workspace, and nothing freed space between attempts. > - Saved-work recovery already reclaims the retained sandbox's inactive provider cache when a save hits a full disk. It runs only after finalization ends. > - This pull request ends finalization on the first full-disk copy-back failure, with the accepted result kept, so saved-work recovery starts at once. > - The benefit is that the task gets its files saved sooner, and the user sees what happened instead of "failed after 3 attempts". ## Linked Issues or Issue Description Refs #19619 (related: records why the read-only capture fallback failed; this PR does not change that path) **What happened?** On staging, a native run finished its turn and its result was accepted. The workspace copy-back then failed three times with `remote_workspace_sandbox_disk_full` (about 7.5 GB of workspace, about 6 GB free). The three attempts spanned about one hour across deploys. Finalization then ended as `native_workspace_sync_out_retry_exhausted`. Saved-work recovery reclaimed the inactive provider cache (about 3 GB freed) and saved the files. **Expected behavior** A full sandbox disk is recognised on the first failure. Paperclip does not spend the finalization budget on attempts that cannot succeed. The agent's result is kept. The user sees that the disk is full and that Paperclip saves the files again without another provider turn. **Steps to reproduce** 1. Run a native task on a remote sandbox whose workspace is larger than the free sandbox space. 2. Let the provider turn finish. 3. Observe three copy-back attempts that each fail with `remote_workspace_sandbox_disk_full`. ## What Changed - `recordRetryableFailure` treats a workspace failure whose cause starts with `remote_workspace_sandbox_disk_full:` as an exhausted budget on the first attempt. The code stays `native_workspace_sync_out_retry_exhausted`, so the existing export hold, saved-work recovery, and export Retry apply unchanged. - The run error for that case says that the sandbox disk is full and that Paperclip saves the files again without repeating the agent's work. It no longer says "after 3 attempts". - Other copy-back failures keep their bounded retry. - `captureRemoteWorkspaceArchive` rethrows the read-only fallback's own failure when that fallback only lost its connection (`transport_closed`, `provider_unavailable`, `provider_rate_limited`, `sandbox_state_transition`). That failure is not disk-full, so finalization keeps its bounded retry for it. Other fallback failures keep the disk-full code. - `remoteWorkspaceFailureCause` records the server-built read-only capture failure, so a failed save names where the fallback stopped. - The transport exports `REMOTE_WORKSPACE_SANDBOX_DISK_FULL_CODE`. The finalizer and tests use it. - `doc/execution-semantics.md` describes the new rule. ## Verification - `cd server && npx vitest run src/services/native-runtime/native-run-finalizer-telemetry.test.ts src/services/remote-workspace-transport.test.ts` (195 pass). - New test "hands a full sandbox disk to saved-work recovery on the first copy-back failure" fails on `origin/master` (the failure stays `retryable_failure`) and passes with this change. It completes an accepted result first and checks that the result stays linked and that no agent wakeup is created. - New transport test "keeps a full disk only when the read-only fallback did not just lose its connection": the two dropped-connection cases fail on `origin/master` and pass with this change. - New test "keeps other copy-back failures on their bounded retry" passes before and after. - `cd server && npx tsc --noEmit` passes. `pnpm verify` selected 2504 test files because the finalizer is widely imported; its first selected batch passed, and required CI supplies the full run. ## Risks - Low risk. The terminal state is the same state that three failed attempts produce today. Only the timing changes. - A sandbox whose disk frees space by itself between attempts now waits for saved-work recovery instead of the next finalizer attempt. Saved-work recovery repeats the save with its own bounded attempts, so this does not lose work. - Upgrade safety: a run saved by an older release in `retryable_failure` with this cause ends on its next full-disk failure. No migration is needed. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell, file edits) in Claude Code. Extended reasoning was not configured. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- doc/execution-semantics.md | 10 +++- .../native-run-finalizer-telemetry.test.ts | 47 +++++++++++++++++++ .../native-runtime/native-run-finalizer.ts | 17 +++++++ .../remote-workspace-transport.test.ts | 23 +++++++++ .../services/remote-workspace-transport.ts | 23 ++++++++- 5 files changed, 117 insertions(+), 3 deletions(-) diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index aaf5361224e..a454d073ee1 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -4565,7 +4565,15 @@ That transfer can stream without another sandbox archive. Provider exclusions ca also omit a nested entry with the same name; credentials remain excluded. Other copy failures and timeouts still fail. Workspace capture itself still needs free sandbox space. Its failed save operation names `remote_workspace_sandbox_disk_full` -when that capacity is exhausted, without changing retry or ownership rules. +when that capacity is exhausted, without changing ownership rules. Finalization +does not retry that copy-back: nothing frees the sandbox between its attempts. +The first full-disk failure ends finalization as +`native_workspace_sync_out_retry_exhausted` and keeps the accepted result. Saved-work +recovery then reclaims the retained sandbox's inactive provider cache and saves the +files again with no provider turn. The export Retry stays available. A read-only +fallback that only lost its connection (a closed transport, a provider 5xx or rate +limit, or a sandbox state change) reports its own cause instead, and finalization +keeps its bounded retry for it. Native assigned app tools save governed responses above 500,000 encoded bytes before returning a bounded reference through PRP. `read_tool_result` retrieves the saved JSON in diff --git a/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts b/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts index 7ec2ea198b1..213fae33bf7 100644 --- a/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts +++ b/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts @@ -66,6 +66,7 @@ import { restoreNativeWorkspaceBestEffort } from "./native-workspace-best-effort import { reconcileNativeFinalizations } from "./native-finalization-reconciler.js"; import { recoverLegacyUnsafeWorkspaceExports } from "./native-workspace-export-recovery.js"; import { finalizeNativeRun, recordNativeFinalizationFailure } from "./native-run-finalizer.js"; +import { REMOTE_WORKSPACE_SANDBOX_DISK_FULL } from "../remote-workspace-transport.js"; import { waitForPendingRunFailureReports } from "../run-failure-report.js"; import { deliverExecutionStatuses } from "../execution-status-delivery.js"; import { commitNativeStatusDecision } from "./status-decision-committer.js"; @@ -902,6 +903,52 @@ describeEmbeddedPostgres("native run finalizer / status decision committer — a expect(run?.error).toMatch(/recovery action/); }); + it("hands a full sandbox disk to saved-work recovery on the first copy-back failure", async () => { + // PAP-4253: three copy-back attempts each hit the same full disk (about 15 + // minutes apiece across deploys). Nothing frees the sandbox between them; + // saved-work recovery reclaims the inactive provider cache, then saves. + const fixture = await seedNativeRun(); + await driveToCompleteResult(fixture); + const [accepted] = await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, fixture.runId)); + expect(accepted).toBeDefined(); + const wakeupsBefore = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests) + .where(eq(agentWakeupRequests.agentId, agentId)); + const failure = await recordNativeFinalizationFailure({ + db, runId: fixture.runId, error: new Error("native_workspace_sync_out_failed"), + projectRunStatus: true, failureScope: "workspace", failureCause: REMOTE_WORKSPACE_SANDBOX_DISK_FULL, + }); + expect(failure).toMatchObject({ phase: "terminal_failure", failureCode: "native_workspace_sync_out_retry_exhausted", + nextAttemptAt: null }); + const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, fixture.runId)); + expect(coordinator.failureDetail).toMatchObject({ recoveryOwner: { kind: "board" }, workspaceFinalizeAttempt: 1, + failureCause: REMOTE_WORKSPACE_SANDBOX_DISK_FULL }); + // The accepted result stays linked for the export recovery. + expect(coordinator.resultId).toBe(accepted.id); + expect(await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, fixture.runId))).toEqual([accepted]); + const run = await readRunError(fixture.runId); + expect(run).toMatchObject({ status: "failed", errorCode: "native_workspace_sync_out_retry_exhausted" }); + expect(run?.error).toMatch(/sandbox disk is full/); + expect(run?.error).not.toMatch(/after 3 attempts/); + // The export hold owns the next step; no provider turn is requested. + expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, fixture.issueId))) + .toEqual([expect.objectContaining({ status: "active", ownerType: "board", cause: "native_workspace_sync_out_retry_exhausted" })]); + expect(await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests) + .where(eq(agentWakeupRequests.agentId, agentId))).toEqual(wakeupsBefore); + }); + + it("keeps other copy-back failures on their bounded retry", async () => { + const fixture = await seedNativeRun(); + await db.insert(nativeRunFinalizations).values({ + runId: fixture.runId, companyId, issueId: fixture.issueId, phase: "observed", attempt: 1, + }); + const failure = await recordNativeFinalizationFailure({ + db, runId: fixture.runId, error: new Error("native_workspace_sync_out_failed"), + projectRunStatus: true, failureScope: "workspace", + failureCause: "remote_workspace_capture_failed: stage=archive code=ECONNRESET", + }); + expect(failure).toMatchObject({ phase: "retryable_failure", failureCode: "native_workspace_sync_out_failed" }); + }); + it("does not attach a finalization error to a provider-succeeded run when provider retries are exhausted", async () => { const fixture = await seedNativeRun(); await db.update(heartbeatRuns).set({ resultJson: { prpRunTerminalState: "succeeded", finalizationFailureCount: 2 } }) diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index a29e848e59c..74e5b1faf37 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -1,5 +1,6 @@ import { notifyNativeEnvironmentSettlement } from "../native-environment-settlement-notifications.js"; import { isContextCompactionRun } from "../context-compaction.js"; +import { REMOTE_WORKSPACE_SANDBOX_DISK_FULL_CODE } from "../remote-workspace-transport.js"; import { notifyExternalAgentSettlement } from "../../modules/external-agents/index.js"; import { notifyNativeRecoveryNotices } from "../native-recovery-notice-notifications.js"; import { resolveCommittedNativeRecoveryNotices } from "./native-recovery-notices.js"; @@ -309,6 +310,11 @@ export function readWorkspaceFailureCause(value: unknown): string | null { function terminalFinalizationFailureMessage(failureCode: string, failureScope: "provider" | "workspace" | undefined, failureCause?: string | null) { + if (failureCode === "native_workspace_sync_out_retry_exhausted" && isSandboxStorageExhausted(failureCause)) { + return "Saving the workspace stopped because the sandbox disk is full. The agent's result is kept, and Paperclip " + + "saves the files again from the retained sandbox without repeating the agent's work; follow the run's recovery " + + `action if that cannot free enough space. Last cause: ${failureCause}`; + } if (failureCode === "native_workspace_sync_out_retry_exhausted") { // This code also covers local-directory and plugin workspaces, so the // message stays general and defers to the recovery action's next step. @@ -326,6 +332,16 @@ function terminalFinalizationFailureMessage(failureCode: string, failureScope: " : `Native run finalization failed (${failureCode}).`; } +/** + * A full sandbox disk stops every copy-back the same way: the archive is built + * in that sandbox, and nothing frees space between finalizer attempts. It is + * recognised on the first failure and handed to saved-work recovery, which can + * reclaim the retained sandbox's inactive provider cache before saving again. + */ +function isSandboxStorageExhausted(failureCause: string | null | undefined) { + return typeof failureCause === "string" && failureCause.startsWith(`${REMOTE_WORKSPACE_SANDBOX_DISK_FULL_CODE}:`); +} + const NATIVE_FINALIZATION_RETRY_LIMIT = 3; /** * Contention while applying a saved, accepted, provider-succeeded result is @@ -476,6 +492,7 @@ async function recordRetryableFailure(input: { : readFinalizationFailureCount(input.run.resultJson) + 1; const budgetExhausted = input.permanent === true || + (input.failureScope === "workspace" && isSandboxStorageExhausted(failureCause)) || (workspaceFinalizeAttempt !== null ? workspaceFinalizeAttempt >= 3 : finalizationFailureCount! >= NATIVE_FINALIZATION_RETRY_LIMIT); diff --git a/server/src/services/remote-workspace-transport.test.ts b/server/src/services/remote-workspace-transport.test.ts index 945dbcbcc37..1c46c97259e 100644 --- a/server/src/services/remote-workspace-transport.test.ts +++ b/server/src/services/remote-workspace-transport.test.ts @@ -16,6 +16,7 @@ import { prepareRemoteRepository, prepareRemoteWorkspaceDirectory, remoteWorkspaceFailureCause, + REMOTE_WORKSPACE_SANDBOX_DISK_FULL, removeRemoteRecoveryAttachment, restoreRemoteWorkspaceDirectory, type RemoteWorkspaceTarget, @@ -1056,6 +1057,28 @@ fs.unlinkSync(${JSON.stringify(kill)});process.kill(process.pid,'SIGKILL');}retu } }); + it.each([ + ["socket hang up", "transport_closed", true], + ["503 service unavailable", "provider_unavailable", true], + ["synthetic transfer unavailable", "provider_error", false], + ] as const)("keeps a full disk only when the read-only fallback did not just lose its connection (%s)", async (thrown, label, transient) => { + await fs.writeFile(path.join(workspace, "saved.txt"), "retained work\n"); + const { remote, execute } = target(); + execute.mockResolvedValueOnce({ exitCode: 1, stdout: "", stderr: REMOTE_WORKSPACE_SANDBOX_DISK_FULL, + timedOut: false, signal: null, pid: process.pid, startedAt: new Date().toISOString() }); + remote.runner!.syncOut = async () => { throw new Error(thrown); }; + const failure = await captureRemoteWorkspaceArchive({ target: remote, remoteCwd: workspace, operationId: randomUUID() }) + .then(() => { throw new Error("expected the capture to fail"); }, (error: Error) => error); + const fallback = `remote_workspace_readonly_capture_failed: stage=transfer reason=operation_failed transport=${label}`; + // Finalization retries a dropped connection; a full disk goes straight to saved-work recovery. + if (transient) { + expect(failure.message).toBe(fallback); + // The save records where the fallback stopped. + expect(remoteWorkspaceFailureCause(failure)).toBe(fallback); + } else expect(failure).toMatchObject({ message: REMOTE_WORKSPACE_SANDBOX_DISK_FULL, cause: { message: fallback } }); + expect(await fs.readFile(path.join(workspace, "saved.txt"), "utf8")).toBe("retained work\n"); + }); + it.each(["source changed", "copy changed", "extra file"])("rejects a read-only fallback when %s", async fault => { await fs.writeFile(path.join(workspace, "saved.txt"), "retained work\n"); const { remote, execute } = target(); diff --git a/server/src/services/remote-workspace-transport.ts b/server/src/services/remote-workspace-transport.ts index 75248a2cf38..42ecdfd82bd 100644 --- a/server/src/services/remote-workspace-transport.ts +++ b/server/src/services/remote-workspace-transport.ts @@ -37,8 +37,9 @@ export function requireRemoteWorkspaceTarget(target: AdapterExecutionTarget | nu } /** The workspace archive is built inside the sandbox, so a full sandbox disk stops the save. */ +export const REMOTE_WORKSPACE_SANDBOX_DISK_FULL_CODE = "remote_workspace_sandbox_disk_full"; export const REMOTE_WORKSPACE_SANDBOX_DISK_FULL = - "remote_workspace_sandbox_disk_full: the sandbox disk is full; free space in the sandbox before saving the workspace"; + `${REMOTE_WORKSPACE_SANDBOX_DISK_FULL_CODE}: the sandbox disk is full; free space in the sandbox before saving the workspace`; // Node reports ENOSPC or EDQUOT. Git and tar child processes report the text. const DISK_FULL_CHECK = String.raw`const diskFull=e=>['ENOSPC','EDQUOT'].includes(e?.code)||/No space left on device|Disk quota exceeded/i.test(String(e?.stderr??'')+String(e?.message??''));`; const CAPTURE_FAILURE_CHECK = `const captureFailure=${remoteWorkspaceCaptureFailureMessage.toString()};const failureDetail=${remoteWorkspaceFailureDetail.toString()};`; @@ -88,11 +89,16 @@ export class RemoteWorkspaceOperationError extends Error { * The server-built diagnostic for a remote workspace failure, or null when the * error text is not one of these redacted forms and must stay off the record. */ +const READONLY_CAPTURE_FAILURE_CAUSE = + /^remote_workspace_readonly_capture_failed: stage=(?:inspect|transfer|verify|archive) reason=[a-z_]{1,32} transport=[a-z_]{1,48}(?: code=[A-Z][A-Z0-9_]{1,31})?$/; + export function remoteWorkspaceFailureCause(error: unknown): string | null { if (error instanceof RemoteWorkspaceOperationError || error instanceof RemoteWorkspaceOperationTimeoutError || error instanceof RemoteWorkspaceRestoreError) return error.message; if (!(error instanceof Error)) return null; if (remoteWorkspaceCaptureFailureMessage({ message: error.message }) === error.message) return error.message; + // A read-only capture failure is server-built from closed fields. + if (READONLY_CAPTURE_FAILURE_CAUSE.test(error.message)) return error.message; const operation = providerRefusals.get(error); return operation ? remoteWorkspaceProviderRefusalCause(operation, error) : null; } @@ -487,10 +493,23 @@ export async function captureRemoteWorkspaceArchive(input: { // it, then normalize and seal it on the controller. Failed verification // retains the original disk-full failure and never permits source cleanup. try { return await captureReadOnlyWorkspaceArchive(input); } - catch (cause) { throw new Error(error.message, { cause }); } + catch (cause) { + // The read-only copy writes nothing to the sandbox. When only its + // connection dropped, a later copy-back can succeed, so finalization + // keeps its bounded retry. Any other fallback failure keeps the + // disk-full code, which finalization does not retry. + if (isTransientReadOnlyCaptureFailure(cause)) throw cause; + throw new Error(error.message, { cause }); + } } } +const TRANSIENT_READONLY_CAPTURE_FAILURE = + /^remote_workspace_readonly_capture_failed: stage=[a-z]+ reason=operation_failed transport=(?:transport_closed|provider_unavailable|provider_rate_limited|sandbox_state_transition)(?: |$)/; +function isTransientReadOnlyCaptureFailure(error: unknown) { + return error instanceof Error && TRANSIENT_READONLY_CAPTURE_FAILURE.test(error.message); +} + /** Captures a sandbox directory without writing to the sandbox. The copy is * verified against an inventory taken before and after the transfer. */ export async function captureReadOnlyWorkspaceArchive(input: { From 7435abcc63355e504f9f89ac78e1c66eaf5b12db Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:39:42 -0600 Subject: [PATCH 11/38] fix(native): wait out a run-event append before saving provider-pack admission (#20682) 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. > - A native OpenCode run in a remote sandbox records a provider-pack admission receipt on its run row after the provider session opens. Artifact retention then requires that receipt. > - `recordNativeProviderPackAdmission` locked the run row with `FOR UPDATE NOWAIT`. > - A run-event append locks the same run row for a few milliseconds (`FOR NO KEY UPDATE` since #20670, `FOR UPDATE` before). Both conflict with `FOR UPDATE`. Startup appends many events at the same moment. > - When the two met, the admission write failed with `55P03`. The admission state stayed `pending`. Artifact retention then failed the run with `native_provider_artifacts_admission_unverified`. The task stopped as "Recovery needed" with no Retry. > - This pull request makes the admission write wait for the run-row lock within the existing 1000 ms `lock_timeout`. The coordinator claim keeps its `NOWAIT` fence. > - The benefit is that an ordinary concurrent event append no longer fails a healthy run before its first turn. ## Linked Issues or Issue Description Refs #20670 (changed the append lock mode; the conflict with `FOR UPDATE NOWAIT` remains). **What happened?** On a hosted staging instance, three OpenCode runs on remote sandboxes failed in the first minute with `native_provider_artifacts_admission_unverified`. Each run log shows `native provider-pack admission receipt could not be saved` about 0.2–0.7 s after the runner authenticated. The run profile kept `nativeProviderPackAdmissionState.state = "pending"`. The tasks stayed blocked. **Steps to reproduce** 1. Start a native run and hold its `heartbeat_runs` row lock in another transaction, as a run-event append does. 2. Call `recordNativeProviderPackAdmission` for that run. 3. Observe `could not obtain lock on row in relation "heartbeat_runs"` (`55P03`). **Expected behavior** The admission waits a short, bounded time for the append to commit, then saves the receipt. ## What Changed - `recordNativeProviderPackAdmission` sets `lock_timeout = 1000ms` for every call, not only `waitForClaim` calls. - The run-row lock is now `FOR UPDATE` without `NOWAIT`, so it waits for a concurrent append within that bound. - The coordinator (`native_run_finalizations`) lock keeps `NOWAIT` when the caller does not wait for the claim. The existing fence tests still pass. - New PostgreSQL test: `waits for a concurrent run-event append's run-row lock instead of losing the admission` (both `waitForClaim` modes). ## Verification - RED on `origin/master` (`c444da7d05`): the new test fails with `55P03` in both modes. - GREEN with this change: `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-provider-pack-admission.test.ts` (37 passed). - `pnpm --filter @paperclipai/server typecheck` passes. - `pnpm verify`: see the result below. ## Risks - Low risk. The normal path has no contention and does not wait. Under contention the admission waits at most 1000 ms, before any provider turn. - A lock wait between the coordinator row and the run row can now meet a deadlock. PostgreSQL detects it and raises an error. That error takes the same caught path as the earlier `55P03`, so the result is no worse than before. > 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, read-only staging API reads). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- .../native-provider-pack-admission.test.ts | 31 +++++++++++++++++++ .../native-provider-pack-admission.ts | 7 +++-- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/server/src/services/native-runtime/native-provider-pack-admission.test.ts b/server/src/services/native-runtime/native-provider-pack-admission.test.ts index 5d5af36841e..8ac60525f12 100644 --- a/server/src/services/native-runtime/native-provider-pack-admission.test.ts +++ b/server/src/services/native-runtime/native-provider-pack-admission.test.ts @@ -226,6 +226,37 @@ describe("provider pack admission PostgreSQL fencing", () => { } finally { release(); await owner; } await expect(recordNativeProviderPackAdmission(db, f)).resolves.toBe(true); }); + it.each([false, true])("waits for a concurrent run-event append's run-row lock instead of losing the admission (waitForClaim: %s)", async waitForClaim => { + // Staging failure: a run-event append locks the run row + // (FOR NO KEY UPDATE, as appendHeartbeatRunEvent does) for milliseconds. A + // NOWAIT admission write failed, left the state pending, and artifact + // retention then failed the run as native_provider_artifacts_admission_unverified. + const f = await fixture(); + let release!: () => void, acquired!: () => void; + const holding = new Promise(resolve => { acquired = resolve; }); + const gate = new Promise(resolve => { release = resolve; }); + const append = db.transaction(async tx => { + await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(eq(heartbeatRuns.id, f.identity.runId)).for("no key update"); + acquired(); await gate; + }); + await holding; + let settled = false; + const recording = recordNativeProviderPackAdmission(db, { ...f, waitForClaim } as Parameters[1]) + .then(value => { settled = true; return { value }; }, error => { settled = true; return { error }; }); + try { + // Release only after the admission is proven to wait on the run row, so + // the old NOWAIT code cannot pass by running after the append commits. + await vi.waitFor(async () => { + const [row] = await db.execute<{ waiting: boolean }>(sql`select exists(select 1 from pg_stat_activity + where datname = current_database() and wait_event_type = 'Lock' and state = 'active' + and query like '%heartbeat_runs%') as waiting`); + expect(settled || row.waiting).toBe(true); + }, { timeout: 800 }); + } finally { release(); await append; } + expect(await recording).toEqual({ value: true }); + expect((await read(f.identity.runId)).runnerProfileJson?.nativeProviderPackAdmissionState) + .toEqual({ ...f.profile.nativeProviderPackAdmissionState, state: "verified" }); + }); it.each([false, true])("waits within the durable-capture bound and rechecks the claim after its lock (revoked: %s)", async revoked => { const f = await fixture(); let release!: () => void, acquired!: () => void; diff --git a/server/src/services/native-runtime/native-provider-pack-admission.ts b/server/src/services/native-runtime/native-provider-pack-admission.ts index 8476f852b10..d815e427f63 100644 --- a/server/src/services/native-runtime/native-provider-pack-admission.ts +++ b/server/src/services/native-runtime/native-provider-pack-admission.ts @@ -132,8 +132,11 @@ export async function recordNativeProviderPackAdmission(db: Db, input: { }): Promise { const receipt = admittedNativeProviderPack(input.session, input.identity); return db.transaction(async tx => { + // Bounds every lock wait below, including the run-row lock. A run-event + // append holds that row FOR UPDATE for milliseconds; NOWAIT there lost the + // admission and then failed the run as admission_unverified. + await tx.execute(sql`select set_config('lock_timeout', '1000ms', true)`); if (input.waitForClaim) { - await tx.execute(sql`select set_config('lock_timeout', '1000ms', true)`); await assertNativeRunnerCheckpointOwner(tx, { companyId: input.identity.companyId, issueId: input.identity.issueId, runId: input.identity.runId, authorityRunId: input.identity.runId, bootId: input.claim.controllerBootId, leaseOwner: input.claim.leaseOwner, @@ -151,7 +154,7 @@ export async function recordNativeProviderPackAdmission(db: Db, input: { eq(heartbeatRuns.id, input.identity.runId), eq(heartbeatRuns.companyId, input.identity.companyId), eq(heartbeatRuns.agentId, input.identity.agentId), eq(heartbeatRuns.nativeIssueId, input.identity.issueId), eq(heartbeatRuns.runtimeMode, "native"), eq(heartbeatRuns.status, "running"), - )).for("update", { noWait: true }).limit(1); + )).for("update").limit(1); if (!run) return false; const current = run.profile?.nativeProviderPackAdmissionState as Record | undefined; if (current?.schema !== "paperclip.native-provider-pack-admission-state.v1" || current.admissionEpoch !== input.admissionEpoch From 52160eba35b719f528ffd7d9d36472e8a57df190 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:05:17 -0600 Subject: [PATCH 12/38] test(restart-chaos): K15 redeploy, F1 workspace symlink, and the staging failure census (#20679) 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. > - The restart-chaos harness (`tests/restart-chaos/`) restarts the control plane while real agent tasks run. It grades whether every task finishes without a human Retry. > - The hosted staging stack deploys about every 40 minutes. In 48 hours, 276 runs failed and 63 tasks stayed blocked. About a quarter of the failures came within 10 minutes of a deploy. The harness passed the same areas. > - A hosted deploy replaces the server container. The new server runs in another process space and has a new deployment id. The PID-based "the earlier owner exited" proofs never apply across that boundary. A harness restart on one machine keeps the process space, so every PID proof succeeds and the hosted recovery path is never tested. > - This pull request adds K15, a redeploy fault. It also adds the staging census that shows the gap. > - The benefit: chaos waves can now exercise the recovery path that staging runs after every deploy, on local and Daytona. ## Linked Issues or Issue Description **What happened?** Many staging tasks that a deploy crossed ended blocked. Examples are `native_remote_recovery_lease_mismatch`, `runner_remote_process_identity_unavailable`, `prior_owner_terminal_state_indeterminate` and `PRP provider resume state is unavailable`. The restart-chaos Daytona waves passed for the same adapters. **What did you expect?** The chaos harness should reproduce the deploy conditions that staging has, so that these failure classes show up in a wave first. **Steps to reproduce** 1. Compare the staging run records' `controllerProcess.hostHash` and `deployment.deploymentId` across a deploy. Both change on every deploy. 2. Compare the same fields across a harness K2 restart. Both stay the same. 3. Read `controllerProcessExited` and `sameProcessSpace` in `server/src/services/controller-process-identity.ts`. A different `hostHash` means that no PID proof applies. **Additional context** The full census, the failure classes and the per-class harness gaps are in `doc/plans/2026-11-11-staging-failures-vs-chaos-coverage.md`. The task identifiers in it are neutral labels. ## What Changed - New fault `K15` (redeploy), in `tests/restart-chaos/redeploy.ts` and `redeploy-preload.mjs`. A K15 wave gives every server an emulated host name through a `--import` preload, which changes the process-space hash. It also gives Railway-shaped deployment variables with the instance home as the exclusive volume. A K15 stops the server with SIGTERM and starts the next generation, with a new host name and deployment id. - `supervisor.ts`, `main.ts`, `config.ts` and `types.ts`: select K15 with `--faults K15`. It works on `--env local` and `--env daytona`. The receipt records `redeploy` and the timeline records `redeploy_switched`. Config refuses K15 together with MS1–MS3. - New opt-in workload `F1` (`workloads.ts`): the agent keeps an absolute symlink in its repository workspace. A staging save-back refused such a link and blocked the task. The oracle needs `done` and the saved notes file, with no Retry. `f1-symlink.test.ts` covers the prompt, the grading and the option planning. - `redeploy.test.ts`: identity derivation, the environment, the argument order, a real child process that proves the preload changes both CJS and ESM `hostname()`, option parsing and plan detection. - `tests/restart-chaos/README.md`: a K15 section and a row in the "Pieces" table. - `doc/plans/2026-11-11-staging-failures-vs-chaos-coverage.md`: the 48-hour staging census, 12 failure classes, the deploy timeline, the reason the harness missed each class, and proposed scenarios. ## Verification - `pnpm exec vitest run --config tests/restart-chaos/vitest.config.ts tests/restart-chaos/redeploy.test.ts tests/restart-chaos/scheduler.test.ts tests/restart-chaos/repeated-restarts.test.ts`: 68 tests pass. The full restart-chaos unit suite passes: 43 files, 516 tests. - `node scripts/typecheck-test-projects.mjs tests/restart-chaos`: passes. - Live Daytona waves on 8f6ca25976, image `paperclip-daytona-runner@sha256:bc7ca92d…`: | Wave | Faults and cells | Result | | --- | --- | --- | | `w-20261111T002313-s9301` | K15, opencode and claude, A1 and C1, reuse lease, 6 tasks | 5 of 6 pass. t05 (OpenCode, C1) failed R5 `silent_dead_run`: 183 s without evidence after the redeploy, then succeeded. | | `w-20261111T004241-s9301` | K2 control, same seed | 6 of 6 pass | | `w-20261111T005008-s9302` | K15, warm sandbox, comment trigger, 4 tasks | 4 of 4 pass | | `w-20261111T010000-s9303` | K15, opencode only, 8 tasks | 8 of 8 pass | | `w-20261111T011044-s9303` | K2 control, same seed | 8 of 8 pass | | `w-20261111T012523-s9304` | F1 with K2, codex and opencode, `--storage s3` | 2 of 2 pass | - Every K15 fault switched the generation, with a new host name and deployment id on the same volume. The server was ready again in 14–24 s. - K15 does not yet reproduce the staging refusal codes on current master. The census document explains the open conditions, such as a code change at the deploy. ## Risks - Low risk. The change is in the test harness and docs only. No product code changes. - K15 is an emulation. It changes the host name only in the server process (and forked Node children). It does not emulate a new kernel boot or PID namespace. The cloud stop-proof service is not emulated, so stop proofs that need it stay unsupported, as on a self-hosted Railway deploy. The README lists these limits. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use (shell, file edit, GitHub CLI). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- ...1-11-staging-failures-vs-chaos-coverage.md | 309 ++++++++++++++++++ tests/restart-chaos/README.md | 73 ++++- tests/restart-chaos/config.ts | 13 +- tests/restart-chaos/f1-symlink.test.ts | 53 +++ tests/restart-chaos/journeys.ts | 2 +- tests/restart-chaos/main.ts | 5 +- tests/restart-chaos/redeploy-preload.mjs | 12 + tests/restart-chaos/redeploy.test.ts | 93 ++++++ tests/restart-chaos/redeploy.ts | 96 ++++++ tests/restart-chaos/supervisor.ts | 36 +- tests/restart-chaos/types.ts | 9 +- tests/restart-chaos/workloads.ts | 35 ++ 12 files changed, 723 insertions(+), 13 deletions(-) create mode 100644 doc/plans/2026-11-11-staging-failures-vs-chaos-coverage.md create mode 100644 tests/restart-chaos/f1-symlink.test.ts create mode 100644 tests/restart-chaos/redeploy-preload.mjs create mode 100644 tests/restart-chaos/redeploy.test.ts create mode 100644 tests/restart-chaos/redeploy.ts diff --git a/doc/plans/2026-11-11-staging-failures-vs-chaos-coverage.md b/doc/plans/2026-11-11-staging-failures-vs-chaos-coverage.md new file mode 100644 index 00000000000..2550b6ff024 --- /dev/null +++ b/doc/plans/2026-11-11-staging-failures-vs-chaos-coverage.md @@ -0,0 +1,309 @@ +# Staging failures vs chaos-harness coverage (2026-11-09 00:00Z to 2026-11-11 00:05Z) + +Question from Dotta: what failed on `paperclip.staging.paperclip.app` in the last 48 hours, why +did the restart-chaos harness (`tests/restart-chaos/`) not find it first, and what must the harness +add so it would. + +## Answer first + +1. **276 runs failed, were cancelled or were interrupted in 48 hours, across 114 tasks.** At census + time, 63 of those tasks (55%) were still `blocked`. +2. **Staging is a continuous deploy target.** There were 47 server process starts in 48 hours. 45 of + them were new Railway deployments: about one deploy every 40 minutes in working hours. Each deploy + replaces the container, so the new server runs in a **different process space** (host, kernel boot + and PID namespace) with **newer code**. Remote Daytona sandboxes keep the previous runner. +3. **The harness restarts the same build on the same Mac, at once.** A harness restart keeps the + process space and has no deployment identity. It is back in seconds. A staging deploy has three + differences: + - it sends a graceful SIGTERM, often 1–3 s after a native coordinator claim; + - the server stays down for 4–7 minutes; + - it has a new deployment identity. + + Native recovery uses the deployment proof (`proveOwnerGone`, `deployment_replaced`), not PID + proofs. So the process space matters less than first assumed. This was corrected after review. + The open gap is the long, mid-turn outage, during which the remote Runner is lost (class R + below). The harness passed D1 8/8 and D5 6/6 on master while staging blocked tasks. +4. **The Daytona matrix does not use the staging workload mix.** Staging runs OpenCode in 66% of + native runs (1266 of 1917), uses reusable sandboxes (saved epochs up to 5), runs 25 agents and has + long-lived parent/child task trees. The Daytona matrix runs only `codex,claude` on fresh + per-run sandboxes, one task tree deep, with waves shorter than one hour. +5. **The harness never builds old saved state.** In the largest class by count, automatic wakes + failed 99 times in a row on one parent task over 8.5 hours. That needed a workspace shared under a + policy retired on 2026-11-07, and every wave starts from an empty database. The existing U2 check + would have failed the task, so grading was not the gap. + +## Method and sources (read-only) + +Task labels `T01`–`T60` stand in for staging task identifiers, which are instance-local. The census +owner keeps the mapping outside the repository. + +- Staging API, GET only, with the operator's existing CLI token loaded into a child process: + - `/api/health`; + - `/api/companies/:id/heartbeat-runs` (company and per agent); + - `/api/heartbeat-runs/:id`; + - `/api/heartbeat-runs/:id/events`; + - `/api/issues/:id`, `/runs`, `/activity` and `/recovery-actions`. + + One company exists. There were 1917 runs in the window. +- Deploy and restart times: every run record carries `controllerProcess`, with `processStartedAt`, + `bootId` and the Railway `deploymentId`. The timeline below is built from those fields. + GitHub has no staging deployment records, because staging deploys from Railway. +- `git log origin/master` for fixes that touch each failure code. +- Window: a failure counts when its run finished at or after 2026-11-09T00:00Z. + +### Data the census could not read + +- **Sentry and Honeycomb:** no read credentials for staging were available. The only keys are + ingest/test-config keys. Sentry triage was not run. +- **a PR-review agent runs:** runs from 2026-11-09 00:00–14:52Z are missing. That agent made more than + 1000 runs in the window, and the run list caps at 1000 with no cursor. Other agents are complete. +- **Commit per deploy:** Railway deployment IDs do not map to git SHAs through the API. Only the + current SHA (`358977454b`, #20649) is visible. "Fixed on master" therefore means "a merged PR + changes this path". It does not mean the fix was proven live on staging. +- **Brief staging outage:** staging was in a maintenance window, `tenant_app_unavailable`, at about + 00:11Z on 2026-11-11, during the census. That was another deploy. Data read before the window is + complete. + +## Class table + +The share column is the share of the 276 failed runs. The "Blocked now" column counts tasks still +blocked at census time. + +| Class | Runs | Share | Tasks | Blocked now | Mechanism (root) | Fixed on master? | Why the harness missed it | Proposed scenario | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | +| W: wake loop on a held shared workspace | 103 | 37% | 4 | 1 | A parent shares a legacy execution workspace with a child that stranded a writer hold on Nov 5. The new stall-wake feature (#20098) woke the parent every 10 min. Each wake failed setup with no backoff. T01 had 99 runs from 07:27 to 15:53Z. | **Fixed:** #20273, #20295, #20314 | Fresh database every wave, so there was no legacy shared-workspace state. The feature landed between waves. U2 would have caught the loop. | None (fixed). If needed: K14 from a pre-2026-11-07 build with M1. | +| R: remote recovery refuses after a deploy | 34 | 12% | 32 | **24** | Recovery after a deploy refuses to continue. Codes include `runner_remote_process_identity_unavailable` (9), `native_remote_recovery_lease_mismatch …identity_run_id` (8), `prior_owner_terminal_state_indeterminate` (6), `cleanup_quarantined` (4) and `missing_evidence` (3). 27 of 34 failed within 10 min of a process start. | **Mostly fixed:** `identity_run_id` by #20642, `prior_owner…` by #20677, others by #20639, #20631, #20666, #20662 and #20650. **Open:** `runner_remote_process_identity_unavailable`, where the remote Runner is gone after a 4–7 min mid-turn outage. | Harness restarts come back at once, with no long mid-turn outage. There were no OpenCode cells on Daytona (19 of 34 are OpenCode). No Daytona workload keeps a tool running across the fault. | **K15 redeploy** (implemented). A long-hold and mid-tool variant with sandbox-side Runner log capture is the follow-up. | +| F: finalization and workspace save-back | 24 | 9% | 15 | 8 | A saved result cannot be copied back or restored. Causes: sandbox disk full (ENOSPC in 2 runs), unsafe symlink in the archive, `recovery_receipt_invalid` (7), a stuck "Recovering saved work…" phase (8) and an exhausted finalization budget (3). | **Partly fixed:** #20666 (receipt), #20578 (re-finalize). Nothing for disk full or symlinks. | Workloads write small files. They never fill the sandbox disk and never create symlinks. ST faults hit S3, not the sandbox disk. | **F1 symlink** workload (built; passes on master). **DF1 sandbox disk full** (proposed). | +| E: Daytona capacity outage | 18 | 7% | 13 | 4 | Daytona returned HTTP 502 and the worker hit SIGKILL from 16:36 to 17:02Z on Nov 10. Reusable sandbox resume failed, plus a git clone network failure. | **Mostly recovers:** 8 tasks recovered automatically and bounded retry works. 4 tasks still blocked. | The harness has no environment-provider fault. All faults hit the control plane or S3. | **EP1 environment provider 5xx window** (proposed, not built). | +| U: provider usage limit | 17 | 6% | 12 | 8 | `provider_limit_wait` waits as designed. The ACPX "terminal limit failure" (7) fails the run, where it should wait. | **Open:** ACPX limit classification. | Not a restart class. Provider shims have no usage-limit message. | Add a usage-limit message to PV faults (proposed). | +| P: provider session resume after a deploy | 16 | 6% | 16 | **11** | The runner or provider cannot resume its session after the controller moved. Codes: `PRP provider resume state is unavailable` (5), `runner_harness_state_mismatch` (8) with sub-codes `provider_identity_incomplete`, `resumed_unavailable` and `backup_without_reusable_lease`, plus `ingress_auth_failed` and `run.attach provider_side_effect_pending`. 8 of the 16 are ACPX and 5 are OpenCode. | **Partly fixed:** #20627 (warm backup). `resume state unavailable` is open. | Same as R: same process space, no OpenCode, no reusable warm sandboxes across deploys. | K15 with `--daytona-warm` and `--adapters claude,opencode`. | +| O: other or unclassified native failures | 13 | 5% | 13 | 5 | `native_run_failed` with no classified error (3), ACPX `session.open` rejected (2), `local_runtime_api_listener_unavailable` (2), `tool.resolve provider_tool_call_retired`, a DB query error, and `Object not found`. | **Open:** classification. | Not deploy-correlated (0 of 13 within 10 min). | None. These are product triage items. | +| B: authorization or binding readiness | 13 | 5% | 9 | 3 | `reviewed_chat_execution_binding_not_authorized` (7) and `not_ready` (2), a credential not shared with the responsible user (2), and a skill package still uploading (2). | **Open** | The harness uses one operator. There are no chat bindings, no shared credentials and no skill uploads. | Out of scope for restart chaos. Route to product. | +| L: legacy runtime lost across a deploy | 12 | 4% | 12 | 5 | Legacy (non-native) runs: `process_lost` (5), `Legacy controller lease lost` (4), graceful SIGTERM (1) and `lease_released_before_terminal` (2). | **Recovers in most cases:** 7 of 12 tasks recovered. | The matrix runs native adapters only. | K15 with a legacy adapter cell (proposed). | +| X: expected cancellations | 11 | 4% | 9 | 2 | Reassignment, ownership changes, dependency blocks and operator interrupts. | No fix needed | n/a | none | +| A: runner or provider-pack artifact incompatible after an upgrade | 8 | 3% | 8 | 4 | New code meets a sandbox prepared by older code. Codes: `OpenCode executable is missing from the provider pack`, `ACPX launch profile omitted its provider-pack authority`, `native_provider_artifacts_admission_unverified` (3), `runner_remote_artifact_platform_mismatch` and `runner_revision_mismatch`. | **Open** | Daytona waves require the runner content to match the image and refuse mismatches. That is exactly the mixed-version state staging lives in. K14 is local only. | **K15 with `--upgrade-from` on Daytona** (allows mixed runner/image versions; proposed follow-up). | +| V: runner event commit stall | 7 | 3% | 5 | 2 | `native_event_replay_conflict: runner_event_commit_stalled`, Codex and ACPX, 20:49–23:55Z on Nov 9. No deploy correlation. | **Likely fixed:** #20385 (usage receipt stalls). No occurrence after 23:55Z on Nov 9. | Database contention (L1) used one-row pressure, not the receipt-update pattern. | none (fixed) | + +Totals: 276 runs and 114 tasks. Classes R, P, A and L together are the deploy-crossing failures: +70 runs (25%) and **44 currently blocked tasks**, which is most of the user-visible harm. Class W is +the largest by count but is fixed. + +## Deploy timeline (Railway, from run records) + +47 process starts between 2026-11-08T22:03Z and 2026-11-10T23:23Z. All but one are new +`deploymentId`s. The exception is a same-deployment restart at 2026-11-09T14:28Z. The median gap in +working hours is about 40 minutes. Every native run longer than about 40 minutes crosses a deploy. + +67 of 276 failures (24%) finished within 10 minutes after a process start. In classes R and P, 30 of +50 did. In classes E, O and V, almost none did. + +## Per-class detail + +### W: wake loop on a held shared workspace (103 runs, fixed) + +- Examples: T01 (99 runs), T02, T03 and T04. +- Timeline: + 1. On Nov 5, child T05 failed setup (`workspace_busy`, then `setup_failed`). Its parent + T01 shared the workspace, a pre-2026-11-07 policy. + 2. On Nov 9, #20098 ("wake the parent once when a child stalls") reached staging. At 07:27Z the + parent began to be woken about every 10 min by `issue.blocker_stalled_wake`. + 3. Every wake failed with `The workspace still has an unfinished writer or save operation.` + 4. At 15:53Z the parent became `blocked`. +- Fixed by: + - #20273, which stops stall wakes from failing setup on a held workspace; + - #20295, which re-proves an exhausted save's agent stop; + - #20314, which moves stranded legacy subtasks off a parent's held workspace. +- Why the harness missed it: + - **Old saved state:** every wave starts from an empty database, so a parent/child pair sharing a + workspace (the legacy policy) never exists. + - **Missing feature in the tested build:** #20098 landed at 00:26Z on Nov 9, after the last wave + that had a stalled child. + - **Timing window:** the loop starts only after a child stalls for longer than the stall threshold. + - **Grading is not the gap.** The enforced U2 check already fails a task after more than three + failures with the same code and no status change. The parent would have failed U2 on its fourth + wake, if a wave had created the legacy state. +- Scenario: none is built in this pass, because the class is fixed and the shared-workspace policy + is retired for new subtasks. A K14 wave from a pre-2026-11-07 build with M1 would recreate the + legacy state, if the fix needs regression cover. + +### R: remote native recovery refuses after a deploy (34 runs, 24 tasks blocked) + +- Examples: + - T06, T07, T08 and T09 (`lease_mismatch identity_run_id`); + - T10, T11, T12 and T13 (`identity_unavailable`); + - T14, T15, T16 and T17 (`prior_owner_terminal_state_indeterminate`, with + `retirement_refused=journal_commands_unsettled(run.attach.pending | semantic_tool.result.pending)`); + - T18 and T19 (`cleanup_quarantined`). +- Mechanism, per sub-code. This was corrected after review by the class R fix owner. + - Native recovery does **not** depend on PID proofs. It uses `proveOwnerGone`, which accepts a + replaced Railway deployment on an exclusive volume (`deployment_replaced`) or a stopped or fenced + boot row. The only PID-only caller left is the runtime skill cache lock (#20688). + - `native_remote_recovery_lease_mismatch … identity_run_id`: the leases were ephemeral and the + sandboxes fresh, so a reused sandbox was not the cause. This is the shape that #20642 fixed. The + last staging occurrence was 14:43Z on Nov 10. + - `prior_owner_terminal_state_indeterminate` with unsettled `run.attach` or `semantic_tool.result`: + fixed by #20677. Retirement is no longer held when the prior ephemeral sandbox is provably + destroyed. + - `runner_remote_process_identity_unavailable` is **still open**: + 1. The controller dies mid-turn while tools run. + 2. Recovery starts 4–7 minutes later. + 3. By then the remote Runner process is gone, or its `session.snapshot` times out. + + Why the Runner exits despite its 60-minute connection lease is not yet known. +- Last occurrences: `identity_unavailable` 2026-11-10T08:10Z, `lease_mismatch` 14:43Z, `prior_owner…` + 18:56Z and `cleanup_quarantined` 17:48Z. +- Code pointers: + - `server/src/services/native-runtime/native-session-executor.ts:14247` (identity wait); + - `server/src/services/native-runtime/remote-recovery-lease-mismatch.ts`; + - `server/src/services/heartbeat/restart-interrupted-turn.ts`. +- Why the harness missed it: + 1. **Deploy timing:** a staging deploy sends a graceful SIGTERM, often 1–3 s after + `native.coordinator.claim`, and the server stays down for 4–7 minutes. K2 restarts at once, + and K4's long hold uses SIGKILL. + 2. **Missing adapter:** OpenCode (19 of 34) never ran in a Daytona cell. + 3. **Mid-turn Runner loss:** no Daytona workload keeps a tool running across the fault. The + `tool` trigger covers only the local B5 shell bench, so the remote Runner is never under a + running tool when the controller goes away. + 4. **Missing environment shape:** `--daytona-reuse-lease` and `--daytona-warm` are not in the + matrix. +- Scenario: **K15 redeploy** (implemented). The fault does a graceful SIGTERM like K2. The + replacement then starts in a new emulated process space (a new hostname through a preload, so + `processSpaceHash` changes) and with a new Railway-shaped deployment identity on the same volume. + Selected with `--faults K15`. RED wave: see "Harness expansion" below. + +### F: finalization and workspace save-back (24 runs, 8 tasks blocked) + +- Examples: + - T20 (`sync_out_retry_exhausted` from disk full, then the finalization budget, three times); + - T21 (`remote_workspace_archive_unsafe_symlink`); + - T22, T23 and T24 (`remote_workspace_recovery_receipt_invalid`); + - T25 and T10 ("Recovering saved work…" phase cancelled with + `execution_reconciliation_required`); + - T26, T27 and T28 (07:26Z on Nov 9, right after a deploy). +- Fixed: #20666 (skip unverifiable recovery sources) covers `receipt_invalid`, which last occurred + at 22:35Z, before that fix was deployed. Disk-full and symlink save-back have no fix and no + scenario. +- Why the harness missed it: **missing workload.** The workloads write a few KB, never fill the + sandbox disk and never create symlinks. ST faults break S3, not the sandbox file system. +- Built: the **F1** workload (`--workloads F1`). The agent keeps an absolute symlink to `/etc/hosts` + in its repository workspace. Wave `w-20261111T012523-s9304` (Daytona, `--storage s3`, K2, Codex + and OpenCode) passed 2 of 2 on master. The save-back did not block the task. The harness keeps no + evidence for passing tasks, so it is not verified that the link existed at save-back time. +- Proposed (not built): `DF1`, which fills the sandbox disk to ENOSPC before result copy-back. + +### E: Daytona capacity outage (18 runs, mostly self-healing) + +- 2026-11-10 16:36–17:02Z: + - `Daytona sandbox creation failed (HTTP 502)` (10); + - `Worker process exited (code=null, signal=SIGKILL)` (3); + - `Reusable sandbox lease … could not be resumed (cause=provider_error | transport_timeout)` (3). +- Plus one `git=network` clone failure and one Daytona rate-limit failure. +- Bounded retry recovered 8 of 13 tasks. 4 remain blocked (T29, T30, T31 and + T32 are examples). +- Fix #20626 (retry and replace a reusable sandbox that will not resume) shipped before the outage. + Its effect at this scale is not verified. +- Why the harness missed it: **missing fault type.** There is no environment-provider fault. All + harness faults hit the control plane, S3 or the provider message stream. +- Proposed: `EP1`, a proxy in front of the Daytona API that returns 502 or times out for a window. + +### U: provider usage limit (17 runs) + +- `provider_limit_wait` (10) is the designed wait. +- The ACPX "terminal limit failure" (7, an error-triage agent) fails the run. It should wait. This is a product + classification gap in the ACPX limit mapping. + +### P: provider session resume after a deploy (16 runs, 11 tasks blocked) + +- Examples: + - T33, T34, T35 and T25 (`PRP provider resume state is unavailable`); + - T36, T37, T38 and T39 (`runner_harness_state_mismatch …`); + - T40 (`run.attach provider_side_effect_pending`). +- Last occurrence: 2026-11-10T21:06Z. +- #20627 (restore a warm backup when its source sandbox is idle) covers `backup_without_reusable_lease` + and `resumed_unavailable`. `resume state is unavailable` and `provider_identity_incomplete` have no + fix. +- Why the harness missed it: the same reasons as R, plus ACPX (8) and OpenCode (5) on warm reusable + sandboxes, which the matrix does not run. + +### O: other (13 runs) + +- Not deploy-correlated. +- `native_run_failed` without a classified provider error appeared on T41, T42 and + T43. Those runs reached `run.result.accepted` after two `turn.failed` events. +- ACPX `session.open` was rejected on T44 and T45. +- These are product triage items, not chaos gaps. + +### B: authorization or binding readiness (13 runs) + +- `reviewed_chat_execution_binding_not_authorized`: 7 runs on a PR-review agent (T30 and T46). +- A credential not shared with the responsible user. +- Skill package uploads still in flight (T47). +- These are product authorization and readiness checks. They are outside the restart-chaos domain. + +### L: legacy runtime lost across a deploy (12 runs) + +- Examples: + - `process_lost` on T26, T27 and T48 (07:11Z on Nov 9, three minutes after a + deploy); + - `Legacy controller lease lost` on T49, T50, T51 and T52 (08:14–08:19Z on + Nov 10, 20 minutes after a deploy). +- 7 of 12 tasks recovered. +- The matrix has no legacy adapter cell. K15 could run one, but this was not done in this pass. + +### A: artifact incompatible after an upgrade (8 runs) + +- Examples: T53 and T54 (`OpenCode executable is missing from the provider pack`), T55 + (`ACPX launch profile omitted …`), T56, T57 and T58 + (`native_provider_artifacts_admission_unverified`), and T59 (`runner_revision_mismatch`). +- Mechanism: a sandbox prepared and admitted by older code is resumed by newer code that expects + new launch-profile fields or provider-pack contents. +- Why the harness missed it: Daytona waves refuse to run unless the runner content ID equals the + image (`daytona-image.ts`). This is deliberate, and it excludes exactly this mixed-version state. +- Follow-up: K15 with `--upgrade-from` on Daytona, with the image of the older checkout. + +### V: runner event commit stall (7 runs, likely fixed) + +- Examples: T60 and T22 (Nov 9, 20:49–23:55Z). +- #20385 (usage receipt stalls during streamed run updates) merged at 23:35Z, and the class has not + occurred since. + +## Harness expansion (this pass) + +| Scenario | Classes | Selector | Status | +| --- | --- | --- | --- | +| K15 redeploy into a new process space and deployment identity | R, P, L (and A with `--upgrade-from`) | `--faults K15` | Implemented, unit-tested. Five Daytona waves are recorded below. | +| EP1 environment-provider 5xx window | E | — | Proposed | +| F1 absolute symlink kept in the repository workspace | F (unsafe-symlink save-back) | `--workloads F1` | Implemented, unit-tested. Daytona wave: 2 of 2 pass on master. | +| DF1 sandbox disk full | F (ENOSPC save-back) | — | Proposed | + +### Waves on master 8f6ca25976 + +All waves ran on Daytona image `ghcr.io/paperclipai/paperclip-daytona-runner@sha256:bc7ca92d…` +(runner content `d7e4d82a…`). + +| Wave | Args | Result | +| --- | --- | --- | +| `w-20261111T002313-s9301` | `--faults K15 --adapters opencode,claude --workloads A1,C1 --daytona-reuse-lease --concurrency 3 --tasks 6` | 5 of 6 pass. t05 (OpenCode, C1) failed R5 `silent_dead_run`: its run stayed `running` with no event, activity or start evidence for 183 s after the redeploy, then succeeded. No Retry was needed. | +| `w-20261111T004241-s9301` (control) | the same seed and cells with `--faults K2` | 6 of 6 pass | +| `w-20261111T005008-s9302` | `--faults K15 --triggers time,comment --adapters opencode,claude --workloads C1 --daytona-warm --concurrency 4 --tasks 4` | 4 of 4 pass | +| `w-20261111T010000-s9303` | `--faults K15 --adapters opencode --workloads A1,C1 --daytona-reuse-lease --concurrency 4 --tasks 8` | 8 of 8 pass | +| `w-20261111T011044-s9303` (control) | the same seed and cells with `--faults K2` | 8 of 8 pass | + +What this shows: + +- Under K15, 17 of 18 tasks passed. Under K2 with the same seeds, 14 of 14 passed. The one failure, + a 183 s silent OpenCode run after a redeploy, occurred only under K15. One failure in 18 is not a + stable reproduction. +- The staging refusal codes of classes R and P did **not** reproduce on current master with K15 + alone. Examples are `identity_run_id` lease mismatch, `runner_remote_process_identity_unavailable` + and `prior_owner_terminal_state_indeterminate`. Two explanations remain open: + - The fixes merged during the window (#20625, #20631, #20639, #20650, #20662, #20666) cover them. + Staging ran older revisions for most of the window. + - They need conditions that K15 does not emulate yet: + - a code change at the deploy, where new server code meets saved state and a sandbox runner from + the older build (class A); + - one sandbox reused across different tasks of one agent; + - many agents and concurrent tasks under load. +- The next scenario to build is **K15 with `--upgrade-from` on Daytona**: start with the older + checkout and its image, redeploy to the current checkout, and keep the older runner in the + retained sandboxes. Today the Daytona image check refuses that mixed state on purpose. diff --git a/tests/restart-chaos/README.md b/tests/restart-chaos/README.md index 672f94618d4..b457d35b03f 100644 --- a/tests/restart-chaos/README.md +++ b/tests/restart-chaos/README.md @@ -292,6 +292,76 @@ receipt names both commits (`upgrade` in `faults.json`, `upgrade_switched` in th timeline). K14 is local-only, because a Daytona runner must match its image, and it is never part of a storm's default faults. +## Redeploy (K15, `redeploy.ts`) + +```sh +node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/main.ts --env daytona --daytona-image $IMG --daytona-cpu 3 \ + --adapters opencode,claude --workloads A1,C1 --faults K15 --daytona-reuse-lease --concurrency 3 --tasks 6 --seed 9301 +``` + +The hosted staging stack deploys about every 40 minutes. Each deploy replaces +the server's container. The replacement has the same database and volume, but it +runs in another process space (host name, kernel boot and PID namespace) and +has a new Railway deployment id. The server's PID-based proof that an earlier +owner exited (`controller-process-identity.ts`, `owner-proof.ts`) never applies +across a deploy. Recovery must use the deployment proof or the lease deadlines +instead. K1 and K2 restart on the same machine, so every PID proof succeeds and +that path stays untested. See `doc/plans/2026-11-11-staging-failures-vs-chaos-coverage.md`. + +K15 emulates the container replacement without a container: + +- Every server in a wave that has a K15 is launched with a `--import` preload + (`redeploy-preload.mjs`). The preload makes `os.hostname()` return a + per-generation name, which changes the process-space hash. +- Every server gets Railway-shaped variables: `RAILWAY_PROJECT_ID`, + `RAILWAY_ENVIRONMENT_ID`, `RAILWAY_SERVICE_ID` and `RAILWAY_DEPLOYMENT_ID`, + plus `RAILWAY_VOLUME_ID` and `RAILWAY_VOLUME_MOUNT_PATH`, which is the + instance home. +- A K15 stops the server with SIGTERM, like K2. The replacement starts as the + next generation, with a new host name and deployment id, on the same project, + service and volume. +- Other faults in the same wave restart within the current generation, like a + platform restart of the same deployment. +- Identities derive from the wave id; a replay uses the source wave id, so it sees the same ones. +- Each K15 receipt records `redeploy` (both generations) in `faults.json`, and + `redeploy_switched` in the timeline. + +Limits: + +- The Daytona sandboxes and remote runners survive, as they do on staging. +- Local runners are stopped with the server's process tree. +- The cloud stop-proof service (`PAPERCLIP_CLOUD_*`) is not emulated, so stop + proofs that need it stay unsupported, as on any self-hosted Railway deploy. +- K15 does not combine with MS1–MS3, because a second server would run in the + real host's process space. +- Combine K15 with `--adapters opencode` and `--daytona-reuse-lease` or + `--daytona-warm` to match staging's workload mix. + +## Absolute symlink in the workspace (F1) + +```sh +node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/main.ts --env daytona --daytona-image $IMG --daytona-cpu 3 \ + --adapters codex,opencode --workloads F1 --faults K2 --storage s3 --concurrency 2 --tasks 2 --seed 9304 +``` + +F1 is opt-in. The agent creates `hosts-link-`, which is an absolute +symlink to `/etc/hosts`, in its repository workspace and keeps it. It also +writes a notes file, and then marks the task done. + +On staging, a remote save-back refused such a link +(`remote_workspace_archive_unsafe_symlink`). The save-back then used up its +retries and left the task blocked. Agents create absolute links in ordinary +work, for example in tool caches or `node_modules/.bin`. + +The oracle passes when: + +- the task is `done`; +- the notes file is saved, without a Retry. + +How the product saves the link itself (skip it, keep it, or record it) is not +graded. F1 is meaningful with a remote workspace (`--env daytona`, with +`--storage s3` as on staging). Locally it is a plain repository task. + ## Config faults (CF1–CF3, `config-wave.ts`) ```sh @@ -991,7 +1061,7 @@ re-arms the task's own triggered faults instead of using their offsets. | `grader.ts` | Pure R1–R6 grading over the samples, plus the universal checks. | | `universal.ts`, `universal-audit.ts` | U1–U4 on every task, and their audit over saved waves. | | `contention.ts` | L1 workload, its accounting oracle and the `--db-pressure` writers. | -| `workloads.ts` | A1 brief document, B1 python CLI with tests, B5 long bench, C1 comment while running, M1 delegation, G1 approval across a restart, H1 budget hard stop across a restart, with their T-oracles. | +| `workloads.ts` | A1 brief document, B1 python CLI with tests, B5 long bench, C1 comment while running, M1 delegation, G1 approval across a restart, H1 budget hard stop across a restart, F1 absolute symlink kept in the workspace, with their T-oracles. | | `journeys.ts`, `journey-driver.ts`, `journey-oauth-app.ts`, `journey-matrix.ts` | Q2 and Q3 definitions and oracles, the board's side of each, Q3's loopback OAuth/MCP app, and the `--matrix` planner. | | `evidence.ts`, `ledger.ts` | Evidence bundle for each failure and the JSONL ledger plus `SUMMARY.md`. | | `daytona-image.ts` | Docker-free extraction of the image's runnerd and provider pack, cached per digest, and the controller/image content-ID check. | @@ -1001,6 +1071,7 @@ re-arms the task's own triggered faults instead of using their offsets. | `time-faults.ts`, `time-faults-config.ts` | TM1–TM3: process freezing, database aging with recorded rows, and the time-corrected API the grader reads through. | | `multi-server.ts` | MS1–MS3: the second server's steps, the seeded holds, and the cross-server invariant over the wave database. | | `repeated-restarts.ts` | RR1–RR3: seeded restart steps, `--rr-gap-seconds`, and the stop-and-replace loop the supervisor runs. | +| `redeploy.ts`, `redeploy-preload.mjs` | K15: per-generation emulated host name and Railway deployment identity, and the preload that applies the host name. | | `daytona-sweep.ts` | Daytona R6: read-only reconciliation of this wave's labelled sandboxes with leases; cleanup only through Paperclip. | ## Output (gitignored) diff --git a/tests/restart-chaos/config.ts b/tests/restart-chaos/config.ts index 8c6baac226e..32a4439b5b6 100644 --- a/tests/restart-chaos/config.ts +++ b/tests/restart-chaos/config.ts @@ -4,7 +4,7 @@ import { parseArgs } from "node:util"; import { applyJourneyOptions } from "./journey-matrix.js"; import { takesJourneyTriggers } from "./journeys.js"; import { STORAGE_FAULT_KINDS, type StorageFaultKind } from "./storage-chaos.js"; -import { validateMultiServerOptions } from "./multi-server.js"; +import { isMultiServerFault, validateMultiServerOptions } from "./multi-server.js"; import { parseTimeFaultOptions } from "./time-faults-config.js"; import { parseStorageTrigger } from "./storage-trigger.js"; import { parseNativeTrigger, parseNativeTriggerOutage } from "./native-trigger.js"; @@ -17,7 +17,10 @@ import { type AdapterId, type EnvironmentKind, type FaultKind, type TriggerId, type WaveOptions, type WorkloadId, } from "./types.js"; -/** A storm's default faults: every restart kind except K14, which needs an older build (`--upgrade-from`). */ +/** + * A storm's default faults: every restart kind except K14, which needs an older build (`--upgrade-from`), + * and K15, which changes the deploy identity of every later server (pass `--faults` to include it). + */ export const STORM_DEFAULT_FAULTS: FaultKind[] = ["K1", "K2", "K4", "K6"]; export const CREDENTIAL_FOR_ADAPTER: Record = { @@ -176,7 +179,7 @@ export function parseCommand(argv: readonly string[], now = Date.now()): ParsedC env, adapters, // The governance scenarios (G1, H1), the journeys (Q1–Q3) and the contention run (L1) are opt-in: H1 needs a wave of its own. - workloads: list(values.workloads, workloadChoices, "workloads", workloadChoices.filter(id => id !== "G1" && id !== "H1" && id !== "R1" && id !== "S1" && id !== "L1" + workloads: list(values.workloads, workloadChoices, "workloads", workloadChoices.filter(id => id !== "G1" && id !== "H1" && id !== "R1" && id !== "S1" && id !== "L1" && id !== "F1" && !takesJourneyTriggers(id) && (id !== "M1" || adapters.length >= 2))), // A crash-point wave schedules no fault; K1 is the restart its self-kill gets. faults: allFaults.filter((fault): fault is FaultKind => !isProviderFault(fault)), @@ -233,6 +236,10 @@ export function parseCommand(argv: readonly string[], now = Date.now()): ParsedC throw new Error("--provider-fault-message, --provider-fault-delays and --provider-fault-restart need a provider fault (PV1, PV2 or PV3) in --faults"); } validateMultiServerOptions(options); + // K15 emulates one deploy identity per generation; a second server beside it would run in the real host's process space. + if (options.faults.includes("K15") && options.faults.some(isMultiServerFault)) { + throw new Error("K15 (redeploy) does not combine with MS1-MS3: the second server would not share the emulated deploy identity"); + } Object.assign(options, parseTimeFaultOptions(options, values["time-age-hours"])); Object.assign(options, parseRepeatedRestartOptions(options, values["rr-gap-seconds"], values["rr-stop-on"])); const upgradeFrom = values["upgrade-from"]; diff --git a/tests/restart-chaos/f1-symlink.test.ts b/tests/restart-chaos/f1-symlink.test.ts new file mode 100644 index 00000000000..39af1900dd6 --- /dev/null +++ b/tests/restart-chaos/f1-symlink.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from "vitest"; +import { parseCommand } from "./config.js"; +import { WORKLOAD_TRIGGERS } from "./journeys.js"; +import { planTasks } from "./scheduler.js"; +import type { OracleArtifacts } from "./types.js"; +import { f1LinkName, workloadDefinitions } from "./workloads.js"; + +const NONCE = "abc123de"; +const LISTING = `lrwxrwxrwx 1 daytona daytona 10 Nov 11 01:30 hosts-link-${NONCE} -> /etc/hosts`; +const notes = (text: string) => ({ [`NOTES-${NONCE}.md`]: text }); +const artifacts = (overrides: Partial = {}): OracleArtifacts => ({ + issueStatus: "done", documents: {}, agentComments: [], files: notes(`F1-${NONCE}\n${LISTING}\n`), commands: {}, + workspacePath: "/workspace/chaos", ...overrides, +}) as OracleArtifacts; + +describe("F1: absolute symlink kept in the repository workspace", () => { + const f1 = workloadDefinitions.F1; + + it("asks for the absolute link and the notes file in a repository workspace", () => { + expect(f1.usesRepository).toBe(true); + const text = f1.description(NONCE); + expect(text).toContain(`ln -s /etc/hosts ${f1LinkName(NONCE)}`); + expect(text).toContain(`NOTES-${NONCE}.md`); + expect(f1.collect.files(NONCE)).toEqual([`NOTES-${NONCE}.md`]); + }); + + it("passes only when the task is done and its saved notes file is in the workspace", () => { + expect(f1.grade(NONCE, artifacts()).verdict).toBe("pass"); + expect(f1.grade(NONCE, artifacts({ issueStatus: "blocked" })).verdict).toBe("fail"); + expect(f1.grade(NONCE, artifacts({ files: {} })).verdict).toBe("fail"); + expect(f1.grade(NONCE, artifacts({ workspacePath: null })).verdict).toBe("fail"); + }); + + it("needs the agent's ls -l line proving the absolute link existed before the save-back", () => { + expect(f1.description(NONCE)).toContain(`ls -l ${f1LinkName(NONCE)}`); + // Skipped link: notes only. + expect(f1.grade(NONCE, artifacts({ files: notes(`F1-${NONCE}\n`) })).verdict).toBe("fail"); + // A regular file of the same name, or a link elsewhere, is not the link under test. + expect(f1.grade(NONCE, artifacts({ files: notes(`F1-${NONCE}\n-rw-r--r-- 1 d d 3 Nov 11 01:30 hosts-link-${NONCE}\n`) })).verdict).toBe("fail"); + expect(f1.grade(NONCE, artifacts({ files: notes(`F1-${NONCE}\n${LISTING.replace("/etc/hosts", "etc/hosts")}\n`) })).verdict).toBe("fail"); + expect(f1.grade(NONCE, artifacts({ files: notes(`F1-${NONCE}\n${LISTING.replace(NONCE, "ffffffff")}\n`) })).verdict).toBe("fail"); + }); + + it("is opt-in, time-triggered, and plans with restart faults on Daytona", () => { + expect(WORKLOAD_TRIGGERS.F1).toEqual(["time"]); + const defaults = parseCommand(["--seed", "1"]); + expect(defaults.mode === "wave" && defaults.options.workloads).not.toContain("F1"); + const parsed = parseCommand(["--env", "daytona", "--daytona-image", `ghcr.io/paperclipai/paperclip-daytona-runner@sha256:${"b".repeat(64)}`, + "--workloads", "F1", "--faults", "K2,K15", "--adapters", "codex", "--tasks", "2", "--seed", "3"]); + if (parsed.mode !== "wave") throw new Error("expected a wave"); + expect(planTasks(parsed.options).map(task => task.workload)).toEqual(["F1", "F1"]); + }); +}); diff --git a/tests/restart-chaos/journeys.ts b/tests/restart-chaos/journeys.ts index e2b0199ec0c..50c4d3a0c10 100644 --- a/tests/restart-chaos/journeys.ts +++ b/tests/restart-chaos/journeys.ts @@ -35,7 +35,7 @@ export type JourneyTrigger = (typeof JOURNEY_TRIGGERS)[number]; /** Each workload's own fault boundaries, for the journey × fault matrix. */ export const WORKLOAD_TRIGGERS: Record = { A1: ["time"], B1: ["time"], B5: ["tool"], C1: ["comment", "result"], M1: ["time"], G1: ["approval"], - H1: ["paused"], R1: ["time"], S1: ["stop"], L1: ["time"], Q1: JOURNEY_TRIGGERS, Q2: JOURNEY_TRIGGERS, Q3: JOURNEY_TRIGGERS, + H1: ["paused"], R1: ["time"], S1: ["stop"], L1: ["time"], F1: ["time"], Q1: JOURNEY_TRIGGERS, Q2: JOURNEY_TRIGGERS, Q3: JOURNEY_TRIGGERS, }; /** Q3 reviews must survive a delay longer than the implicit deadline #20340 removed. */ diff --git a/tests/restart-chaos/main.ts b/tests/restart-chaos/main.ts index d31cdd29190..2d205493d6e 100644 --- a/tests/restart-chaos/main.ts +++ b/tests/restart-chaos/main.ts @@ -38,6 +38,7 @@ import { collectWaveSpeed, speedMarkdown } from "./wave-speed.js"; import { TaskObserver, childSpeedTasksInTurn } from "./observer.js"; import { closeJourneyApps } from "./journey-driver.js"; import { matrixMayLaunch, planMatrixWave } from "./journey-matrix.js"; +import { redeployWave } from "./redeploy.js"; import { StormRun, TASK_FAULT_LOG, observedFaultSchedule, planWave, replayOnCurrentBuild, replayRecordFor, replayWave, type TaskFaultLog } from "./scheduler.js"; import { chaosLifecycleOverrides, seedChaosLab } from "./seed.js"; import { ChaosSupervisor } from "./supervisor.js"; @@ -200,7 +201,9 @@ async function main(): Promise { const batchSize = crashPoints.length ? Math.max(1, Math.floor(plan.tasks.length / crashPoints.length)) : 0; if (crashPoint && plan.tasks.length !== batchSize * crashPoints.length) throw new Error(`--tasks must be a multiple of the ${crashPoints.length} crash point(s)`); const supervisor = await ChaosSupervisor.create({ repositoryRoot, waveDir, timeline, - ...(plan.options.upgradeFrom ?? plan.options.serverFrom ? { upgradeFrom: plan.options.upgradeFrom ?? plan.options.serverFrom } : {}) }); + ...(plan.options.upgradeFrom ?? plan.options.serverFrom ? { upgradeFrom: plan.options.upgradeFrom ?? plan.options.serverFrom } : {}), + // K15: every server of the wave runs under an emulated deploy identity; a replay derives the source wave's ones. + ...(redeployWave(plan) ? { redeployWaveId: plan.replayOf?.waveId ?? plan.waveId } : {}) }); // Crash-point suite: one booted server, one point at a time. Each point gets // its own batch of tasks; the point is armed once the batch launched and the // server kills itself at its nth hit (restarted like K1). Invariants are diff --git a/tests/restart-chaos/redeploy-preload.mjs b/tests/restart-chaos/redeploy-preload.mjs new file mode 100644 index 00000000000..7767bfc0b44 --- /dev/null +++ b/tests/restart-chaos/redeploy-preload.mjs @@ -0,0 +1,12 @@ +// K15 (redeploy.ts): give the server process an emulated host name, so its process-space hash +// differs from the previous deploy's, as a replaced container's does. Loaded with `--import` +// before the server. Node children forked with the server's execArgv inherit it, as they share its container. +import os from "node:os"; +import { syncBuiltinESMExports } from "node:module"; + +const hostname = process.env.RESTART_CHAOS_REDEPLOY_HOSTNAME?.trim(); +if (hostname) { + os.hostname = () => hostname; + // `import { hostname } from "node:os"` reads the ESM export, which only follows the CJS object after a sync. + syncBuiltinESMExports(); +} diff --git a/tests/restart-chaos/redeploy.test.ts b/tests/restart-chaos/redeploy.test.ts new file mode 100644 index 00000000000..dd23abd74b3 --- /dev/null +++ b/tests/restart-chaos/redeploy.test.ts @@ -0,0 +1,93 @@ +import { spawnSync } from "node:child_process"; +import { describe, expect, it } from "vitest"; +import { parseCommand } from "./config.js"; +import { + REDEPLOY_HOSTNAME_ENV, REDEPLOY_PRELOAD_PATH, nextRedeployIdentity, redeployEnvironment, redeployIdentity, redeployNodeArgs, + redeployReceipt, redeployWave, +} from "./redeploy.js"; +import { planTasks } from "./scheduler.js"; +import { FAULT_SIGNAL } from "./supervisor.js"; +import type { WavePlan } from "./types.js"; + +const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-5[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/; +const IMAGE = `ghcr.io/paperclipai/paperclip-daytona-runner@sha256:${"a".repeat(64)}`; + +describe("K15 redeploy identity", () => { + it("keeps the service and volume and changes the host and deployment on every generation", () => { + const first = redeployIdentity("w-1", 0); + const second = nextRedeployIdentity("w-1", first); + expect(second.generation).toBe(1); + expect(second.hostname).not.toBe(first.hostname); + expect(second.deploymentId).not.toBe(first.deploymentId); + for (const key of ["projectId", "environmentId", "serviceId", "volumeId"] as const) expect(second[key]).toBe(first[key]); + for (const id of [first.projectId, first.environmentId, first.serviceId, first.deploymentId, first.volumeId]) expect(id).toMatch(UUID); + }); + + it("is deterministic per wave, so a replay derives the same identities", () => { + expect(redeployIdentity("w-1", 3)).toEqual(redeployIdentity("w-1", 3)); + expect(redeployIdentity("w-2", 0).deploymentId).not.toBe(redeployIdentity("w-1", 0).deploymentId); + expect(() => redeployIdentity("w-1", -1)).toThrow(/non-negative/); + }); + + it("names the Railway variables the server reads as its deployment, with the instance home as the exclusive volume", () => { + const identity = redeployIdentity("w-1", 2); + expect(redeployEnvironment(identity, "/tmp/chaos/home")).toEqual({ + [REDEPLOY_HOSTNAME_ENV]: identity.hostname, + RAILWAY_PROJECT_ID: identity.projectId, RAILWAY_ENVIRONMENT_ID: identity.environmentId, RAILWAY_SERVICE_ID: identity.serviceId, + RAILWAY_DEPLOYMENT_ID: identity.deploymentId, RAILWAY_VOLUME_ID: identity.volumeId, RAILWAY_VOLUME_MOUNT_PATH: "/tmp/chaos/home", + }); + expect(redeployReceipt(redeployIdentity("w-1", 0), identity)).toMatchObject({ fromGeneration: 0, toGeneration: 2, + toDeploymentId: identity.deploymentId, volumeId: identity.volumeId }); + }); + + it("loads the preload ahead of the server's own --import loader", () => { + expect(redeployNodeArgs(["--import", "/x/tsx/loader.mjs", "entry.ts"])).toEqual(["--import", REDEPLOY_PRELOAD_PATH, "--import", "/x/tsx/loader.mjs", "entry.ts"]); + }); + + it("changes os.hostname for both the CommonJS object and ESM named imports, as processSpaceHash reads it", () => { + const script = "import os from 'node:os'; import { hostname } from 'node:os'; console.log(JSON.stringify([os.hostname(), hostname()]));"; + const run = (env: NodeJS.ProcessEnv) => spawnSync(process.execPath, ["--import", REDEPLOY_PRELOAD_PATH, "--input-type=module", "-e", script], + { env: { PATH: process.env.PATH, ...env }, encoding: "utf8" }); + const emulated = run({ [REDEPLOY_HOSTNAME_ENV]: "chaos-deploy-test" }); + expect(emulated.status).toBe(0); + expect(JSON.parse(emulated.stdout)).toEqual(["chaos-deploy-test", "chaos-deploy-test"]); + // Without the variable the preload changes nothing. + const real = run({}); + expect(real.status).toBe(0); + const [cjs, esm] = JSON.parse(real.stdout) as string[]; + expect(cjs).toBe(esm); + expect(cjs).not.toBe("chaos-deploy-test"); + }); +}); + +describe("K15 wave options", () => { + it("is a graceful stop, selectable on local and Daytona like K2", () => { + expect(FAULT_SIGNAL.K15).toBe("SIGTERM"); + const local = parseCommand(["--faults", "K15", "--adapters", "opencode", "--workloads", "A1,C1", "--seed", "1"]); + expect(local.mode === "wave" && local.options.faults).toEqual(["K15"]); + const daytona = parseCommand(["--env", "daytona", "--daytona-image", IMAGE, "--faults", "K2,K15", "--adapters", "opencode", + "--workloads", "C1", "--daytona-reuse-lease", "--seed", "1"]); + if (daytona.mode !== "wave") throw new Error("expected a wave"); + expect(daytona.options.faults).toEqual(["K2", "K15"]); + expect(daytona.options.daytonaReuseLease).toBe(true); + }); + + it("refuses a second server beside an emulated deploy", () => { + expect(() => parseCommand(["--faults", "K15,MS1", "--workloads", "B5,Q1", "--concurrency", "1", "--seed", "1"])).toThrow(/K15 \(redeploy\) does not combine with MS1-MS3/); + }); + + it("plans K15 cells with no hold and marks the wave as a redeploy wave", () => { + const parsed = parseCommand(["--faults", "K15", "--adapters", "codex,opencode", "--workloads", "A1,C1", "--tasks", "4", "--seed", "7"]); + if (parsed.mode !== "wave") throw new Error("expected a wave"); + const tasks = planTasks(parsed.options); + expect(tasks.every(task => task.fault === "K15" && task.holdMs === 0)).toBe(true); + const plan = { options: parsed.options, tasks } as Pick; + expect(redeployWave(plan)).toBe(true); + const k2 = parseCommand(["--faults", "K2", "--workloads", "A1", "--tasks", "2", "--seed", "7"]); + if (k2.mode !== "wave") throw new Error("expected a wave"); + expect(redeployWave({ options: k2.options, tasks: planTasks(k2.options) })).toBe(false); + // A replay of a K2 task that a K15 crossed still needs the emulated identity. + expect(redeployWave({ options: k2.options, tasks: [{ ...planTasks(k2.options)[0]!, + replayFaults: [{ kind: "K15", holdMs: 0, atMs: 1_000 }] }] })).toBe(true); + }); +}); diff --git a/tests/restart-chaos/redeploy.ts b/tests/restart-chaos/redeploy.ts new file mode 100644 index 00000000000..7be1e02ca65 --- /dev/null +++ b/tests/restart-chaos/redeploy.ts @@ -0,0 +1,96 @@ +/** + * K15 (redeploy): what a hosted deploy does to the control plane, beyond K2's graceful stop. + * + * On the hosted staging stack every deploy replaces the server's container. The replacement runs + * in another process space (host name, kernel boot and PID namespace), so the server's PID-based + * "the previous owner has exited" proofs (`server/src/services/controller-process-identity.ts`, + * `owner-proof.ts`) never apply. It also carries a new Railway deployment id on the same exclusive + * volume, which is the proof hosted recovery uses instead. A K1/K2 restart on one machine keeps the + * process space, so every PID proof succeeds there and this path is never exercised. + * + * K15 emulates both changes without a container: each server of a K15 wave sees an emulated host + * name (a `--import` preload replaces `os.hostname`, which changes the process-space hash) and + * Railway-shaped deployment variables naming one stable project, environment, service and volume + * and a deployment id per generation. A K15 stops the server with SIGTERM like K2 and starts the + * replacement as the next generation. Other faults in the same wave restart within a generation, + * like a platform restart of the same deployment. + */ +import { createHash } from "node:crypto"; +import { fileURLToPath } from "node:url"; +import type { WavePlan } from "./types.js"; + +/** Whether any server of this wave can be redeployed: a planned, storm or replayed K15. */ +export function redeployWave(plan: Pick): boolean { + return plan.options.faults.includes("K15") || (plan.storm?.faults.some(fault => fault.kind === "K15") ?? false) + || plan.tasks.some(task => task.fault === "K15" || (task.replayFaults?.some(fault => fault.kind === "K15") ?? false)); +} + +/** The preload that applies the emulated host name before the server loads. */ +export const REDEPLOY_PRELOAD_PATH = fileURLToPath(new URL("./redeploy-preload.mjs", import.meta.url)); +/** Read by the preload: the host name `os.hostname()` returns in the server process. */ +export const REDEPLOY_HOSTNAME_ENV = "RESTART_CHAOS_REDEPLOY_HOSTNAME"; + +export interface RedeployIdentity { + /** 0 for the wave's first server; each K15 adds one. */ + generation: number; + hostname: string; + projectId: string; + environmentId: string; + serviceId: string; + deploymentId: string; + volumeId: string; +} + +/** A deterministic UUID-shaped id for one wave, role and generation (no randomness: replays match). */ +function uuidFor(waveId: string, role: string, generation = 0): string { + const hex = createHash("sha256").update(`restart-chaos-redeploy:${waveId}:${role}:${generation}`).digest("hex"); + // Version 5-style layout so validators that require a UUID shape accept it. + const variant = ((parseInt(hex[16]!, 16) & 0x3) | 0x8).toString(16); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-${variant}${hex.slice(17, 20)}-${hex.slice(20, 32)}`; +} + +/** The identity of the server that serves generation `generation` of this wave. */ +export function redeployIdentity(waveId: string, generation: number): RedeployIdentity { + if (!Number.isInteger(generation) || generation < 0) throw new Error(`Redeploy generation must be a non-negative integer, got ${generation}`); + return { + generation, + hostname: `chaos-deploy-${createHash("sha256").update(`${waveId}:${generation}`).digest("hex").slice(0, 10)}`, + projectId: uuidFor(waveId, "project"), + environmentId: uuidFor(waveId, "environment"), + serviceId: uuidFor(waveId, "service"), + deploymentId: uuidFor(waveId, "deployment", generation), + volumeId: uuidFor(waveId, "volume"), + }; +} + +/** The next deploy of the same service: same project, environment, service and volume. */ +export function nextRedeployIdentity(waveId: string, current: RedeployIdentity): RedeployIdentity { + return redeployIdentity(waveId, current.generation + 1); +} + +/** + * Server environment for one generation. The volume mount is the instance home: on staging the + * instance directory lives on the exclusive volume that survives each deploy. + */ +export function redeployEnvironment(identity: RedeployIdentity, volumeMountPath: string): Record { + return { + [REDEPLOY_HOSTNAME_ENV]: identity.hostname, + RAILWAY_PROJECT_ID: identity.projectId, + RAILWAY_ENVIRONMENT_ID: identity.environmentId, + RAILWAY_SERVICE_ID: identity.serviceId, + RAILWAY_DEPLOYMENT_ID: identity.deploymentId, + RAILWAY_VOLUME_ID: identity.volumeId, + RAILWAY_VOLUME_MOUNT_PATH: volumeMountPath, + }; +} + +/** Node arguments that load the preload ahead of the server entry's own `--import` loader. */ +export function redeployNodeArgs(args: readonly string[]): string[] { + return ["--import", REDEPLOY_PRELOAD_PATH, ...args]; +} + +/** What a K15 receipt records: both generations, so a replay and the evidence name them. */ +export function redeployReceipt(from: RedeployIdentity, to: RedeployIdentity) { + return { fromGeneration: from.generation, toGeneration: to.generation, fromHostname: from.hostname, toHostname: to.hostname, + fromDeploymentId: from.deploymentId, toDeploymentId: to.deploymentId, volumeId: to.volumeId }; +} diff --git a/tests/restart-chaos/supervisor.ts b/tests/restart-chaos/supervisor.ts index 86e35504c40..6ae0399120a 100644 --- a/tests/restart-chaos/supervisor.ts +++ b/tests/restart-chaos/supervisor.ts @@ -39,6 +39,7 @@ import { isRepeatedRestartFault, newRepeatedRestartRecord, recordFirstRestart, r type RepeatedRestartRecord, type RestartStep } from "./repeated-restarts.js"; import type { FaultKind, FaultReceipt, TriggerId } from "./types.js"; import { isMultiServerFault, runMultiServerFault, type MultiServerKind, type MultiServerRecord, type ServerProcessWindow } from "./multi-server.js"; +import { nextRedeployIdentity, redeployEnvironment, redeployIdentity, redeployNodeArgs, redeployReceipt, type RedeployIdentity } from "./redeploy.js"; /** First boot applies every migration; a loaded host can need longer (RESTART_CHAOS_HEALTH_TIMEOUT_MS). */ const HEALTH_TIMEOUT_MS = (() => { @@ -48,7 +49,7 @@ const HEALTH_TIMEOUT_MS = (() => { const READY_TIMEOUT_MS = 300_000; const STOP_TIMEOUT_MS = 30_000; -export const FAULT_SIGNAL: Record = { K1: "SIGKILL", K2: "SIGTERM", K4: "SIGKILL", K6: "SIGKILL", K14: "SIGTERM", +export const FAULT_SIGNAL: Record = { K1: "SIGKILL", K2: "SIGTERM", K4: "SIGKILL", K6: "SIGKILL", K14: "SIGTERM", K15: "SIGTERM", TM1: "SIGSTOP", TM2: "SIGSTOP", TM3: "SIGKILL", RR1: "SIGKILL", RR2: "SIGKILL", RR3: "SIGKILL", // MS1 leaves the primary alone; MS2 freezes it; MS3 stops it gracefully (multi-server.ts). MS1: "none", MS2: "SIGSTOP", MS3: "SIGTERM" }; @@ -154,13 +155,16 @@ export class ChaosSupervisor { private serverRoot: string; /** The environment overrides the wave passed to `start`, kept for every restart and for the K14 switch. */ private extraEnvironment: Record = {}; + /** K15 waves: the wave id the emulated deploy identities derive from, and the generation serving now. */ + private redeploy: { waveId: string; identity: RedeployIdentity } | null = null; /** Wave secrets, kept across a K14 switch as an in-place upgrade keeps its configuration. */ private readonly secrets = { PAPERCLIP_AGENT_JWT_SECRET: secret(), PAPERCLIP_DECISION_SIGNING_SECRET: secret(), PAPERCLIP_TOOL_ACTION_SIGNING_SECRET: secret(), BETTER_AUTH_SECRET: secret() }; private constructor(readonly repositoryRoot: string, readonly port: number, readonly paths: SupervisorPaths, - private readonly timeline: Timeline, upgradeFrom: string | null) { + private readonly timeline: Timeline, upgradeFrom: string | null, redeployWaveId: string | null) { this.serverRoot = upgradeFrom ?? repositoryRoot; + if (redeployWaveId) this.redeploy = { waveId: redeployWaveId, identity: redeployIdentity(redeployWaveId, 0) }; this.baseUrl = `http://127.0.0.1:${port}`; this.log = createWriteStream(paths.serverLogPath, { flags: "a", mode: 0o600 }); this.stopper = createRunnerE2EServerStopper({ @@ -171,13 +175,16 @@ export class ChaosSupervisor { }); } - static async create(input: { repositoryRoot: string; waveDir: string; timeline: Timeline; upgradeFrom?: string }): Promise { + /** `redeployWaveId`: a K15 wave; every server gets the emulated deploy identity of its generation (redeploy.ts). */ + static async create(input: { repositoryRoot: string; waveDir: string; timeline: Timeline; upgradeFrom?: string; + redeployWaveId?: string }): Promise { const temporaryRoot = await createRunnerE2ETemporaryRoot(); const home = path.join(temporaryRoot, "home"); const paths: SupervisorPaths = { temporaryRoot, home, configPath: path.join(home, "instances", "default", "config.json"), serverLogPath: path.join(input.waveDir, "server.log") }; const port = await reserveRunnerE2EServerPort(); - const supervisor = new ChaosSupervisor(input.repositoryRoot, port, paths, input.timeline, input.upgradeFrom ?? null); + const supervisor = new ChaosSupervisor(input.repositoryRoot, port, paths, input.timeline, input.upgradeFrom ?? null, + input.redeployWaveId ?? null); input.timeline.add("supervisor_created", { temporaryRoot, port, ...(input.upgradeFrom ? { upgradeFrom: input.upgradeFrom, upgradeFromSha: checkoutSha(input.upgradeFrom) } : {}) }); return supervisor; @@ -241,6 +248,8 @@ export class ChaosSupervisor { PAPERCLIP_IN_WORKTREE: "false", ...waveServerUrlEnvironment(this.port), ...extraEnvironment, + // K15: the generation's emulated host name and Railway deployment identity; the volume is the instance home. + ...(this.redeploy ? redeployEnvironment(this.redeploy.identity, home) : {}), }; const environment = buildPaperclipServerEnvironment(source, overrides); const workspaceStorage = extraEnvironment.PAPERCLIP_STORAGE_PROVIDER === "s3" @@ -257,7 +266,9 @@ export class ChaosSupervisor { const control = this.crashPointControl; const env = control ? { ...this.environment, PAPERCLIP_CRASH_POINT_CONTROL: control.controlPath, PAPERCLIP_CRASH_POINT_RECEIPT: control.receiptPath } : this.environment; - const child = spawn(process.execPath, runnerE2ETypeScriptProcessArgs(root, entry, ["onboard", "--yes", "--run"]), + const args = runnerE2ETypeScriptProcessArgs(root, entry, ["onboard", "--yes", "--run"]); + // K15 waves: the emulated host name of the serving deploy generation (redeploy.ts). + const child = spawn(process.execPath, this.redeploy ? redeployNodeArgs(args) : args, { cwd: root, env, stdio: ["ignore", "pipe", "pipe"], detached: runnerE2EServerDetached }); this.child = child; const window = this.trackWindow(child, "primary"); @@ -484,6 +495,8 @@ export class ChaosSupervisor { receipt.restartedAt = Date.now(); // K14: the replacement is the current build, on the same database and instance directory. if (kind === "K14") receipt.upgrade = await this.switchToCurrentBuild(receipt.faultId); + // K15: the replacement is the next deploy: a new process space and deployment id on the same volume. + if (kind === "K15") receipt.redeploy = this.advanceDeploy(receipt.faultId); this.timeline.add("fault_restarting", { faultId: receipt.faultId }); return this.spawnServer(); }, @@ -668,6 +681,19 @@ export class ChaosSupervisor { throw new Error(`Second server did not report ready within ${READY_TIMEOUT_MS}ms`); } + /** K15: move the next server to the next deploy generation (redeploy.ts). */ + private advanceDeploy(faultId: string): NonNullable { + if (!this.redeploy || !this.environment) throw new Error("K15 needs a redeploy wave (ChaosSupervisor.create redeployWaveId)"); + const from = this.redeploy.identity; + const to = nextRedeployIdentity(this.redeploy.waveId, from); + this.redeploy.identity = to; + Object.assign(this.environment, redeployEnvironment(to, this.paths.home)); + const receipt = redeployReceipt(from, to); + this.timeline.add("redeploy_switched", { faultId, ...receipt }); + this.log.write(`\n[restart-chaos] ${faultId} K15 redeploy ${from.hostname}/${from.deploymentId} -> ${to.hostname}/${to.deploymentId}\n`); + return receipt; + } + /** * K14: move the server from the older build to this checkout. Only the first K14 switches; a later * one restarts the current build (recorded with `switched: false`). diff --git a/tests/restart-chaos/types.ts b/tests/restart-chaos/types.ts index 58d82c4fd65..0dee982800e 100644 --- a/tests/restart-chaos/types.ts +++ b/tests/restart-chaos/types.ts @@ -6,11 +6,13 @@ import type { TimeFaultRecord } from "./time-faults.js"; /** * K14 (upgrade mid-run): a graceful stop, then the replacement starts from the current build (`--upgrade-from`). + * K15 (redeploy, redeploy.ts): a graceful stop, then the replacement starts in a new emulated process space with a new + * Railway-shaped deployment id on the same volume, as a hosted deploy replaces the server's container. * TM1–TM3 (time faults, time-faults.ts): freeze the server, sleep with aged rows, or an aged outage. * RR1–RR3 (repeated restarts, repeated-restarts.ts): a K1, then more restarts while the replacement recovers. * MS1–MS3 (two servers, one database, multi-server.ts): a second server beside the first. */ -export const FAULT_KINDS = ["K1", "K2", "K4", "K6", "K14", "TM1", "TM2", "TM3", "RR1", "RR2", "RR3", "MS1", "MS2", "MS3"] as const; +export const FAULT_KINDS = ["K1", "K2", "K4", "K6", "K14", "K15", "TM1", "TM2", "TM3", "RR1", "RR2", "RR3", "MS1", "MS2", "MS3"] as const; export type FaultKind = (typeof FAULT_KINDS)[number]; /** The shortest seeded K4 outage (scheduler.ts K4_HOLD_RANGE_MS), also the K4 hold after a provider fault. */ export const K4_MIN_HOLD_MS = 120_000; @@ -25,8 +27,9 @@ export type TaskFaultKind = FaultKind | "K13" | "K0" | ProviderFaultKind; * G1: an approval-gated action across a restart. H1: a budget hard stop crossed mid-run with a restart (its own wave). * Q1: a saved question (question-handoff.ts). Q2, Q3: journeys.ts. * L1: high-output, high-accounting run for database contention (contention.ts). + * F1: an absolute symlink pointing out of the repository workspace, kept at rest (staging save-back class F). */ -export const WORKLOAD_IDS = ["A1", "B1", "B5", "C1", "M1", "G1", "H1", "R1", "S1", "Q1", "L1", "Q2", "Q3"] as const; +export const WORKLOAD_IDS = ["A1", "B1", "B5", "C1", "M1", "G1", "H1", "R1", "S1", "Q1", "L1", "Q2", "Q3", "F1"] as const; export type WorkloadId = (typeof WORKLOAD_IDS)[number]; export const ADAPTER_IDS = ["codex", "claude", "opencode"] as const; @@ -281,6 +284,8 @@ export interface FaultReceipt { crashPoint?: { name: string; hit: number; pid: number; token?: string }; /** K14: the build the stopped server ran and the build its replacement runs. */ upgrade?: { fromRoot: string; fromSha: string | null; toRoot: string; toSha: string | null; switched: boolean }; + /** K15: the deploy generation, emulated host name and deployment id before and after. */ + redeploy?: ReturnType; /** TM1–TM3: what was frozen and which rows were aged. */ timeFault?: TimeFaultRecord; /** RR1–RR3: every stop and replacement of the sequence, the first kill included. */ diff --git a/tests/restart-chaos/workloads.ts b/tests/restart-chaos/workloads.ts index 4e01eb612bb..fd622ca82a8 100644 --- a/tests/restart-chaos/workloads.ts +++ b/tests/restart-chaos/workloads.ts @@ -41,6 +41,10 @@ const briefMarker = (nonce: string) => `CHAOS-${nonce}`; const followUpMarker = (nonce: string) => `FOLLOWUP-${nonce}`; const continueMarker = (nonce: string) => `CONTINUE-${nonce}`; const notesFile = (nonce: string) => `NOTES-${nonce}.md`; +/** F1: the absolute symlink the agent creates and keeps in the repository root. */ +export const f1LinkName = (nonce: string) => `hosts-link-${nonce}`; +/** F1: an `ls -l` line for that link: a symlink (`l` mode) naming the link and its absolute target. */ +export const f1LinkListing = (nonce: string) => new RegExp(`^l\\S*\\s.*\\s${f1LinkName(nonce)} -> /etc/hosts$`); const benchFile = (nonce: string) => `bench-result-${nonce}.txt`; const benchRecord = (nonce: string) => `.bench/run-${nonce}.txt`; const r1Module = (nonce: string) => `packages/shared/src/chaos/slug-${nonce}.ts`; @@ -319,6 +323,37 @@ export const workloadDefinitions: Record = { ]); }, }, + F1: { + // Staging class F (doc/plans/2026-11-11-staging-failures-vs-chaos-coverage.md): a remote save-back refused + // an absolute symlink (`remote_workspace_archive_unsafe_symlink`), exhausted its retries and left the task + // blocked. Agents create such links in ordinary work (tool caches, `node_modules/.bin`). The oracle expects + // the task to finish with its result saved, with no Retry; how the link itself is saved is the product's choice. + id: "F1", + label: "Absolute symlink kept in the repository workspace", + usesRepository: true, + fireWindowMs: [20_000, 90_000], + budgetMs: 12 * 60_000, + title: nonce => `Chaos F1 workspace link ${nonce}`, + description: nonce => [ + "Work in this task's repository workspace (a small Python CLI called chaoscli).", + `Run \`ln -s /etc/hosts ${f1LinkName(nonce)}\` in the repository root to create a symbolic link, and keep it.`, + `Create \`${notesFile(nonce)}\` in the repository root. Its first line is exactly \`F1-${nonce}\`.`, + `Its second line is the exact output of \`ls -l ${f1LinkName(nonce)}\`, run after you created the link.`, + "Do not change any other file and do not run ./bench.sh. Then mark this task done.", + ].join("\n"), + collect: { documents: [], files: nonce => [notesFile(nonce)], commands: [] }, + grade(nonce, artifacts) { + const lines = (artifacts.files[notesFile(nonce)] ?? "").split(/\r?\n/).map(line => line.trim()).filter(Boolean); + return result([ + statusCheck(artifacts), + { name: "workspace_located", ok: artifacts.workspacePath !== null }, + { name: "notes_file", ok: lines[0] === `F1-${nonce}` }, + // Proof the absolute link was in the workspace before the save-back: the agent's own `ls -l` output, saved + // with the notes file. Best-effort against an agent that invents it; how the link itself is saved is not graded. + { name: "link_listed", ok: f1LinkListing(nonce).test(lines[1] ?? ""), detail: JSON.stringify((lines[1] ?? "").slice(0, 160)) }, + ]); + }, + }, R1: { id: "R1", label: "Code change in a Paperclip clone", From 06af074452042750c7a1c3a614c417dbf1a0fd06 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:10:48 -0600 Subject: [PATCH 13/38] fix(native): deliver the retry after a failed native turn, once per chain (#20681) 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 > - The native runtime decides a task's next status after each run, through the status arbiter and the status-decision committer > - When a native turn fails without a classified provider error, the arbiter keeps the task's status and asks for one retry (`schedule_retry`) > - The native-status wake dispatcher refused that retry wake, because its provenance check accepted only `enqueue_continuation` effects > - So the task stayed `in_progress` with no live run, no queued wake and no visible cause, until a person noticed it > - This pull request lets the dispatcher accept the committed retry effect, keeps the retry on its chat route, and limits the automatic continuation to one per chain > - The benefit is that a failed turn always ends with either queued work or a blocked task with a working Retry ## Linked Issues or Issue Description **What happened?** A native run that ends with a failed turn and no classified provider error leaves its task stranded. Examples: an OpenCode server that the sandbox killed with SIGKILL during a turn (`opencode_server_exited`), or an OpenCode turn that ended without an answer (`opencode_empty_response`). The run's accepted result is finalized as `run_failed_partial_evidence_preserved`. The committer queues a `schedule_retry` wake. The dispatcher then skips the wake with `chat_control_recovery_proof_unresolved`. The task stays `in_progress` with no run, no wake and no blocker. **Steps to reproduce** 1. Run a native task. Make the provider turn fail with `opencode_server_exited` or `opencode_empty_response` and an accepted `needs_review` result. 2. Finalize the run. 3. Run the native-status wake dispatcher. 4. See that the retry wake and its dispatch receipt are `skipped`, and that no run starts. **Expected behavior** The task gets its automatic continuation. If that continuation fails the same way, the task is blocked with a clear board blocker and a Retry that starts a new run. **Paperclip version or commit** `origin/master` at c444da7d05. **Additional context** The task stays `in_progress` for hours with no owner. On a staging deployment, two tasks stayed in this state for more than 7 and 11 hours. ## What Changed - `server/src/services/chat-control-recovery-stop.ts`: the native-parent proof accepts the `schedule_retry` effect, as well as `enqueue_continuation`, when the effect targets the wake intent. Other effect kinds (for example `notify_owner`) are not changed. The other checks (applied decision, delivered effect, same company, task and agent) do not change. - `server/src/services/native-runtime/status-arbiter.ts`: new input `failedTurnContinuationUsed`. When it is true, a failed run is decided as `native_run_failed_continuation_exhausted`: the task is blocked with a board blocker and no wake. New constants `NATIVE_RUN_FAILED_RETRY_CAUSE` and `NATIVE_RUN_FAILED_CONTINUATION_EXHAUSTED_ACTION`. - `server/src/services/native-runtime/native-failed-turn-continuation.ts` (new): `isFailedTurnContinuationRun` reads the run's dispatcher-set `nativeStatusWakeIntentId` and proves from the intent row (company, agent, task, committer actor, `retryCause`) that the run is the automatic continuation of a failed turn. A copied or unknown id does not count. - `server/src/services/native-runtime/native-run-finalizer.ts`: passes `failedTurnContinuationUsed` to the arbiter for failed runs that the run still owns; the committer rechecks that ownership under the issue lock (`requireProviderFailureOwner`). - `server/src/services/native-runtime/native-continuation-delivery.ts`: the failed-turn retry keeps the failed run as its chat conversation source, so its answer reaches the original chat. - `doc/execution-semantics.md`: documents the retry wake, its provenance and the one-continuation bound. - New test `native-failed-turn-continuation.integration.test.ts`. ## Verification - `cd server && npx vitest run src/services/native-runtime/native-failed-turn-continuation.integration.test.ts` - RED on `origin/master` (c444da7d05): the dispatcher reports `dispatched: 0` and the wake is skipped with `chat_control_recovery_proof_unresolved`. - GREEN with this change: for both `opencode_server_exited` and `opencode_empty_response`, the dispatcher starts one continuation run. When that continuation fails the same way, the task is blocked with the board blocker, no new wake is queued, and the task Retry is accepted and starts a new run. A copied wake id does not exhaust the continuation. - Related suites pass: `status-arbiter.test.ts`, `native-provider-failure.integration.test.ts`, `heartbeat-dependency-scheduling.test.ts`, `chat-control-admission-retry.test.ts`. - `npx tsc --noEmit -p server` passes. - `pnpm verify` selects broad verification (exit 2) because `doc/execution-semantics.md` changed. Required CI supplies that coverage. ## Risks - Behavior change: a failed native turn now gets the automatic continuation that the arbiter already requested. That continuation is a new run of the same task, with the normal admission gates. It does not replay the failed turn. - The continuation is bounded to one per chain, so a deterministic failure cannot make a wake loop. - Tasks that are already stranded by the old behavior keep their skipped wake. Their task Retry still works. - Upgrade safety: an old pending `schedule_retry` intent is accepted by the new dispatcher. A run that started before this change has no proven intent, so it gets one continuation. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, through Claude Code with tool use (shell, file edit, read-only API access). Extended reasoning was used. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- doc/execution-semantics.md | 2 + .../services/chat-control-recovery-stop.ts | 8 +- .../native-continuation-delivery.ts | 22 ++- ...iled-turn-continuation.integration.test.ts | 158 ++++++++++++++++++ .../native-failed-turn-continuation.ts | 36 ++++ .../native-runtime/native-run-finalizer.ts | 6 + .../services/native-runtime/status-arbiter.ts | 24 ++- .../status-decision-committer.ts | 3 +- 8 files changed, 251 insertions(+), 8 deletions(-) create mode 100644 server/src/services/native-runtime/native-failed-turn-continuation.integration.test.ts create mode 100644 server/src/services/native-runtime/native-failed-turn-continuation.ts diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index a454d073ee1..e683dead6d6 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -1579,6 +1579,8 @@ An explicit recovery action is a typed liveness repair path for a source issue. A terminal native failure can retain a result accepted before checkpoint or cleanup failed. That result is historical evidence, not a live controller. New user input may start a fresh turn after the controller and execution environment have stopped and ordinary admission checks pass. Preserve the failed run, its result, and its recovery budget. Do not commit the old result, infer action outcomes, or replay the failed turn. A message saved while cleanup is pending must be reconsidered after verified cleanup and delivered once. External chat messages retain their original inbound action, wake receipt and actor. Cleanup delegates reconsideration to the live inbound owner, which revalidates the endpoint, conversation generation, principal and exact saved source before normal admission. The existing stranded-queue sweep uses the same owner after a lost callback or restart; it cannot substitute a generic assignment wake. A rejected source must not prevent other saved messages from being reconsidered. Admission must consume its deferred receipt in the same transaction that creates the new run, including in agent chat, where later messages keep their separate turns. Completing that run must not promote the consumed receipt again. Workspace-export repair retains its separate saved-result recovery path. +When a native run's accepted result reports a failed turn without a classified provider error (`run_failed_partial_evidence_preserved`, for example an OpenCode server that was killed or ended without an answer), the status decision keeps the task's status and queues one same-agent `schedule_retry` wake. The wake dispatcher accepts that committed decision effect as the continuation's provenance, exactly like an `enqueue_continuation` effect, so the task always has queued work, and the retry answers the same external chat conversation. The automatic continuation is used once per chain: if the run started from that wake fails the same way, the decision is `native_run_failed_continuation_exhausted`, the task is blocked with a board blocker, and the visible Retry starts the next attempt. + A host-verified workspace copy-back receipt also permits new user input after a native coordinator reaches terminal failure with a retained result. The receipt must bind the company, task, run, allocation, descriptor and final file digest. diff --git a/server/src/services/chat-control-recovery-stop.ts b/server/src/services/chat-control-recovery-stop.ts index dff28753fcb..900a752b260 100644 --- a/server/src/services/chat-control-recovery-stop.ts +++ b/server/src/services/chat-control-recovery-stop.ts @@ -92,6 +92,9 @@ export type ChatControlRecoveryStop = sourceRunId: string; }; +/** Status-decision effects whose target is the native-status wake intent. */ +const NATIVE_STATUS_WAKE_EFFECT_KINDS = ["enqueue_continuation", "schedule_retry"]; + /** A dispatched native continuation inherits only its committed decision's * source run. Arbitrary payload.nativeDecisionId / context.source is not proof. */ export async function readChatControlNativeParent( @@ -137,7 +140,10 @@ export async function readChatControlNativeParent( eq(statusDecisionEffects.companyId, scope.companyId), eq(statusDecisionEffects.issueId, scope.issueId), eq(statusDecisionEffects.decisionId, statusDecisions.id), - eq(statusDecisionEffects.effectKind, "enqueue_continuation"), + // A committed continuation or failed-turn retry effect that targets + // this intent is its proof. Refusing the retry stranded the task + // with no queued work. + inArray(statusDecisionEffects.effectKind, NATIVE_STATUS_WAKE_EFFECT_KINDS), eq(statusDecisionEffects.targetType, "agent_wakeup_request"), eq(statusDecisionEffects.targetId, intent.id), eq(statusDecisionEffects.deliveryState, "delivered"), diff --git a/server/src/services/native-runtime/native-continuation-delivery.ts b/server/src/services/native-runtime/native-continuation-delivery.ts index ee468b9dc5d..f5510581e97 100644 --- a/server/src/services/native-runtime/native-continuation-delivery.ts +++ b/server/src/services/native-runtime/native-continuation-delivery.ts @@ -2,6 +2,7 @@ import { agentWakeupRequests, heartbeatRuns, statusDecisions, statusDecisionEffe import { and, eq, inArray, isNull, ne, or, sql } from "drizzle-orm"; import { alias } from "drizzle-orm/pg-core"; import { boundRunIssueIdSql } from "../run-task-binding.js"; +import { NATIVE_RUN_FAILED_RETRY_CAUSE } from "./status-arbiter.js"; /** Recover conversation provenance from a committed continuation, never from * provider-supplied source IDs or the mere presence of a chat on the task. */ @@ -34,18 +35,29 @@ export async function readNativeContinuationSource( )) .innerJoin(statusDecisionEffects, and( eq(statusDecisionEffects.companyId, binding.companyId), eq(statusDecisionEffects.issueId, binding.issueId), - eq(statusDecisionEffects.effectKind, "enqueue_continuation"), eq(statusDecisionEffects.targetType, "agent_wakeup_request"), sql`${statusDecisionEffects.targetId} = ${agentWakeupRequests.id}::text`, eq(statusDecisionEffects.deliveryState, "delivered"), - sql`${statusDecisionEffects.payload}->>'continuationKind' = 'same_agent'`, - sql`${agentWakeupRequests.payload}->>'continuationKind' = 'same_agent'`, + or(and( + eq(statusDecisionEffects.effectKind, "enqueue_continuation"), + sql`${statusDecisionEffects.payload}->>'continuationKind' = 'same_agent'`, + sql`${agentWakeupRequests.payload}->>'continuationKind' = 'same_agent'`, + ), and( + // The one automatic retry after a failed turn answers the same chat. + eq(statusDecisionEffects.effectKind, "schedule_retry"), + sql`${agentWakeupRequests.payload}->>'retryCause' = ${NATIVE_RUN_FAILED_RETRY_CAUSE}`, + )), )) .innerJoin(statusDecisions, and( eq(statusDecisions.id, statusDecisionEffects.decisionId), eq(statusDecisions.companyId, binding.companyId), eq(statusDecisions.issueId, binding.issueId), eq(statusDecisions.applicationState, "applied"), - eq(statusDecisions.reasonCode, "live_continuation_registered"), - sql`${agentWakeupRequests.idempotencyKey} = 'native-status:' || ${statusDecisions.id}::text || ':continuation'`, + or(and( + eq(statusDecisions.reasonCode, "live_continuation_registered"), + sql`${agentWakeupRequests.idempotencyKey} = 'native-status:' || ${statusDecisions.id}::text || ':continuation'`, + ), and( + eq(statusDecisions.reasonCode, "run_failed_partial_evidence_preserved"), + sql`${agentWakeupRequests.idempotencyKey} = 'native-status:' || ${statusDecisions.id}::text || ':retry'`, + )), sql`${agentWakeupRequests.payload}->>'nativeDecisionId' = ${statusDecisions.id}::text`, )) .innerJoin(source, and( diff --git a/server/src/services/native-runtime/native-failed-turn-continuation.integration.test.ts b/server/src/services/native-runtime/native-failed-turn-continuation.integration.test.ts new file mode 100644 index 00000000000..8bd98a0bb92 --- /dev/null +++ b/server/src/services/native-runtime/native-failed-turn-continuation.integration.test.ts @@ -0,0 +1,158 @@ +import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { agents, agentWakeupRequests, companies, companyMemberships, completionContracts, createDb, heartbeatRuns, issues, nativeRunFinalizations, statusDecisions } from "@paperclipai/db"; +import type { ControlPlanePort, NativeExecutionInputV1, PrpEvent, PrpTerminalState } from "@paperclipai/paperclip-runner"; +import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; +import { CONTROL_PLANE_CONFORMANCE_RESULT } from "../../vendor/paperclip-runner/testing.js"; + +const provider = vi.hoisted(() => ({ execute: vi.fn() })); +vi.mock("../../vendor/paperclip-runner/index.js", async (importOriginal) => ({ + ...(await importOriginal()), + executeNativeSession: provider.execute, +})); + +import { executePaperclipNativeSession } from "./native-session-executor.js"; +import { buildNativeCompletionContract } from "./completion-contracts.js"; +import { prepareNativeHeartbeatRun } from "./prepare-native-run.js"; +import { finalizeNativeRun } from "./native-run-finalizer.js"; +import { readNativeContinuationSource } from "./native-continuation-delivery.js"; +import { NATIVE_RUN_FAILED_CONTINUATION_EXHAUSTED_ACTION } from "./status-arbiter.js"; +import { heartbeatService } from "../heartbeat.js"; +import { requestTaskRetry } from "../task-retry.js"; + +type FailureCode = "opencode_server_exited" | "opencode_empty_response"; + +// Seen on a staging deployment: an OpenCode turn +// failed (its server was killed, or it ended without an answer). The accepted +// result kept the task in_progress and the arbiter scheduled a retry, but the +// dispatcher refused that wake (`chat_control_recovery_proof_unresolved`), so +// the task sat for hours with no owner and no queued work. +describe("native failed-turn continuation", () => { + let temporary: Awaited>; + let db: ReturnType; + const companyId = randomUUID(); + const agentId = randomUUID(); + + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("native-failed-turn-"); + db = createDb(temporary.connectionString); + await db.insert(companies).values({ id: companyId, name: "Native failed turn", issuePrefix: "NFT" }); + await db.insert(agents).values({ id: agentId, companyId, name: "OpenCode agent", status: "active", adapterType: "paperclip_runner", adapterConfig: { provider: "opencode", model: "openrouter/test-model" } }); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "board-user", status: "active", membershipRole: "member" }); + }); + afterAll(async () => { await temporary?.cleanup(); }); + + async function failTurn(issueId: string, code: FailureCode, context: Record = {}, dispatchedFrom?: string) { + const runId = randomUUID(); + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + // A dispatched continuation carries the dispatcher's own receipt for its intent. + const [receipt] = dispatchedFrom ? await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "automation", + triggerDetail: "system", reason: "issue_status_changed", status: "claimed", requestedByActorType: "system", + requestedByActorId: `native-status-wake-dispatch:${dispatchedFrom}`, payload: { issueId } }).returning() : []; + const [run] = await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", runtimeMode: "native", nativeIssueId: issueId, responsibleUserId: "board-user", invocationSource: "automation", triggerDetail: "system", wakeupRequestId: receipt?.id ?? null, contextSnapshot: { issueId, ...context } }).returning(); + if (receipt) await db.update(agentWakeupRequests).set({ runId }).where(eq(agentWakeupRequests.id, receipt.id)); + await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId)); + const native = await prepareNativeHeartbeatRun({ db, run, issue, environmentLeaseId: randomUUID() }); + const [contract] = await db.select().from(completionContracts).where(eq(completionContracts.issueId, issueId)); + const completionInput = buildNativeCompletionContract(issue, { revision: contract.revision }); + await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "observed" }); + const execution: NativeExecutionInputV1 = { + schema: "paperclip.native-execution-input.v1", + binding: { companyId, runId, issueId, agentId, executionWorkspaceId: runId }, + provider: { kind: "opencode", model: "openrouter/test-model" }, + task: { identifier: issueId, title: issue.title, description: null, prompt: "Review the PR.", workMode: "standard" }, + workspace: { cwd: "/tmp", repoUrl: null, repoRef: null, branchName: null }, + session: { normalizedSessionId: native.normalizedSessionId, driverKind: "opencode_server", protocolVersion: 1, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } }, + completionContract: { id: contract.id, sha256: contract.canonicalSha256, schemaVersion: "paperclip.completion-contract.v1", contract: completionInput }, + interactionResponses: [], credentialBindings: [], + }; + await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: execution } }).where(eq(heartbeatRuns.id, runId)); + const event: PrpEvent = { + schema: "paperclip.prp.event.v1", runId, normalizedSessionId: native.normalizedSessionId, + turnId: native.turnId, sourceInstanceId: native.runnerInstanceId, sourceEventId: "turn-terminal", sourceSeq: 1, + sourceKind: "runner", eventType: "turn.failed", schemaVersion: 1, priority: 0, emittedAt: new Date().toISOString(), + payload: code === "opencode_server_exited" + ? { status: "failed", error: { code, message: "OpenCode stopped while the turn was running.", opencodeFailure: { kind: "server_exited", signal: "SIGKILL", connectionError: "ECONNREFUSED" } } } + : { status: "failed", error: { code, message: "OpenCode ended without a final answer.", retryable: false } }, + }; + const terminal: PrpTerminalState = { schema: "paperclip.prp.terminal.v1", turnTerminalState: "failed", runTerminalState: "failed", reportedWorkDisposition: "needs_review" }; + const result = { ...CONTROL_PLANE_CONFORMANCE_RESULT, reportedWorkDisposition: "needs_review" as const, + completionClaim: { ...CONTROL_PLANE_CONFORMANCE_RESULT.completionClaim, contractRevision: completionInput.revision } }; + const openInput = { identity: { companyId, issueId, runId, agentId, sessionId: native.normalizedSessionId }, backendKind: "mock" as const, sourceInstanceId: native.runnerInstanceId }; + provider.execute.mockReset().mockImplementation(async (options: { controlPlane: ControlPlanePort }) => { + await options.controlPlane.openRun(openInput); + await options.controlPlane.appendEvent(event); + await options.controlPlane.completeRun({ result, terminal, turnId: native.turnId }); + return { result, terminal, turnId: native.turnId, normalizedSessionId: native.normalizedSessionId, providerSessionId: "fixture-provider-session", driverKind: execution.session.driverKind, driverVersion: "fixture", nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null }; + }); + await executePaperclipNativeSession({ db, execution, runnerInstanceId: native.runnerInstanceId, backend: { + descriptor: async () => { throw new Error("Unexpected provider call"); }, + openSession: async () => { throw new Error("Unexpected provider call"); }, + } }); + await finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true }); + const [failedRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(failedRun.status).toBe("failed"); + const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId)); + return { runId, decision }; + } + + const issueWakes = async (issueId: string) => (await db.select().from(agentWakeupRequests) + .where(eq(agentWakeupRequests.companyId, companyId))).filter(wake => wake.payload?.issueId === issueId); + + it.each(["opencode_server_exited", "opencode_empty_response"] as const)("continues the task once after %s, then hands it to Retry", async (code) => { + const issueId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Review a PR", status: "in_progress", workMode: "standard", assigneeAgentId: agentId, createdByUserId: "board-user", responsibleUserId: "board-user" }); + const first = await failTurn(issueId, code); + expect(first.decision.reasonCode).toBe("run_failed_partial_evidence_preserved"); + + const heartbeat = heartbeatService(db); + expect(await heartbeat.dispatchPendingNativeStatusWakeups({ companyId })).toMatchObject({ dispatched: 1 }); + const wakes = await issueWakes(issueId); + expect(wakes.filter(wake => wake.status === "skipped")).toEqual([]); + const intent = wakes.find(wake => wake.requestedByActorId === "native-status-committer")!; + expect(intent.payload).toMatchObject({ retryCause: "native_run_failed" }); + const [continuation] = (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId))) + .filter(r => r.id !== first.runId && r.contextSnapshot?.issueId === issueId); + expect(continuation?.contextSnapshot?.nativeStatusWakeIntentId).toBe(intent.id); + expect(["queued", "running"]).toContain(continuation.status); + // The continuation keeps the failed run as its conversation source. + expect(await readNativeContinuationSource(db, { companyId, issueId, runId: continuation.id })).toBe(first.runId); + // The fixture cannot launch a real runner; let the dispatched run settle. + await heartbeat.drainActiveRunExecutions(); + const [task] = await db.select().from(issues).where(eq(issues.id, issueId)); + expect(task.assigneeAgentId).toBe(agentId); + + // The continuation's own turn fails the same way: no second automatic + // wake, and a board blocker whose Retry restarts the work. + await db.update(issues).set({ status: "in_progress", executionRunId: null, checkoutRunId: null }).where(eq(issues.id, issueId)); + const before = (await issueWakes(issueId)).length; + const second = await failTurn(issueId, code, { nativeStatusWakeIntentId: intent.id }, intent.id); + expect(second.decision).toMatchObject({ reasonCode: "native_run_failed_continuation_exhausted", toStatus: "blocked" }); + await heartbeat.dispatchPendingNativeStatusWakeups({ companyId }); + expect((await issueWakes(issueId)).length).toBe(before + 1); // only the fixture dispatch receipt + const [blocked] = await db.select().from(issues).where(eq(issues.id, issueId)); + expect(blocked).toMatchObject({ status: "blocked", unblockDescriptor: { owner: "board", action: NATIVE_RUN_FAILED_CONTINUATION_EXHAUSTED_ACTION } }); + // The visible Retry is accepted and starts a new run of the task. + const receipt = await requestTaskRetry({ db, companyId, issueId, actorId: "board-user", actorSource: "session", + idempotencyKey: randomUUID(), observedRunId: second.runId }); + expect(receipt).toMatchObject({ accepted: true, stale: false }); + await heartbeat.resumeTaskRetry(companyId, receipt.requestId!); + const retried = (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId))) + .filter(r => r.contextSnapshot?.issueId === issueId && r.contextSnapshot?.taskRetryRequestId === receipt.requestId); + expect(retried).toHaveLength(1); + await heartbeat.drainActiveRunExecutions(); + }, 120_000); + + it("does not treat a copied retry intent id as a used continuation", async () => { + const issueId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Review another PR", status: "in_progress", workMode: "standard", assigneeAgentId: agentId, createdByUserId: "board-user", responsibleUserId: "board-user" }); + const first = await failTurn(issueId, "opencode_empty_response"); + expect(first.decision.reasonCode).toBe("run_failed_partial_evidence_preserved"); + const intent = (await issueWakes(issueId)).find(wake => wake.requestedByActorId === "native-status-committer")!; + // A real intent id copied into a run that the dispatcher did not start. + await db.update(issues).set({ status: "in_progress", executionRunId: null, checkoutRunId: null }).where(eq(issues.id, issueId)); + const copied = await failTurn(issueId, "opencode_empty_response", { nativeStatusWakeIntentId: intent.id }); + expect(copied.decision.reasonCode).toBe("run_failed_partial_evidence_preserved"); + }, 120_000); +}); diff --git a/server/src/services/native-runtime/native-failed-turn-continuation.ts b/server/src/services/native-runtime/native-failed-turn-continuation.ts new file mode 100644 index 00000000000..4ba427e28ec --- /dev/null +++ b/server/src/services/native-runtime/native-failed-turn-continuation.ts @@ -0,0 +1,36 @@ +import { and, eq, sql } from "drizzle-orm"; +import { agentWakeupRequests, type Db, type heartbeatRuns } from "@paperclipai/db"; +import { NATIVE_RUN_FAILED_RETRY_CAUSE } from "./status-arbiter.js"; + +/** + * True when this run was dispatched from the committer's `schedule_retry` wake + * for an earlier failed turn. The intent id is set by the native-status wake + * dispatcher, and the intent row itself proves the retry cause, so provider + * output or a copied context cannot claim or hide the used continuation. + */ +export async function isFailedTurnContinuationRun( + db: Pick, + run: Pick, + issueId: string, +): Promise { + const intentId = run.contextSnapshot?.nativeStatusWakeIntentId; + if (typeof intentId !== "string" || !/^[0-9a-f-]{36}$/i.test(intentId) || !run.wakeupRequestId) return false; + // The run's own dispatch receipt must be the one the dispatcher created for + // this intent, so a copied intent id on another run proves nothing. + const [dispatch] = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, run.companyId), + eq(agentWakeupRequests.id, run.wakeupRequestId), + eq(agentWakeupRequests.runId, run.id), + eq(agentWakeupRequests.requestedByActorId, `native-status-wake-dispatch:${intentId}`), + )).limit(1); + if (!dispatch) return false; + const [intent] = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, run.companyId), + eq(agentWakeupRequests.agentId, run.agentId), + eq(agentWakeupRequests.id, intentId), + eq(agentWakeupRequests.requestedByActorId, "native-status-committer"), + sql`${agentWakeupRequests.payload}->>'issueId' = ${issueId}`, + sql`${agentWakeupRequests.payload}->>'retryCause' = ${NATIVE_RUN_FAILED_RETRY_CAUSE}`, + )).limit(1); + return Boolean(intent); +} diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index 74e5b1faf37..69b6ca12c3a 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -29,6 +29,7 @@ import { isNativePlanWaitResult, readNativePlanWait } from "./native-plan-wait.j import { hasPendingNativeChildCompletion } from "./native-child-completion-delivery.js"; import { settleExternalConversation } from "../slack-conversation-lifecycle.js"; import { executionFailureRetryCount } from "../execution-recovery-attempt.js"; +import { isFailedTurnContinuationRun } from "./native-failed-turn-continuation.js"; import { readPersistedNativeFailureEvidence } from "./native-provider-failure-evidence.js"; import { explainFailedRun, NATIVE_RUN_FAILED_UNEXPLAINED } from "./native-run-failure-explanation.js"; import { dismissAutomaticCompletionReviews } from "./automatic-completion-reviews.js"; @@ -1655,6 +1656,10 @@ export async function finalizeNativeRun(input: { providerOverloaded: providerFailure?.errorCode === "native_provider_overloaded" && ownsProviderFailureDecision, providerFailureSuperseded: providerFailure?.errorCode === "native_provider_overloaded" && !ownsProviderFailureDecision, failureRetryCount: executionFailureRetryCount(run), + // Only the task's current owner may turn its own failed continuation + // into a blocker; the committer rechecks that under the issue lock. + failedTurnContinuationUsed: terminalState === "failed" && ownsProviderFailureDecision && !reviewContext + && await isFailedTurnContinuationRun(input.db, run, authoritativeIssue.id), ...(reviewContext ? { nativeReviewOutcome: nativeReview ? nativeReview.interaction.status === "pending" ? "pending" as const : "resolved" as const : "stale" as const } : {}), @@ -1799,6 +1804,7 @@ export async function finalizeNativeRun(input: { ? { agentId: run.agentId, reviewContext } : undefined, requireProviderFailureOwner: decision.reasonCode?.startsWith("native_provider_overloaded") + || decision.reasonCode === "native_run_failed_continuation_exhausted" ? { agentId: run.agentId, reviewContext } : undefined, requireBoardResponseWaitSource: decision.reasonCode === "board_response_waiting" || repairBoardResponseWait diff --git a/server/src/services/native-runtime/status-arbiter.ts b/server/src/services/native-runtime/status-arbiter.ts index 89b62d3028c..ef691a0f897 100644 --- a/server/src/services/native-runtime/status-arbiter.ts +++ b/server/src/services/native-runtime/status-arbiter.ts @@ -3,6 +3,11 @@ import { NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_CAPACITY_MAX_RETRIES, N export const NATIVE_STATUS_ARBITER_POLICY_VERSION = "phase6-v13"; +/** The automatic continuation after a failed turn is used once per chain. */ +export const NATIVE_RUN_FAILED_RETRY_CAUSE = "native_run_failed"; +export const NATIVE_RUN_FAILED_CONTINUATION_EXHAUSTED_ACTION = + "The agent's turn failed again after Paperclip continued it automatically. The saved work is kept. Check the failed run, then Retry the task."; + export type NativeAuthoritativeIssueStatus = | "backlog" | "todo" @@ -179,6 +184,11 @@ export function arbitrateNativeStatus(input: { providerOverloaded?: boolean; providerFailureSuperseded?: boolean; failureRetryCount?: number; + /** + * This run was itself the automatic continuation of an earlier failed turn. + * Another failure needs a person's Retry, never another automatic wake. + */ + failedTurnContinuationUsed?: boolean; agentId: string; priorIssueStatus: NativeAuthoritativeIssueStatus; }): NativeStatusDecision { @@ -312,6 +322,18 @@ export function arbitrateNativeStatus(input: { effects: [{ kind: "release_run_resources" }], }; } + if (input.failedTurnContinuationUsed) { + // The automatic continuation already ran and failed too. Keep the work + // and hand the next attempt to a person instead of waking again. + return { + policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION, + statusAction: "blocked", + toStatus: "blocked", + reasonCode: "native_run_failed_continuation_exhausted", + unblockDescriptor: { owner: "board", action: NATIVE_RUN_FAILED_CONTINUATION_EXHAUSTED_ACTION }, + effects: [{ kind: "bind_blocker", owner: "board", action: NATIVE_RUN_FAILED_CONTINUATION_EXHAUSTED_ACTION }], + }; + } return { policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION, statusAction: "preserve", @@ -321,7 +343,7 @@ export function arbitrateNativeStatus(input: { effects: [ { kind: "schedule_retry", - cause: "native_run_failed", + cause: NATIVE_RUN_FAILED_RETRY_CAUSE, summary: "Resume the persisted native run without opening a second provider session.", agentId: input.agentId, diff --git a/server/src/services/native-runtime/status-decision-committer.ts b/server/src/services/native-runtime/status-decision-committer.ts index 9370ad3d8a9..00143623712 100644 --- a/server/src/services/native-runtime/status-decision-committer.ts +++ b/server/src/services/native-runtime/status-decision-committer.ts @@ -1696,7 +1696,8 @@ export async function commitNativeStatusDecision(input: { if (reasonCode === "native_provider_model_rejected" && !input.requireModelRejectionOwner) { throw new Error("native_model_rejection_owner_required"); } - if (reasonCode.startsWith("native_provider_overloaded") && !input.requireProviderFailureOwner) { + if ((reasonCode.startsWith("native_provider_overloaded") || reasonCode === "native_run_failed_continuation_exhausted") + && !input.requireProviderFailureOwner) { throw new Error("native_provider_failure_owner_required"); } const publications: ActivityPublication[] = []; From b93df4ca382f49adb195d49021ebfaac309a97af Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:15:13 -0600 Subject: [PATCH 14/38] fix(chat): consume a saved chat wake whose message a completed run answered (#20689) 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 > - External chat (for example GitHub review requests) wakes the assigned agent with a saved chat message > - When the agent is already running, the chat wake is saved behind that run and released after it finishes > - The running agent often reads the new message as part of its current turn, so the message is already answered when the saved wake is released > - The release kept that chat wake anyway, removed its now-delivered message ids, and started a reviewed chat run with no message > - A reviewed chat run with no message cannot be attested, so it failed with `reviewed_chat_execution_binding_not_authorized` and the task became blocked > - This pull request treats a chat message wake like a comment wake: when a completed run already received all its messages, the saved wake is consumed > - The benefit is that a message that arrives during an active run no longer blocks the task after it was answered ## Linked Issues or Issue Description **What happened?** A GitHub chat message arrived for a task while the assigned agent's run was active. The wake was saved behind that run. The run read the message and answered it. When the run finished, the saved chat wake was still promoted. Its message ids were removed because a completed run already received them. The new run had source `chat:` and no message, so reviewed chat attestation denied it with `context_mismatch`. The run failed with `reviewed_chat_execution_binding_not_authorized`. Review-path recovery inherited the same context and failed too, and the task was blocked. **Steps to reproduce** 1. Assign a task in review to an agent that is running. 2. Deliver an external chat message for the task. The wake is saved behind the active run. 3. Let the active run receive the message as wake input and succeed. 4. Release the task's execution lock. 5. See that the saved chat wake is promoted with no message, instead of being consumed. **Expected behavior** The saved chat wake is consumed with "Queued messages were already delivered to a completed run". No new run starts. The chat does not get a "not started" notice for a message that was answered. **Paperclip version or commit** `origin/master` at 6e524d8a69. **Additional context** This was seen on a staging deployment on five runs across three tasks in one day. It is a message timing race, not a deploy or authorization problem. ## What Changed - `server/src/modules/wake-queue/adapters/postgres.ts`: a saved wake whose reason is `External chat message received` and whose payload mutation is `chat_message_received` is treated as message-only. If a completed run already received all of its messages, the release consumes it, the same as a comment wake. If any message is still unread, it is promoted as before. - `server/src/services/chat-inbound-wakeup-publications.ts`: a chat receipt consumed for that reason does not publish "This follow-up was not started". Other declines keep that notice. - `server/src/services/queued-comment-delivery.ts`: constants for the chat message wake reason and the delivered-message reason. - New test `server/src/modules/wake-queue/adapters/chat-wake-delivered.test.ts`. ## Verification - `cd server && npx vitest run src/modules/wake-queue/adapters/chat-wake-delivered.test.ts` - RED on `origin/master`: the release promotes the consumed chat wake ("Unexpected promotion of a consumed chat wake"), and the receipt resolves to a `not_started` notice. - GREEN with this change: the wake is cancelled with the delivered reason, no run starts, no "not started" notice, and a chat wake with an unread message is still promoted. - Related suites: `src/modules/wake-queue`, `heartbeat-reviewed-chat-binding.integration.test.ts`, `durable-chat-wakeup.test.ts`, `heartbeat-native-status-context.test.ts`, `external-chat-wait.integration.test.ts`, `heartbeat-held-comment-wake.test.ts`. - `npx tsc --noEmit -p server` passes. ## Risks - A chat wake that merged with another kind of wake takes the merged wake's reason and mutation. Only a wake whose current reason and mutation are both the chat message values is treated as message-only, so other merged intents keep promotion. - A visible "Your follow-up is queued." notice is not followed by a "not started" notice when the message was already answered. That matches the existing behavior when the wake is promoted. - Not changed: a separate case where messages from two different chat conversations are merged into one saved wake. That case fails with `binding_denied` and needs its own change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, through Claude Code with tool use (shell, file edit, read-only API access). Extended reasoning was used. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- .../adapters/chat-wake-delivered.test.ts | 108 ++++++++++++++++++ .../modules/wake-queue/adapters/postgres.ts | 8 +- .../wake-queue/application/use-cases.ts | 3 +- .../src/modules/wake-queue/domain/policy.ts | 3 + server/src/modules/wake-queue/index.ts | 1 + .../services/chat-channels/inbound/wakeups.ts | 7 +- .../chat-inbound-wakeup-publications.ts | 5 + server/src/services/heartbeat/queue.ts | 3 +- .../src/services/queued-comment-delivery.ts | 5 + 9 files changed, 136 insertions(+), 7 deletions(-) create mode 100644 server/src/modules/wake-queue/adapters/chat-wake-delivered.test.ts diff --git a/server/src/modules/wake-queue/adapters/chat-wake-delivered.test.ts b/server/src/modules/wake-queue/adapters/chat-wake-delivered.test.ts new file mode 100644 index 00000000000..438adc20b17 --- /dev/null +++ b/server/src/modules/wake-queue/adapters/chat-wake-delivered.test.ts @@ -0,0 +1,108 @@ +import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { agents, agentWakeupRequests, companies, createDb, heartbeatRuns, issueComments, issues } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js"; +import { createReleaseIssueExecution } from "../application/use-cases.js"; +import { createPostgresWakeQueueAdapter } from "./postgres.js"; +import { resolveInboundWakeReceipt } from "../../../services/chat-inbound-wakeup-publications.js"; +import { createDurableChatWakeupRequest } from "../../../services/durable-chat-wakeup.js"; + +const support = await getEmbeddedPostgresTestSupport(); + +// A GitHub message arrives while the agent's run is active. The wake is saved +// behind that run. The run reads the message (it is in its wake input) and +// finishes. Before this fix the saved wake was still promoted, with its message +// ids removed. A reviewed chat run with no message cannot be attested, so it +// failed with `reviewed_chat_execution_binding_not_authorized` (context_mismatch) +// and blocked the task. +describe.skipIf(!support.supported)("release of a saved chat wake whose message was delivered", () => { + let database: Awaited>; + let db: ReturnType; + let companyId: string; + let agentId: string; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("wake-chat-delivered-"); + db = createDb(database.connectionString); + const [company] = await db.insert(companies).values({ name: "Chat wake fixture", issuePrefix: "CWD" }).returning(); + const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Reviewer", adapterType: "process" }).returning(); + companyId = company.id; + agentId = agent.id; + }, 60_000); + + afterAll(async () => { + await db?.$client.end(); + await database?.cleanup(); + }); + + async function seed(delivered: boolean) { + const [issue] = await db.insert(issues).values({ companyId, title: "Review a pull request", status: "in_review", + assigneeAgentId: agentId }).returning(); + const [message] = await db.insert(issueComments).values({ companyId, issueId: issue.id, authorUserId: "chat-user", + body: "GitHub review request.", createdAt: new Date(Date.now() - 60_000), updatedAt: new Date(Date.now() - 60_000) }).returning(); + // The finishing run started after the message and received it as wake input. + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "succeeded", + invocationSource: "assignment", triggerDetail: "system", startedAt: new Date(Date.now() - 30_000), finishedAt: new Date(), + contextSnapshot: { issueId: issue.id, source: "chat:github", wakeReason: "External chat message received", + chatConversationId: randomUUID(), ...(delivered ? { wakeCommentIds: [message.id] } : { wakeCommentIds: [randomUUID()] }) }, + }).returning(); + await db.update(issues).set({ executionRunId: run.id, executionLockedAt: new Date() }).where(eq(issues.id, issue.id)); + const context = { issueId: issue.id, taskId: issue.id, source: "chat:github", wakeReason: "External chat message received", + wakeSource: "assignment", chatConversationId: randomUUID(), commentId: message.id, wakeCommentId: message.id, + wakeCommentIds: [message.id] }; + const wakeId = randomUUID(); + const { idempotencyKey } = createDurableChatWakeupRequest({ id: wakeId, companyId, agentId, issueId: issue.id, + commentId: message.id, requestedByActorType: "user", requestedByActorId: "chat-user", requestedAt: new Date(), + authorize: async () => {} }); + const [wake] = await db.insert(agentWakeupRequests).values({ id: wakeId, idempotencyKey, companyId, agentId, source: "assignment", + triggerDetail: "system", reason: "External chat message received", status: "deferred_issue_execution", + requestedByActorType: "user", requestedByActorId: "chat-user", + payload: { issueId: issue.id, mutation: "chat_message_received", wakeCommentId: message.id, _paperclipWakeContext: context }, + }).returning(); + return { issue, run, wake }; + } + + function release(unexpected: () => never) { + return createReleaseIssueExecution({ + issueLock: createPostgresWakeQueueAdapter(db, { resolveResponsibleUserId: unexpected, getRoutineEnv: unexpected, + resolveSessionBeforeForWakeup: unexpected } as never), + recovery: { escalateStrandedAssignedIssue: unexpected, escalateStrandedRecoveryIssueInPlace: unexpected } as never, + }); + } + + it("consumes the saved chat wake instead of starting a run with no message", async () => { + const { run, wake } = await seed(true); + const unexpected = vi.fn((): never => { throw new Error("Unexpected promotion of a consumed chat wake"); }); + const result = await release(unexpected)({ companyId, runId: run.id, now: new Date() }); + expect(result.outcome.kind).toBe("released"); + expect(unexpected).not.toHaveBeenCalled(); + const [saved] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake.id)); + expect(saved).toMatchObject({ status: "cancelled", runId: null, error: "Queued messages were already delivered to a completed run" }); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId)).then(rows => + rows.filter(row => row.contextSnapshot?.issueId === saved.payload?.issueId && row.id !== run.id))).toEqual([]); + }); + + it("does not report a delivered chat message as not started", async () => { + const { wake } = await seed(true); + const action = { id: wake.id, companyId, kind: "inbound_wakeup", conversationId: randomUUID(), deliveryId: randomUUID(), + principalId: randomUUID(), createdAt: wake.requestedAt, status: "processed", + payload: { version: 1, agentId, issueId: wake.payload?.issueId, commentId: wake.payload?.wakeCommentId, + requestedByActorType: "user", requestedByActorId: "chat-user" } }; + const consumed = { ...wake, status: "cancelled", error: "Queued messages were already delivered to a completed run" }; + expect(resolveInboundWakeReceipt(action as never, consumed, consumed)).toBeNull(); + // Other declines keep their notice. + const refused = { ...wake, status: "cancelled", error: "Deferred wake suppressed by active subtree pause hold" }; + expect(resolveInboundWakeReceipt(action as never, refused, refused)).toMatchObject({ state: "not_started" }); + }); + + it("still promotes a saved chat wake whose message no run has received", async () => { + const { run, wake } = await seed(false); + // Promotion reaches the host; the refusal proves the wake was not consumed. + const unexpected = vi.fn((): never => { throw new Error("promotion reached the host"); }); + await expect(release(unexpected)({ companyId, runId: run.id, now: new Date() })).rejects.toThrow("promotion reached the host"); + expect(unexpected).toHaveBeenCalled(); + const [saved] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake.id)); + expect(saved.status).not.toBe("cancelled"); + }); +}); diff --git a/server/src/modules/wake-queue/adapters/postgres.ts b/server/src/modules/wake-queue/adapters/postgres.ts index d59c9340a0a..93689a48dd1 100644 --- a/server/src/modules/wake-queue/adapters/postgres.ts +++ b/server/src/modules/wake-queue/adapters/postgres.ts @@ -19,7 +19,7 @@ import { and, asc, eq, inArray, isNull, notInArray, or, sql } from "drizzle-orm" import { readReleaseRun, type ReleaseRun } from "./release-run-read.js"; import { isGovernancePauseStop } from "../../../services/governance-pause-stop.js"; import type { Db } from "@paperclipai/db"; -import { deliveredQueuedCommentIds } from "../../../services/queued-comment-delivery.js"; +import { deliveredQueuedCommentIds, EXTERNAL_CHAT_MESSAGE_WAKE_MUTATION, EXTERNAL_CHAT_MESSAGE_WAKE_REASON } from "../../../services/queued-comment-delivery.js"; import { extractIssueReferenceIdentifiers, isUuidLike } from "@paperclipai/shared"; import { activityLog, @@ -177,7 +177,11 @@ function toDeferredWakeCandidate(row: typeof agentWakeupRequests.$inferSelect): !queuedReason || queuedReason === "issue_commented" || queuedReason === "issue_reopened_via_comment" || - queuedReason === "issue_comment_mentioned"; + queuedReason === "issue_comment_mentioned" || + // An inbound chat message wake carries only its saved messages. When a + // completed run already received them, nothing is left to start, and a + // reviewed chat run with no message cannot be attested. + (queuedReason === EXTERNAL_CHAT_MESSAGE_WAKE_REASON && payload.mutation === EXTERNAL_CHAT_MESSAGE_WAKE_MUTATION); const preservesIndependentContinuation = hasInteractionContinuationWakeContext(deferredContextSeed) || deferredContextSeed.resumeIntent === true || diff --git a/server/src/modules/wake-queue/application/use-cases.ts b/server/src/modules/wake-queue/application/use-cases.ts index 10e8c617f25..3a74a7aa2f9 100644 --- a/server/src/modules/wake-queue/application/use-cases.ts +++ b/server/src/modules/wake-queue/application/use-cases.ts @@ -1,5 +1,6 @@ import { readWakeChatConversationId } from "../../run-dispatch/index.js"; import { enrichPromotedWakeContext, wakeMustNotJoinActiveRun } from "../domain/context.js"; +import { QUEUED_MESSAGES_DELIVERED_REASON } from "../domain/policy.js"; import { decideQueuedCommentAction, decideReleaseRecovery, @@ -272,7 +273,7 @@ async function runReleaseDrain( reason: commentAction.selfAuthored ? "Deferred wake contained only comments authored by the finishing run" : liveness.deliveredCommentIds?.length - ? "Queued messages were already delivered to a completed run" + ? QUEUED_MESSAGES_DELIVERED_REASON : "Queued messages were discarded before promotion", now: input.now, }); diff --git a/server/src/modules/wake-queue/domain/policy.ts b/server/src/modules/wake-queue/domain/policy.ts index 11b904bdc61..8ef29468016 100644 --- a/server/src/modules/wake-queue/domain/policy.ts +++ b/server/src/modules/wake-queue/domain/policy.ts @@ -13,6 +13,9 @@ // This file only branches on that facts object; it never queries a // database, reads the clock, or reads the wake context payload directly. +/** The error a saved wake records when a completed run already received all of its messages. */ +export const QUEUED_MESSAGES_DELIVERED_REASON = "Queued messages were already delivered to a completed run"; + export type WakeAdmissionFacts = { /** True when the active execution run's agent and this wake's own agent share an execution-agent-name key. */ isSameExecutionAgent: boolean; diff --git a/server/src/modules/wake-queue/index.ts b/server/src/modules/wake-queue/index.ts index 15e86549d30..9ac0a76879b 100644 --- a/server/src/modules/wake-queue/index.ts +++ b/server/src/modules/wake-queue/index.ts @@ -29,6 +29,7 @@ export type { } from "./application/types.js"; export { WakeQueueApplicationError } from "./application/types.js"; export { hasRetainedExternalChatRetry } from "./domain/context.js"; +export { QUEUED_MESSAGES_DELIVERED_REASON } from "./domain/policy.js"; export type { IssueSnapshot, RunSnapshot, diff --git a/server/src/services/chat-channels/inbound/wakeups.ts b/server/src/services/chat-channels/inbound/wakeups.ts index d80fde3d6f9..feea97ba8f0 100644 --- a/server/src/services/chat-channels/inbound/wakeups.ts +++ b/server/src/services/chat-channels/inbound/wakeups.ts @@ -1,3 +1,4 @@ +import { EXTERNAL_CHAT_MESSAGE_WAKE_MUTATION, EXTERNAL_CHAT_MESSAGE_WAKE_REASON } from "../../queued-comment-delivery.js"; import { notifyChatInboundWakeNotices } from "../../chat-inbound-wake-notice-notifications.js"; import { DELIVERY_PROCESSING_STALE_MS } from "./delivery-ledger.js"; import type { EndpointRow, DbOrTransaction } from "../runtime-types.js"; @@ -367,8 +368,8 @@ export function createInboundWakeups(db: Db, options: WakeupOptions) { await queueIssueAssignmentWakeup({ heartbeat: options.heartbeat, issue: context.issue, - reason: "External chat message received", - mutation: "chat_message_received", + reason: EXTERNAL_CHAT_MESSAGE_WAKE_REASON, + mutation: EXTERNAL_CHAT_MESSAGE_WAKE_MUTATION, contextSource: `chat:${context.endpoint.provider}`, requestedByActorType: request.requestedByActorType, requestedByActorId: request.requestedByActorId, @@ -471,7 +472,7 @@ export function createInboundWakeups(db: Db, options: WakeupOptions) { }); assertDurableChatWakeupReceipt(request, receipt); await queueIssueAssignmentWakeup({ heartbeat: options.heartbeat, issue: context.issue, - reason: "External chat message received", mutation: "chat_message_received", + reason: EXTERNAL_CHAT_MESSAGE_WAKE_REASON, mutation: EXTERNAL_CHAT_MESSAGE_WAKE_MUTATION, contextSource: `chat:${context.endpoint.provider}`, taskKey: context.issue.identifier, requestedByActorType: request.requestedByActorType, requestedByActorId: request.requestedByActorId, wakeCommentId: request.commentId, chatConversationId: context.conversation.id, diff --git a/server/src/services/chat-inbound-wakeup-publications.ts b/server/src/services/chat-inbound-wakeup-publications.ts index 0f3915b2706..d037459beb5 100644 --- a/server/src/services/chat-inbound-wakeup-publications.ts +++ b/server/src/services/chat-inbound-wakeup-publications.ts @@ -3,6 +3,7 @@ import { assertDurableChatWakeupReceipt, createDurableChatWakeupRequest, } from "./durable-chat-wakeup.js"; +import { QUEUED_MESSAGES_DELIVERED_REASON } from "../modules/wake-queue/index.js"; type Action = typeof chatActions.$inferSelect; type Receipt = typeof agentWakeupRequests.$inferSelect; @@ -125,6 +126,10 @@ export function resolveInboundWakeReceipt( const declined = ["skipped", "cancelled", "failed"].includes(owner.status) || ["skipped", "cancelled", "failed"].includes(receipt.status); + // A completed run already received this message and answered it. Saying + // "not started" would be wrong; it keeps the same silence as a promotion. + if (declined && owner.status === "cancelled" && owner.error === QUEUED_MESSAGES_DELIVERED_REASON) + return null; if (declined) return owner.runId || receipt.runId ? null diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index a99654a7ba1..d504a101231 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -1,3 +1,4 @@ +import { QUEUED_MESSAGES_DELIVERED_REASON } from "../../modules/wake-queue/index.js"; 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"; @@ -1920,7 +1921,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende const remaining = commentIds.filter(commentId => !delivered.has(commentId)); const now = new Date(); await db.update(agentWakeupRequests).set(remaining.length === 0 - ? { status: "cancelled", finishedAt: now, updatedAt: now, error: "Queued messages were already delivered to a completed run" } + ? { status: "cancelled", finishedAt: now, updatedAt: now, error: QUEUED_MESSAGES_DELIVERED_REASON } : { payload: withQueuedCommentIdsInWakePayload(parseObject(receipt.payload), remaining), updatedAt: now }) .where(and(eq(agentWakeupRequests.id, receipt.id), eq(agentWakeupRequests.status, "deferred_issue_execution"))); } diff --git a/server/src/services/queued-comment-delivery.ts b/server/src/services/queued-comment-delivery.ts index 6ef16eab4fd..9faf1b6a169 100644 --- a/server/src/services/queued-comment-delivery.ts +++ b/server/src/services/queued-comment-delivery.ts @@ -1,6 +1,11 @@ import { and, eq, inArray, sql } from "drizzle-orm"; import { heartbeatRunEvents, heartbeatRuns, issueComments, type Db } from "@paperclipai/db"; +/** The wake reason an inbound chat message records (see chat inbound wakeups). */ +export const EXTERNAL_CHAT_MESSAGE_WAKE_REASON = "External chat message received"; +/** The mutation an inbound chat message wake records. */ +export const EXTERNAL_CHAT_MESSAGE_WAKE_MUTATION = "chat_message_received"; + /** * Per-comment consumption (work-intent outbox, invariant 4). A succeeded run * of the wake's agent that started after the comment's latest revision From 3fdcc2a28c79022d5f560fe108d63c9a2c3630b6 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:15:48 -0600 Subject: [PATCH 15/38] fix(runner): resend an ACPX turn whose start was cut off before the prompt left (#20675) 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 > - A native ACPX run (for example Claude) sends `turn.start` to its Runner. The Runner asks the ACPX sidecar to start the turn, and the sidecar sends the prompt to the provider > - A start can fail without a definite answer. A host freeze can outlast the sidecar request deadline, or the sidecar or Runner can die during the start > - The Runner then saved the session `closed`. Every same-run resume failed with `ACPX session is not open`, and the task needed Retry > - The Runner cannot tell from its own state whether the provider has the prompt. Resending could duplicate it. A continuation could lose it > - This pull request adds a durable record that answers that question: a sidecar prompt-dispatch journal, written before the prompt reaches the provider > - The benefit is that a start cut off before the prompt left resends the prompt exactly once, with no Retry. Every case the record cannot prove keeps today's behavior ## Linked Issues or Issue Description **What happened?** Local restart-chaos wave `w-20261110T185315-s9107`, task t05 (claude, workload C1, fault TM2). A follow-up run reopened the parked Claude session and sent `turn.start`. The sidecar first starts Claude and loads the conversation; the prompt goes out only after that. After 24 s without a reply, the harness froze the server, Runner, sidecar and Claude (SIGSTOP) for 33 s. On thaw the Runner's 30 s sidecar deadline had passed. It reaped the sidecar and saved the session `closed`. Three same-run resumes failed with `PRP command turn.start failed: … ACPX session is not open`, recovery stopped with `native_session_retry_exhausted`, and a person had to click Retry. **Expected behavior** When a durable record proves the prompt never reached the provider, the run resends it once by itself. When the record cannot prove it, the run behaves as today. **Steps to reproduce** 1. On master, run `cargo test --manifest-path packages/paperclip-runner/runner/Cargo.toml -p paperclip-runner-core --test acpx_park_preparation cut_turn_start`. 2. `a_start_cut_off_before_the_prompt_left_reopens_and_sends_the_prompt_once` fails: the session is `closed` and the next start fails with `ACPX session is not open`. Refs #20507, #20645, #20674 ## What Changed - New file contract in `protocol/provider-schemas/acpx-sidecar.schema.json`: `turnDispatchJournalFile` (`paperclip-turn-dispatch.jsonl`) and `turnDispatchJournalRecord` (`received` / `dispatched`). The generator emits the file name and schema into TypeScript and Rust, so the pack contract digest covers them. - Sidecar (`turn-dispatch-journal.ts`, `codex-runtime-adapter.ts`, `runtime-host.ts`, `acpx-runtime-sidecar.ts`): when the runtime port starts a turn, before any provider work, it truncates the journal and writes `received`. ACPX calls `onAcpMessage("outbound")` synchronously before it writes a message to the provider. On the turn's first `session/prompt` request the port appends `dispatched` and fsyncs it there, so the record exists before the bytes leave. A failed dispatch write aborts the prompt write. A failed `received` write removes the file and runs the turn unjournaled. - Runner (`acpx_turn_dispatch.rs`, `acpx_provider_backend.rs`): the journal is read only after the provider lifetime fence proves that the sidecar and provider are gone. A lone complete `received` record for the turn proves the prompt never left. - A start that failed in flight saves the session `prepared` with no active turn and returns `ACPX turn start failed before its prompt reached the provider`. The run's next `turn.start` reopens the conversation and sends the prompt once. Until the proof settles, the saved state stays `turn_starting`, so a Runner killed during the proof goes through the restore check below. - A Runner killed while the session was `turn_starting` restores the session idle (`session.resumed`, no `turn.failed`). The same-run resume then starts the turn once instead of sending a continuation that would lose the prompt. - A `dispatched` record, another turn's record, a torn or malformed file, or no file keeps today's behavior (closed session, or lost-turn recovery). - Fake sidecar: writes the same journal and adds `hang-before-dispatch` / `hang-after-dispatch` faults. - Docs: `packages/paperclip-runner/docs/durable-recovery.md` ("ACPX turn starts cut off before the prompt left"). The design note is `doc/plans/2026-11-10-durable-turn-start-and-tool-call-records.md` (in #20674). ## Verification - Red on master, green here: `cargo test -p paperclip-runner-core --test acpx_park_preparation cut_turn_start` (4 tests: cut before dispatch reopens and sends once; cut after dispatch stays closed and never resends; Runner killed before dispatch restores idle; Runner killed after dispatch or with no journal reports the lost turn). The two "before" cases fail on master. - `cargo test -p paperclip-runner-core`: all pass. `cargo fmt --check` clean. - `pnpm --filter @paperclipai/paperclip-runner exec vitest run src/drivers/acpx/turn-dispatch-journal.test.ts src/drivers/acpx/codex-runtime-adapter.test.ts`: 121 passed. One test uses a real ACPX runtime and an ACP peer that refuses a prompt arriving before its `dispatched` record; it fails if the hook is removed. - `node scripts/generate-acpx-sidecar-contract.mjs --check`, `node --test scripts/contracts/contract-fingerprints.test.mjs`, and `tsc -p tsconfig.test.json` pass. - Time to first token, measured with the same open/write/fsync sequence on this Mac (APFS, load average ~11, 300 samples): `received` p50 0.24 ms, p95 0.59 ms; `dispatched` (with fsync) p50 4.7 ms, p95 11.5 ms. Against a Claude TTFT budget of 9.5–16.5 s p50 this is under 0.1%. No wait, round trip or file transfer is added. Recovery work (fence, journal read) runs only after a failed start. - Live restart-chaos wave and runner image: see the comments on this pull request. ## Risks - A false "not dispatched" proof would duplicate a prompt. It needs a lone, complete `received` record for this exact turn ID, read after the fence proves the sidecar is gone. `dispatched` is fsynced before the prompt write, and a failed write aborts the send. A failed `received` write removes the file, so it cannot leave a lone record. - Upgrade safety: saved provider state gains no field (its decoder denies unknown fields), and only lifecycles an older Runner already handles are written. An older Runner ignores the journal file. State saved by an older Runner has no journal, which reads as unknown and keeps today's behavior. A new Runner with an older sidecar never sees a `received` record, so no proof forms. - The changed sidecar schema changes the pack contract digest, so Daytona needs a new runner image. Older image packs are not reused. - A failed start now waits for the provider lifetime fence (at most 5 s, usually immediate) before it settles. This is only on a failure path. ## Model Used Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell, file editing) in Claude Code. Extended reasoning was used. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- ...urable-turn-start-and-tool-call-records.md | 15 +- .../paperclip-runner/docs/durable-recovery.md | 41 ++++ .../provider-schemas/acpx-sidecar.schema.json | 15 ++ .../runner-core/src/acpx_provider_backend.rs | 102 ++++++++- .../runner-core/src/acpx_turn_dispatch.rs | 134 ++++++++++++ .../runner-core/src/bin/fake-acpx-sidecar.rs | 47 +++- .../src/generated_acpx_sidecar_contract.rs | 2 + .../runner/crates/runner-core/src/lib.rs | 1 + .../tests/acpx_park_preparation.rs | 3 + .../tests/support/acpx_cut_turn_start.rs | 204 ++++++++++++++++++ .../generate-acpx-sidecar-contract.mjs | 19 +- .../src/cli/acpx-runtime-sidecar.ts | 3 + .../acpx/codex-runtime-adapter.test.ts | 66 ++++++ .../src/drivers/acpx/codex-runtime-adapter.ts | 16 +- .../acpx/generated-sidecar-contract.ts | 2 + .../src/drivers/acpx/runtime-host.ts | 4 + .../acpx/turn-dispatch-journal.test.ts | 163 ++++++++++++++ .../src/drivers/acpx/turn-dispatch-journal.ts | 92 ++++++++ ...runnerd-acpx-source-reconciliation.test.ts | 37 ++++ 19 files changed, 956 insertions(+), 10 deletions(-) create mode 100644 packages/paperclip-runner/runner/crates/runner-core/src/acpx_turn_dispatch.rs create mode 100644 packages/paperclip-runner/runner/crates/runner-core/tests/support/acpx_cut_turn_start.rs create mode 100644 packages/paperclip-runner/src/drivers/acpx/turn-dispatch-journal.test.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/turn-dispatch-journal.ts diff --git a/doc/plans/2026-11-10-durable-turn-start-and-tool-call-records.md b/doc/plans/2026-11-10-durable-turn-start-and-tool-call-records.md index a7828ba4e0f..902e37b29b5 100644 --- a/doc/plans/2026-11-10-durable-turn-start-and-tool-call-records.md +++ b/doc/plans/2026-11-10-durable-turn-start-and-tool-call-records.md @@ -53,4 +53,17 @@ This makes the gateway call idempotent on its durable input, which is the cleane ## Time to first token -Change 2 touches only recovery. Change 1 adds to every turn, before the prompt reaches the provider: one small unsynced file write when the turn starts, and one append plus `fsync` immediately before the prompt write. It adds no wait, no file transfer and no round trip. The measured cost is in the change 1 PR (target: well under 5 ms p95 on local disks, against a 9.5–16.5 s TTFT p50 budget). Recovery-time work (fence proof, journal read) runs only after a failure. +Change 2 touches only recovery. Change 1 adds to every turn, before the prompt reaches the provider: one small unsynced file write when the turn starts, and one append plus `fsync` immediately before the prompt write. It adds no wait, no file transfer and no round trip. Measured with the same open/write/fsync sequence on a loaded macOS host (APFS, load average ~11, 300 samples): the `received` write p50 0.24 ms, p95 0.59 ms; the `dispatched` append and fsync p50 4.7 ms, p95 11.5 ms. Against a Claude TTFT budget of 9.5–16.5 s p50 this is under 0.1%. Linux overlay disks in Daytona were not measured. Recovery-time work (fence proof, journal read) runs only after a failure. + +## Not covered: a remote Runner gone mid-turn with tools running + +Staging class R, item 1 (`runner_remote_process_identity_unavailable`, mostly OpenCode on Daytona). A deploy stops the controller for 4–7 min while a turn runs tools. On recovery the remote Runner is gone (`process_not_running`, `runnerSettled: false`), or it is adopted and `session.snapshot` then times out. The turn is unsettled and tool effects are possible, so recovery refuses (`provider_turn_unsettled`) and Retry is needed. Retry works. + +The question is whether a durable record can prove "no tool call was in flight when the Runner stopped" (every intent has an outcome), so recovery could continue from the checkpoint. **These two changes do not cover it.** What they give, and what is missing: + +- **Paperclip semantic tools** (calls that reach the server's tool gateway). The intent is the controller's committed semantic input, keyed by call ID. The outcome is the server receipt or the journaled result command. Both live on the control plane, so they are readable without a live Runner. Change 2 makes `write_document` settle exactly once from its receipt. Other semantic tools keep their rules. +- **Provider-native tools** (OpenCode's shell and file edits, Claude's built-in tools). These are the class R calls, and they have **no write-ahead intent record**. The Runner learns of a tool only from a provider event (`tool.execution.started`), which the provider emits after it decided to run the tool, and often after it started it. A missing `started` event therefore does not prove that no tool ran. A complete record needs a hook that runs before execution: a permission or pre-tool callback that the provider waits on (OpenCode plugins and ACP permission requests can serve), which journals the intent durably in the Runner's state before it answers. +- **Readable without a live Runner.** The Runner's journal (`runner-state.json`, provider state) is in the sandbox. Commands already delivered stay on the controller, but events the Runner had not yet delivered are only in the sandbox. The server would need to read the sandbox files through the provider API (Daytona filesystem) after it proves the Runner and provider processes are stopped. It would also need a way to trust those bytes: today they carry no signature that binds them to the Runner's authenticated session. Process proof alone is not enough for an adopted Runner whose `session.snapshot` timed out; that case needs the same file read after a forced stop. +- **The rule it would enable.** Every journaled intent has a matching outcome, the provider and Runner are proven stopped, and the last checkpoint covers the last outcome: recovery may resume from the checkpoint and send a same-conversation continuation. Anything else keeps Retry. + +This is a follow-up, not part of these PRs. diff --git a/packages/paperclip-runner/docs/durable-recovery.md b/packages/paperclip-runner/docs/durable-recovery.md index d62874891e0..b146dc651a2 100644 --- a/packages/paperclip-runner/docs/durable-recovery.md +++ b/packages/paperclip-runner/docs/durable-recovery.md @@ -112,6 +112,47 @@ unconfirmed cleanup do not qualify. Error messages cannot authorize recovery. An arbitrary `closed` provider state stays closed. This path does not establish recovery for a Runner killed during an accepted turn. +## ACPX turn starts cut off before the prompt left + +A turn start can fail without a definite answer: the sidecar's reply is lost or +late (for example, a host freeze outlasts the request deadline), or the sidecar +or Runner dies while the start is in flight. Resending the prompt could +duplicate it, and a continuation could lose it. + +The sidecar's runtime port keeps a prompt-dispatch journal, +`paperclip-turn-dispatch.jsonl`, in the session's private runtime directory +(`turnDispatchJournalFile` and `turnDispatchJournalRecord` in the sidecar +schema). When it starts a turn, before any provider work, it truncates the file +and writes a `received` record. Immediately before ACPX writes the turn's first +`session/prompt` request to the provider, it appends a `dispatched` record and +fsyncs it. ACPX calls the host's `onAcpMessage("outbound")` hook synchronously +before it writes the bytes, so a failed journal write aborts the prompt write. + +The Runner reads the journal only after it acquires the provider lifetime fence, +which proves that the sidecar and the provider are gone. + +- A lone, complete `received` record for the turn proves that the prompt never + reached the provider. A start that failed in flight saves the session + `prepared`, with no active turn, and fails the command with + `ACPX turn start failed before its prompt reached the provider`. The run's + next `turn.start` reopens the conversation and sends the prompt once. A + Runner that died while the session was `turn_starting` restores the session + idle, emits `session.resumed` and no `turn.failed`, and the same-run resume + starts the turn once. +- A `dispatched` record, a record of another turn, a torn or malformed file, or + no file (an older sidecar) proves nothing. The earlier behavior applies + unchanged: a failed start closes the session, and a killed Runner uses + lost-turn recovery. + +Until a proof settles it, the saved session stays `turn_starting`, so a Runner +killed during the proof restores through the same check. The cut-off command is +never executed again. Saved state gains no field, so an older Runner reading it +mid-deploy sees only lifecycles it already handles. + +On the normal path the journal costs one small unsynced write when the turn +starts and one append and fsync just before the prompt is written. It adds no +wait, round trip or file transfer. + ## ACPX cancellation without a reply The Runner serves controller commands one at a time. It therefore waits at most diff --git a/packages/paperclip-runner/protocol/provider-schemas/acpx-sidecar.schema.json b/packages/paperclip-runner/protocol/provider-schemas/acpx-sidecar.schema.json index 1e2e51e408b..64a33d45c4a 100644 --- a/packages/paperclip-runner/protocol/provider-schemas/acpx-sidecar.schema.json +++ b/packages/paperclip-runner/protocol/provider-schemas/acpx-sidecar.schema.json @@ -9,6 +9,21 @@ ], "$defs": { "protocolVersion": { "const": 2 }, + "turnDispatchJournalFile": { + "description": "File name of the sidecar's prompt-dispatch journal in the session runtime directory. It holds turnDispatchJournalRecord lines for the latest turn only.", + "const": "paperclip-turn-dispatch.jsonl" + }, + "turnDispatchJournalRecord": { + "description": "One journal line. The runtime port truncates the file and writes `received` when it starts the turn, before any provider work. It appends `dispatched` and fsyncs it immediately before the turn's first session/prompt request is written to the provider. The Runner reads the journal only after it proves that the sidecar and provider are gone: a lone `received` line proves the prompt never reached the provider.", + "type": "object", + "properties": { + "schema": { "const": "paperclip.acpx-turn-dispatch.v1" }, + "turnId": { "type": "string", "minLength": 1 }, + "phase": { "enum": ["received", "dispatched"] } + }, + "required": ["schema", "turnId", "phase"], + "additionalProperties": false + }, "command": { "enum": [ "initialize", diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs index 6797bdcb6d0..f15147c4664 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs @@ -22,6 +22,7 @@ use crate::acpx_provider_session::{ PiThinkingLevel, }; use crate::acpx_sidecar_transport::AcpxSidecarTransportConfig; +use crate::acpx_turn_dispatch::{read_turn_dispatch_journal, TurnDispatchEvidence}; #[cfg(test)] use crate::durable::QualifiedLaunchArtifact; use crate::durable::{ @@ -1299,6 +1300,66 @@ impl AcpxCommandExecutor { self.save_state() } + /// A turn start that failed without a definite answer (a lost or late + /// reply, an exited or frozen sidecar) leaves the prompt's fate unknown: + /// resending could duplicate it and continuing could lose it. Once the + /// sidecar and provider are proven gone, the sidecar's dispatch journal + /// can prove that the prompt never left. Then the session is saved + /// reopenable with no active turn, so the run's next `turn.start` sends + /// the prompt once. Returns false, changing nothing, without that proof. + fn reopen_after_undispatched_turn_start( + &mut self, + turn_id: &str, + ) -> Result { + let session_identity = self + .session + .as_ref() + .map(|session| session.identity().clone()); + let Some(state) = self.state.as_ref() else { + return Ok(false); + }; + let Some(identity) = state.identity.clone() else { + return Ok(false); + }; + if session_identity.as_ref() != Some(&identity) + || state.lifecycle != "turn_starting" + || state.active_turn_id.as_deref() != Some(turn_id) + || state.provider_exit_unconfirmed + || !state.pending_runtime_requests.is_empty() + || state.semantic_result.is_some() + || !state + .pending_events + .iter() + .all(|event| event.event_type == "session.resumed") + || !(state.goal_projection.is_null() || goal_is_dormant(&state.goal_projection)) + { + return Ok(false); + } + // The saved state still says `turn_starting` until a proof settles it, + // so a Runner killed during this wait restores through the same check. + self.session = None; + let Ok(_provider_lifetime_fence) = + await_provider_lifetime_fence(identity.provider_lifetime_fence_candidates) + else { + return Ok(false); + }; + let runtime_directory = state.descriptor.runtime_directory.clone(); + if read_turn_dispatch_journal(&runtime_directory, turn_id) + != TurnDispatchEvidence::NotDispatched + { + return Ok(false); + } + let state = self + .state + .as_mut() + .expect("ACPX state remains available after an undispatched turn start"); + state.lifecycle = "prepared".to_owned(); + state.active_turn_id = None; + self.context.provider_turn_id = None; + self.save_state()?; + Ok(true) + } + /// Restores the conversation of a turn that was active when the runner /// died, without inventing its outcome. The original provider lifetime /// must have lost its fence quorum first, so no second provider can act on @@ -1326,11 +1387,29 @@ impl AcpxCommandExecutor { { return Ok(false); } - match await_provider_lifetime_fence(identity.provider_lifetime_fence_candidates) { - // Release the quorum so the restored provider can inherit it. - Ok(listeners) => drop(listeners), - Err(_) => return Ok(false), - } + // A Runner killed while the start was in flight saved `turn_starting`. + // When the sidecar's journal proves the prompt never left, no + // provider turn exists: restore the session idle so the run's next + // turn.start sends the prompt once, instead of a continuation that + // would lose it. + let start_turn_id = (state.lifecycle == "turn_starting") + .then(|| previous_turn.clone()) + .flatten(); + let runtime_directory = state.descriptor.runtime_directory.clone(); + let undispatched = + match await_provider_lifetime_fence(identity.provider_lifetime_fence_candidates) { + // Read the journal while the quorum proves the sidecar is gone, + // then release it so the restored provider can inherit it. + Ok(listeners) => { + let undispatched = start_turn_id.is_some_and(|turn_id| { + read_turn_dispatch_journal(&runtime_directory, &turn_id) + == TurnDispatchEvidence::NotDispatched + }); + drop(listeners); + undispatched + } + Err(_) => return Ok(false), + }; let Ok(session) = self.start_session(true) else { return Ok(false); }; @@ -1353,6 +1432,12 @@ impl AcpxCommandExecutor { priority: EventPriority::P0, payload: session_event_payload(&state.descriptor, &identity, process_id, turn_controls), })?; + if undispatched { + self.recovery_pending_effects = None; + self.session = Some(session); + self.save_state()?; + return Ok(true); + } state.push(NormalizedProviderEvent { event_type: "turn.failed".to_owned(), priority: EventPriority::P0, @@ -2103,6 +2188,13 @@ impl AcpxCommandExecutor { }) }) .cloned(); + if rejected_checkpoint.is_none() + && self.reopen_after_undispatched_turn_start(&provider_turn_id)? + { + return Err(DurableRunnerError::invalid(format!( + "ACPX turn start failed before its prompt reached the provider: {error}" + ))); + } let state = self .state .as_mut() diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_turn_dispatch.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_turn_dispatch.rs new file mode 100644 index 00000000000..1c85852f613 --- /dev/null +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_turn_dispatch.rs @@ -0,0 +1,134 @@ +//! Reads the ACPX sidecar's prompt-dispatch journal. +//! +//! The sidecar's runtime port writes `received` for a turn before any provider +//! work and appends a synced `dispatched` immediately before the turn's first +//! `session/prompt` request reaches the provider (see the TypeScript +//! `turn-dispatch-journal.ts` and `turnDispatchJournalRecord` in the sidecar +//! schema). Callers read it only after they prove that the sidecar and the +//! provider are gone, so neither can still write or send. + +use std::io::Read; +use std::path::Path; + +use serde::Deserialize; + +use crate::durable::open_private_regular_file; +use crate::generated_acpx_sidecar_contract::{ + GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE, GENERATED_ACPX_TURN_DISPATCH_SCHEMA, +}; + +// Two records of one bounded turn ID fit easily; anything larger is not ours. +const MAX_JOURNAL_BYTES: u64 = 4 * 1024; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum TurnDispatchEvidence { + /// The sidecar started this turn and never wrote its prompt to the provider. + NotDispatched, + /// The prompt may have reached the provider. + Dispatched, + /// No usable record for this turn: an older sidecar, another turn, or a + /// damaged file. Recovery must not assume either outcome. + Unknown, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Record { + schema: String, + #[serde(rename = "turnId")] + turn_id: String, + phase: String, +} + +pub(crate) fn read_turn_dispatch_journal( + runtime_directory: &Path, + turn_id: &str, +) -> TurnDispatchEvidence { + let path = runtime_directory.join(GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE); + let Ok(file) = open_private_regular_file(&path) else { + return TurnDispatchEvidence::Unknown; + }; + let mut bytes = Vec::new(); + if file + .take(MAX_JOURNAL_BYTES + 1) + .read_to_end(&mut bytes) + .is_err() + || bytes.len() as u64 > MAX_JOURNAL_BYTES + { + return TurnDispatchEvidence::Unknown; + } + classify(&bytes, turn_id) +} + +fn classify(bytes: &[u8], turn_id: &str) -> TurnDispatchEvidence { + // Every record ends with a newline; a torn tail proves nothing. + let Some(body) = bytes.strip_suffix(b"\n") else { + return TurnDispatchEvidence::Unknown; + }; + let mut phases = Vec::new(); + for line in body.split(|byte| *byte == b'\n') { + let Ok(record) = serde_json::from_slice::(line) else { + return TurnDispatchEvidence::Unknown; + }; + if record.schema != GENERATED_ACPX_TURN_DISPATCH_SCHEMA || record.turn_id != turn_id { + return TurnDispatchEvidence::Unknown; + } + phases.push(record.phase); + } + match phases.as_slice() { + [received] if received == "received" => TurnDispatchEvidence::NotDispatched, + [received, rest @ ..] + if received == "received" + && !rest.is_empty() + && rest.iter().all(|phase| phase == "dispatched") => + { + TurnDispatchEvidence::Dispatched + } + _ => TurnDispatchEvidence::Unknown, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn line(turn: &str, phase: &str) -> String { + format!( + "{{\"schema\":\"{GENERATED_ACPX_TURN_DISPATCH_SCHEMA}\",\"turnId\":\"{turn}\",\"phase\":\"{phase}\"}}\n" + ) + } + + #[test] + fn only_a_lone_received_record_of_this_turn_proves_the_prompt_never_left() { + let received = line("turn-1", "received"); + let dispatched = format!("{received}{}", line("turn-1", "dispatched")); + assert_eq!( + classify(received.as_bytes(), "turn-1"), + TurnDispatchEvidence::NotDispatched + ); + assert_eq!( + classify(dispatched.as_bytes(), "turn-1"), + TurnDispatchEvidence::Dispatched + ); + for unknown in [ + String::new(), + received.trim_end().to_owned(), + line("turn-0", "received"), + line("turn-1", "dispatched"), + format!("{received}{}", line("turn-0", "dispatched")), + format!("{received}{{\"schema\":"), + format!("{received}{received}"), + received.replace( + "paperclip.acpx-turn-dispatch.v1", + "paperclip.acpx-turn-dispatch.v0", + ), + received.replace("}\n", ",\"extra\":true}\n"), + ] { + assert_eq!( + classify(unknown.as_bytes(), "turn-1"), + TurnDispatchEvidence::Unknown, + "{unknown:?}" + ); + } + } +} diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs b/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs index ff3d63dd1e6..ba2594f75bf 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs @@ -1,7 +1,10 @@ use std::io::{self, BufRead, Write}; use std::time::Duration; -use paperclip_runner_core::generated_acpx_sidecar_contract::GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION; +use paperclip_runner_core::generated_acpx_sidecar_contract::{ + GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION, GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE, + GENERATED_ACPX_TURN_DISPATCH_SCHEMA, +}; use serde_json::{json, Value}; const PROJECTED_INPUT_PROVIDER_ID: &str = "input / réquest"; @@ -69,6 +72,7 @@ fn run() -> Result<(), Box> { let mut source_run = String::new(); let mut source_pending_completion: Option = None; let mut source_goal_revision = 0_u64; + let mut runtime_directory: Option = None; // `--cancel-reply lost|late`: the provider stops its prompt, but the reply // to turn.cancel is dropped, or written only before the next request. let cancel_reply = args @@ -252,6 +256,47 @@ fn run() -> Result<(), Box> { response = json!({"protocolVersion":GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION,"id":id,"ok":false, "error":{"code":"temporarily_unavailable","message":"Optional read is temporarily unavailable.","retryable":true}}); } + if command == "session.open" { + runtime_directory = request["params"]["runtimeDirectory"] + .as_str() + .map(std::path::PathBuf::from); + } + // Like the real runtime port: journal the turn, then its prompt + // dispatch, before the provider can see the prompt. + // `hang-before-dispatch` / `hang-after-dispatch` freeze the start + // on either side of that boundary without replying. + if command == "turn.start" { + if let Some(directory) = runtime_directory.as_ref() { + let turn = request["params"]["turnId"].as_str().unwrap(); + let path = directory.join(GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE); + let record = |phase: &str| { + format!( + "{}\n", + json!({"schema":GENERATED_ACPX_TURN_DISPATCH_SCHEMA,"turnId":turn,"phase":phase}) + ) + }; + let mut options = std::fs::OpenOptions::new(); + options.write(true).create(true).truncate(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + options + .open(&path)? + .write_all(record("received").as_bytes())?; + if fault == "hang-before-dispatch" { + loop { + std::thread::sleep(std::time::Duration::from_secs(60)); + } + } + let mut journal = std::fs::OpenOptions::new().append(true).open(&path)?; + journal.write_all(record("dispatched").as_bytes())?; + // The runtime port fsyncs here; the fixture skips it to stay fast. + if fault == "hang-after-dispatch" { + loop { + std::thread::sleep(std::time::Duration::from_secs(60)); + } + } + } + } if command == "session.open" && fault == "slow-open" { std::thread::sleep(std::time::Duration::from_secs(10)); } diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_sidecar_contract.rs b/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_sidecar_contract.rs index 367a3bb54db..b0a137dac7d 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_sidecar_contract.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_sidecar_contract.rs @@ -1,6 +1,8 @@ // Generated by scripts/generate-acpx-sidecar-contract.mjs. Do not edit. pub const GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION: u64 = 2; +pub const GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE: &str = "paperclip-turn-dispatch.jsonl"; +pub const GENERATED_ACPX_TURN_DISPATCH_SCHEMA: &str = "paperclip.acpx-turn-dispatch.v1"; pub const GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE: &[(&str, &[&str])] = &[ ("edit", &["edit", "write", "patch"]), diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/lib.rs b/packages/paperclip-runner/runner/crates/runner-core/src/lib.rs index 4c744e414c3..c5d86fc4105 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/lib.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/lib.rs @@ -9,6 +9,7 @@ pub mod acpx_provider_checkpoint; pub mod acpx_provider_session; pub mod acpx_provider_state; pub mod acpx_sidecar_transport; +mod acpx_turn_dispatch; pub mod aws_agentcore_provider; pub mod claude_managed_provider; pub mod codex_provider; diff --git a/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_park_preparation.rs b/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_park_preparation.rs index bd049c55cab..c1fe9911b63 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_park_preparation.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_park_preparation.rs @@ -17,6 +17,9 @@ use sha2::{Digest, Sha256}; #[path = "support/acpx_turn_end_restart.rs"] mod turn_end_restart; +#[path = "support/acpx_cut_turn_start.rs"] +mod cut_turn_start; + struct Fixture(PathBuf); impl Drop for Fixture { fn drop(&mut self) { diff --git a/packages/paperclip-runner/runner/crates/runner-core/tests/support/acpx_cut_turn_start.rs b/packages/paperclip-runner/runner/crates/runner-core/tests/support/acpx_cut_turn_start.rs new file mode 100644 index 00000000000..98de3ed7735 --- /dev/null +++ b/packages/paperclip-runner/runner/crates/runner-core/tests/support/acpx_cut_turn_start.rs @@ -0,0 +1,204 @@ +//! A `turn.start` cut off between the Runner's request and the sidecar's +//! reply (a frozen or killed sidecar, a timeout). The sidecar's dispatch +//! journal decides whether the prompt could have reached the provider. + +use super::*; + +const JOURNAL: &str = "paperclip-turn-dispatch.jsonl"; + +fn journal_phases(harness: &Harness) -> Vec { + fs::read_to_string(harness.fixture.0.join(JOURNAL)) + .unwrap_or_default() + .lines() + .map(|line| { + serde_json::from_str::(line).unwrap()["phase"] + .as_str() + .unwrap() + .to_owned() + }) + .collect() +} + +fn kill(pid: &Value) { + std::process::Command::new("kill") + .args(["-9", &pid.to_string()]) + .status() + .unwrap(); +} + +/// Starts `turn` against a sidecar that freezes at `fault`, then kills the +/// sidecar once the journal shows `phases`, and returns the start's error. +fn cut_turn_start(harness: &mut Harness, turn: &str, fault: &str, phases: &[&str]) -> String { + harness.fixture.fault(fault); + let sidecar = harness.fixture.process_starts().last().unwrap()["processStart"].clone(); + let root = harness.fixture.0.clone(); + let expected = phases + .iter() + .map(|phase| phase.to_string()) + .collect::>(); + let killer = std::thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + let seen = fs::read_to_string(root.join(JOURNAL)) + .unwrap_or_default() + .lines() + .map(|line| { + serde_json::from_str::(line).unwrap()["phase"] + .as_str() + .unwrap() + .to_owned() + }) + .collect::>(); + if seen == expected { + break; + } + assert!( + Instant::now() < deadline, + "the sidecar never reached {expected:?}" + ); + std::thread::sleep(Duration::from_millis(10)); + } + kill(&sidecar); + }); + harness.sequence += 1; + let error = harness + .executor + .execute(&command( + harness.sequence, + "turn.start", + json!({"turnId": turn, "text": "Write the brief."}), + )) + .unwrap_err() + .to_string(); + killer.join().unwrap(); + harness.fixture.fault(""); + error +} + +#[test] +fn a_start_cut_off_before_the_prompt_left_reopens_and_sends_the_prompt_once() { + let mut harness = Harness::new(); + let error = cut_turn_start(&mut harness, "cut", "hang-before-dispatch", &["received"]); + assert!( + error.contains("before its prompt reached the provider"), + "{error}" + ); + let saved = harness.fixture.state(); + assert_eq!(saved["lifecycle"], "prepared", "{saved}"); + assert_eq!(saved["activeTurnId"], Value::Null); + assert_eq!(saved["providerExitUnconfirmed"], false); + // The run's next start reopens the conversation and delivers its prompt. + let before = harness.fixture.journal().len(); + let events = harness.complete_turn("resent"); + assert!( + events.iter().all(|event| event["type"] != "turn.failed"), + "{events:?}" + ); + let starts = harness.fixture.journal()[before..] + .iter() + .filter(|line| line["command"] == "turn.start") + .map(|line| line["params"]["turnId"].clone()) + .collect::>(); + assert_eq!(starts, [json!("resent")]); + assert_eq!(journal_phases(&harness), ["received", "dispatched"]); + harness.executor.shutdown().unwrap(); +} + +#[test] +fn a_start_cut_off_after_the_prompt_left_stays_closed_and_never_resends() { + let mut harness = Harness::new(); + let error = cut_turn_start( + &mut harness, + "cut", + "hang-after-dispatch", + &["received", "dispatched"], + ); + assert!(error.contains("failed closed"), "{error}"); + assert_eq!(harness.fixture.state()["lifecycle"], "closed"); + let starts = harness.fixture.process_starts().len(); + harness.sequence += 1; + let refused = harness + .executor + .execute(&command( + harness.sequence, + "turn.start", + json!({"turnId": "resent", "text": "Write the brief."}), + )) + .unwrap_err() + .to_string(); + assert_eq!(refused, "ACPX session is not open"); + assert_eq!(harness.fixture.process_starts().len(), starts); +} + +/// The Runner itself dies while the session is saved `turn_starting`. +fn restore_cut_runner(harness: &mut Harness, phases: &[&str]) -> Vec { + let mut saved = harness.fixture.state(); + harness.executor.shutdown().unwrap(); + saved["lifecycle"] = json!("turn_starting"); + saved["activeTurnId"] = json!("cut"); + fs::write( + harness.fixture.0.join("acpx-provider-state.json"), + serde_json::to_vec_pretty(&saved).unwrap(), + ) + .unwrap(); + let journal = phases + .iter() + .map(|phase| { + format!( + "{}\n", + json!({"schema":"paperclip.acpx-turn-dispatch.v1","turnId":"cut","phase":phase}) + ) + }) + .collect::(); + let path = harness.fixture.0.join(JOURNAL); + let _ = fs::remove_file(&path); + if !phases.is_empty() { + fs::write(&path, journal).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); + } + harness.executor = + NativeProviderCommandExecutor::with_runner_config(&harness.fixture.0, &harness.config); + harness.sequence += 1; + let snapshot = harness + .executor + .execute(&command(harness.sequence, "session.snapshot", json!({}))) + .unwrap(); + let mut events = snapshot + .events + .iter() + .map(|(kind, _, payload)| json!({"type":kind,"payload":payload})) + .collect::>(); + events.extend(harness.drain()); + events +} + +#[test] +fn a_runner_killed_before_the_prompt_left_restores_an_idle_session() { + let mut harness = Harness::new(); + let events = restore_cut_runner(&mut harness, &["received"]); + let kinds = events + .iter() + .map(|event| event["type"].clone()) + .collect::>(); + assert!(kinds.contains(&json!("session.resumed")), "{events:?}"); + assert!(!kinds.contains(&json!("turn.failed")), "{events:?}"); + let saved = harness.fixture.state(); + assert_eq!(saved["lifecycle"], "session_open"); + assert_eq!(saved["activeTurnId"], Value::Null); + harness.complete_turn("resent"); + harness.executor.shutdown().unwrap(); +} + +#[test] +fn a_runner_killed_after_the_prompt_left_or_without_a_journal_reports_the_lost_turn() { + for phases in [&["received", "dispatched"][..], &[][..]] { + let mut harness = Harness::new(); + let events = restore_cut_runner(&mut harness, phases); + let lost = events + .iter() + .find(|event| event["type"] == "turn.failed") + .unwrap_or_else(|| panic!("{phases:?}: {events:?}")); + assert_eq!(lost["payload"]["code"], "provider_turn_lost_on_restore"); + harness.executor.shutdown().unwrap(); + } +} diff --git a/packages/paperclip-runner/scripts/generate-acpx-sidecar-contract.mjs b/packages/paperclip-runner/scripts/generate-acpx-sidecar-contract.mjs index d682aed0d18..dfd1441e996 100644 --- a/packages/paperclip-runner/scripts/generate-acpx-sidecar-contract.mjs +++ b/packages/paperclip-runner/scripts/generate-acpx-sidecar-contract.mjs @@ -33,6 +33,21 @@ const toolOperationPrecedence = [ ["list", ["list", "glob"]], ]; const protocolVersion = readAcpxSidecarProtocolVersion(schema); +// The prompt-dispatch journal is a file contract between the sidecar (writer) +// and the Runner (reader after the sidecar is proven gone). +const turnDispatchJournalFile = schema.$defs.turnDispatchJournalFile?.const; +const turnDispatchRecord = schema.$defs.turnDispatchJournalRecord; +const turnDispatchSchema = turnDispatchRecord?.properties?.schema?.const; +const turnDispatchPhases = turnDispatchRecord?.properties?.phase?.enum; +if ( + typeof turnDispatchJournalFile !== "string" || + !/^[a-z0-9.-]+$/.test(turnDispatchJournalFile) || + typeof turnDispatchSchema !== "string" || + JSON.stringify(turnDispatchPhases) !== JSON.stringify(["received", "dispatched"]) || + turnDispatchRecord?.additionalProperties !== false +) { + throw new Error("ACPX turn dispatch journal contract must declare its file, schema and closed phases"); +} const quote = (value) => JSON.stringify(value); const rustVariant = (value) => value @@ -40,8 +55,8 @@ const rustVariant = (value) => .map((part) => part[0].toUpperCase() + part.slice(1)) .join(""); -const typescript = `// Generated by scripts/generate-acpx-sidecar-contract.mjs. Do not edit.\n\nexport const GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION = ${protocolVersion} as const;\nexport const GENERATED_ACPX_SIDECAR_COMMANDS = [\n${commands.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\nexport type GeneratedAcpxSidecarCommand =\n (typeof GENERATED_ACPX_SIDECAR_COMMANDS)[number];\n\nexport const GENERATED_ACPX_SIDECAR_EVENT_TYPES = [\n${events.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\nexport type GeneratedAcpxSidecarEventType =\n (typeof GENERATED_ACPX_SIDECAR_EVENT_TYPES)[number];\n\nexport const GENERATED_ACPX_SIDECAR_OPEN_PARAMS = [\n${openParams.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\n\nexport const GENERATED_ACPX_SIDECAR_PROVIDER_POLICY_FIELDS = [\n${providerPolicyFields.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\n\nexport type GeneratedAcpxToolOperation =\n | "read"\n | "search"\n | "list"\n | "edit"\n | "execute"\n | "unknown";\n\nexport const GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE = [\n${toolOperationPrecedence.map(([operation, tokens]) => ` { operation: ${quote(operation)}, tokens: [${tokens.map(quote).join(", ")}] },`).join("\n")}\n] as const;\n\nexport function classifyGeneratedAcpxToolOperation(\n toolKind: unknown,\n toolTitle: unknown,\n): GeneratedAcpxToolOperation {\n const candidate =\n typeof toolKind === "string" && toolKind\n ? toolKind\n : typeof toolTitle === "string"\n ? toolTitle\n : "";\n const normalized = candidate.slice(0, 240).toLowerCase();\n for (const { operation, tokens } of GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE) {\n if (tokens.some((token) => normalized.includes(token))) return operation;\n }\n return normalized ? "execute" : "unknown";\n}\n`; -const rust = `// Generated by scripts/generate-acpx-sidecar-contract.mjs. Do not edit.\n\npub const GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION: u64 = ${protocolVersion};\n\npub const GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE: &[(&str, &[&str])] = &[\n${toolOperationPrecedence.map(([operation, tokens]) => ` (${quote(operation)}, &[${tokens.map(quote).join(", ")}]),`).join("\n")}\n];\n\npub fn classify_generated_acpx_tool_operation(kind: &str, title: &str) -> &'static str {\n let kind = kind.to_ascii_lowercase();\n let title = title.to_ascii_lowercase();\n let candidate = if kind.is_empty() { &title } else { &kind };\n for (operation, tokens) in GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE {\n if tokens.iter().any(|token| candidate.contains(token)) {\n return operation;\n }\n }\n if candidate.is_empty() {\n "unknown"\n } else {\n "execute"\n }\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum GeneratedAcpxSidecarCommand {\n${commands.map((value) => ` ${rustVariant(value)},`).join("\n")}\n}\n\nimpl GeneratedAcpxSidecarCommand {\n pub const fn as_str(self) -> &'static str {\n match self {\n${commands.map((value) => ` Self::${rustVariant(value)} => ${quote(value)},`).join("\n")}\n }\n }\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)]\npub enum GeneratedAcpxSidecarEventType {\n${events.map((value) => ` #[serde(rename = ${quote(value)})]\n ${rustVariant(value)},`).join("\n")}\n}\n`; +const typescript = `// Generated by scripts/generate-acpx-sidecar-contract.mjs. Do not edit.\n\nexport const GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION = ${protocolVersion} as const;\nexport const GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE = ${quote(turnDispatchJournalFile)};\nexport const GENERATED_ACPX_TURN_DISPATCH_SCHEMA = ${quote(turnDispatchSchema)};\nexport const GENERATED_ACPX_SIDECAR_COMMANDS = [\n${commands.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\nexport type GeneratedAcpxSidecarCommand =\n (typeof GENERATED_ACPX_SIDECAR_COMMANDS)[number];\n\nexport const GENERATED_ACPX_SIDECAR_EVENT_TYPES = [\n${events.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\nexport type GeneratedAcpxSidecarEventType =\n (typeof GENERATED_ACPX_SIDECAR_EVENT_TYPES)[number];\n\nexport const GENERATED_ACPX_SIDECAR_OPEN_PARAMS = [\n${openParams.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\n\nexport const GENERATED_ACPX_SIDECAR_PROVIDER_POLICY_FIELDS = [\n${providerPolicyFields.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\n\nexport type GeneratedAcpxToolOperation =\n | "read"\n | "search"\n | "list"\n | "edit"\n | "execute"\n | "unknown";\n\nexport const GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE = [\n${toolOperationPrecedence.map(([operation, tokens]) => ` { operation: ${quote(operation)}, tokens: [${tokens.map(quote).join(", ")}] },`).join("\n")}\n] as const;\n\nexport function classifyGeneratedAcpxToolOperation(\n toolKind: unknown,\n toolTitle: unknown,\n): GeneratedAcpxToolOperation {\n const candidate =\n typeof toolKind === "string" && toolKind\n ? toolKind\n : typeof toolTitle === "string"\n ? toolTitle\n : "";\n const normalized = candidate.slice(0, 240).toLowerCase();\n for (const { operation, tokens } of GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE) {\n if (tokens.some((token) => normalized.includes(token))) return operation;\n }\n return normalized ? "execute" : "unknown";\n}\n`; +const rust = `// Generated by scripts/generate-acpx-sidecar-contract.mjs. Do not edit.\n\npub const GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION: u64 = ${protocolVersion};\npub const GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE: &str = ${quote(turnDispatchJournalFile)};\npub const GENERATED_ACPX_TURN_DISPATCH_SCHEMA: &str = ${quote(turnDispatchSchema)};\n\npub const GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE: &[(&str, &[&str])] = &[\n${toolOperationPrecedence.map(([operation, tokens]) => ` (${quote(operation)}, &[${tokens.map(quote).join(", ")}]),`).join("\n")}\n];\n\npub fn classify_generated_acpx_tool_operation(kind: &str, title: &str) -> &'static str {\n let kind = kind.to_ascii_lowercase();\n let title = title.to_ascii_lowercase();\n let candidate = if kind.is_empty() { &title } else { &kind };\n for (operation, tokens) in GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE {\n if tokens.iter().any(|token| candidate.contains(token)) {\n return operation;\n }\n }\n if candidate.is_empty() {\n "unknown"\n } else {\n "execute"\n }\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum GeneratedAcpxSidecarCommand {\n${commands.map((value) => ` ${rustVariant(value)},`).join("\n")}\n}\n\nimpl GeneratedAcpxSidecarCommand {\n pub const fn as_str(self) -> &'static str {\n match self {\n${commands.map((value) => ` Self::${rustVariant(value)} => ${quote(value)},`).join("\n")}\n }\n }\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)]\npub enum GeneratedAcpxSidecarEventType {\n${events.map((value) => ` #[serde(rename = ${quote(value)})]\n ${rustVariant(value)},`).join("\n")}\n}\n`; // Classification must inspect the same complete provider value in both // languages. Display-field truncation happens only after operation selection. diff --git a/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts b/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts index 75d63241aa1..f372b66d618 100644 --- a/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts +++ b/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts @@ -114,6 +114,7 @@ import { } from "./acpx-sidecar-lifecycle.js"; import { AcpxTurnControlLedger, parseAcpxTurnControl } from "../drivers/acpx/turn-controls.js"; +import { createAcpxTurnDispatchJournal } from "../drivers/acpx/turn-dispatch-journal.js"; const turnControls = new AcpxTurnControlLedger(); const MAX_PENDING_TOOLS = 512; @@ -488,6 +489,8 @@ async function dispatch( onPermissionRequest: (providerRequest, context) => waitForPermission(currentTurnId, activeAgent, providerRequest, context, toolEvidence), onTerminalSessionFailure: (failure) => { sessionFailure.value = failure; }, + // Lets a Runner that lost this request prove whether the prompt left. + dispatchJournal: createAcpxTurnDispatchJournal(openParams!.runtimeDirectory, currentTurnId), }); } catch (error) { turnId = null; diff --git a/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.test.ts b/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.test.ts index 09af405e9b0..72b770ea593 100644 --- a/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.test.ts @@ -1005,6 +1005,72 @@ describe("Codex ACPX runtime adapter", () => { } finally { await port.close({ reason: "fixture done" }); } }); + it("journals a turn before provider work and its prompt dispatch before the prompt write", async () => { + const runtime = fakeRuntime(); + let created!: AcpRuntimeOptions; + const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), + createRuntime: value => { created = value; return runtime; } }); + const order: string[] = []; + const journal = { + markReceived: vi.fn(() => { order.push("received"); return true; }), + markDispatched: vi.fn(() => { order.push("dispatched"); }), + }; + const pending = pendingExtensionTurn("journaled-turn"); + vi.mocked(runtime.startTurn).mockImplementation(() => { order.push("runtime.startTurn"); return pending.turn; }); + try { + const turn = port.startTurn({ requestId: "journaled-turn", text: "fixture", dispatchJournal: journal }); + expect(order).toEqual(["received", "runtime.startTurn"]); + // Other outbound traffic never counts as the prompt. + created.onAcpMessage?.("outbound", { id: 7, method: "session/set_config_option", params: {} }); + created.onAcpMessage?.("outbound", { method: "session/cancel", params: {} }); + expect(journal.markDispatched).not.toHaveBeenCalled(); + created.onAcpMessage?.("outbound", { id: 8, method: "session/prompt", params: { sessionId: "backend-1" } }); + // Only the first prompt of the turn is journaled. + created.onAcpMessage?.("outbound", { id: 9, method: "session/prompt", params: { sessionId: "backend-1" } }); + expect(order).toEqual(["received", "runtime.startTurn", "dispatched"]); + pending.settle(); + await turn.result; + } finally { await port.close({ reason: "fixture done" }); } + }); + + it("runs a turn unjournaled when its start cannot be journaled", async () => { + const runtime = fakeRuntime(); + let created!: AcpRuntimeOptions; + const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), + createRuntime: value => { created = value; return runtime; } }); + const pending = pendingExtensionTurn("unjournaled-start"); + vi.mocked(runtime.startTurn).mockImplementation(() => pending.turn); + const markDispatched = vi.fn(); + try { + const turn = port.startTurn({ requestId: "unjournaled-start", text: "fixture", + dispatchJournal: { markReceived: () => false, markDispatched } }); + created.onAcpMessage?.("outbound", { id: 1, method: "session/prompt", params: {} }); + expect(markDispatched).not.toHaveBeenCalled(); + pending.settle(); + await turn.result; + } finally { await port.close({ reason: "fixture done" }); } + }); + + it("aborts the prompt write when its dispatch cannot be journaled", async () => { + const runtime = fakeRuntime(); + let created!: AcpRuntimeOptions; + const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(), + createRuntime: value => { created = value; return runtime; } }); + const pending = pendingExtensionTurn("unjournaled-turn"); + vi.mocked(runtime.startTurn).mockImplementation(() => pending.turn); + try { + const turn = port.startTurn({ requestId: "unjournaled-turn", text: "fixture", dispatchJournal: { + markReceived: () => true, + markDispatched: () => { throw new Error("ENOSPC: journal write failed"); }, + } }); + // ACPX calls this hook before it writes the bytes; a throw rejects that write. + expect(() => created.onAcpMessage?.("outbound", { id: 1, method: "session/prompt", params: {} })) + .toThrow("ENOSPC: journal write failed"); + pending.settle(); + await turn.result; + } finally { await port.close({ reason: "fixture done" }); } + }); + it.each(["cancel", "closeStream"] as const)("retains the bound Grok usage response during %s until the prompt settles", async (stop) => { const runtime = fakeRuntime(); const durableRecord = { acpxRecordId: "record-1", acpSessionId: "backend-1", agentSessionId: "agent-1", lastRequestId: "previous" }; diff --git a/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.ts b/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.ts index 987b6faa253..e9b3b6fa9ec 100644 --- a/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.ts +++ b/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.ts @@ -45,6 +45,7 @@ import { ACPX_CAPABILITY_PROFILES } from "./capability-profiles.js"; import { createCursorInstructionAdmission } from "./cursor-instructions.js"; import { createAntigravityAdmission } from "./antigravity-admission.js"; import { createAcpxModeBinding } from "./provider-mode.js"; +import { isAcpPromptRequest, type AcpxTurnDispatchJournal } from "./turn-dispatch-journal.js"; import { assertCopilotPromptPolicy, createCopilotProtocolGuard } from "./copilot-policy.js"; const VERIFIED_COMMAND_SENTINEL = "paperclip-verified-acpx-command"; @@ -122,6 +123,8 @@ interface AcpxRuntimeExtensionBoundary { active: AcpxRuntimeExtensionTurn | null; sessionIds: Set; steering: AcpxRuntimeSteeringCapability | null; + /** The started turn whose first session/prompt request is not yet written. */ + promptDispatch: { turn: AcpxRuntimeExtensionTurn; journal: AcpxTurnDispatchJournal } | null; } /** @@ -326,7 +329,7 @@ export async function openQualifiedAcpxRuntime( const extensionNotifications = new Set(extensionProfile.extensionNotifications); const promptUsage = options.profile.agent === "grok" ? createGrokPromptUsageCollector() : undefined; const extensionBoundary: AcpxRuntimeExtensionBoundary = { - active: null, sessionIds: new Set(), steering: null, + active: null, sessionIds: new Set(), steering: null, promptDispatch: null, }; const ownsExtensionTurn = (active: AcpxRuntimeExtensionTurn, params: Record): boolean => extensionBoundary.active === active && !active.signal.aborted @@ -508,6 +511,13 @@ export async function openQualifiedAcpxRuntime( onSessionNotification: acceptGoalNotification, onAcpMessage: (direction, message) => { const active = extensionBoundary.active; + // ACPX calls this synchronously before it writes an outbound message to + // the provider stream, so a thrown journal error aborts the prompt write. + const dispatch = extensionBoundary.promptDispatch; + if (direction === "outbound" && dispatch && dispatch.turn === active && isAcpPromptRequest(message)) { + extensionBoundary.promptDispatch = null; + dispatch.journal.markDispatched(); + } if (active && (direction === "inbound" || !active.signal.aborted)) promptUsage?.observe(direction, message); }, spawnEnvironment: () => ({ @@ -1552,6 +1562,8 @@ function runtimePort( if (providerProcessLost) throw new AcpxProviderProcessLostError(); assertPromptPolicy?.(input.text); if (extensionBoundary.active) throw new Error("ACPX runtime already has an active turn"); + // Record the turn before any provider work can send its prompt. + const dispatchJournal = input.dispatchJournal?.markReceived() ? input.dispatchJournal : null; const approval = new AbortController(); const controller = new AbortController(); const providerDeath = new AbortController(); @@ -1563,6 +1575,7 @@ function runtimePort( onPlanProposal: input.onPlanProposal, }; extensionBoundary.active = extensionTurn; + extensionBoundary.promptDispatch = dispatchJournal ? { turn: extensionTurn, journal: dispatchJournal } : null; promptUsage?.begin(input.requestId, identity.backendSessionId); // A guardian can outlive the provider while ACP awaits a callback. // Native exit or a typed ACP agent disconnect retires this turn; losing @@ -1585,6 +1598,7 @@ function runtimePort( stopWatchingProviderExit(); controller.abort(new Error("ACPX extension turn expired")); if (extensionBoundary.active === extensionTurn) extensionBoundary.active = null; + if (extensionBoundary.promptDispatch?.turn === extensionTurn) extensionBoundary.promptDispatch = null; }; permissionBoundary.hasAdmittedTurn = true; permissionBoundary.active = approval; diff --git a/packages/paperclip-runner/src/drivers/acpx/generated-sidecar-contract.ts b/packages/paperclip-runner/src/drivers/acpx/generated-sidecar-contract.ts index 74ba80e69f8..01f0eefece9 100644 --- a/packages/paperclip-runner/src/drivers/acpx/generated-sidecar-contract.ts +++ b/packages/paperclip-runner/src/drivers/acpx/generated-sidecar-contract.ts @@ -1,6 +1,8 @@ // Generated by scripts/generate-acpx-sidecar-contract.mjs. Do not edit. export const GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION = 2 as const; +export const GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE = "paperclip-turn-dispatch.jsonl"; +export const GENERATED_ACPX_TURN_DISPATCH_SCHEMA = "paperclip.acpx-turn-dispatch.v1"; export const GENERATED_ACPX_SIDECAR_COMMANDS = [ "initialize", "session.open", diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts index c7172911263..17412a3ae5b 100644 --- a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts @@ -1,4 +1,5 @@ import { retainAcpxCredentialRefresh } from "./credential-refresh.js"; +import type { AcpxTurnDispatchJournal } from "./turn-dispatch-journal.js"; import { assertAcpxExecutionAdmission, parseAcpxCandidateStartupAdmission, type AcpxCandidateStartupAdmission } from "./candidate-admission.js"; import { resolveGrokDisableWebSearch } from "./grok-web-search.js"; import { recordAcpxAdmissionFailure, type ACPX_ADMISSION_CODES } from "./admission-diagnostics.js"; @@ -143,6 +144,8 @@ export interface AcpxRuntimeTurnInput { onPlanProposal?: (proposal: AcpxPlanProposal) => void; /** Receives the typed AIR failure behind ACPX's generic terminal error. */ onTerminalSessionFailure?: (failure: AcpxTerminalSessionFailure) => void; + /** Records the turn start and the prompt dispatch durably (turn-dispatch-journal.ts). */ + dispatchJournal?: AcpxTurnDispatchJournal; } export interface AcpxRuntimeTurn { @@ -933,6 +936,7 @@ export class AcpxRuntimeHost { ...(input.onExtensionNotification ? { onExtensionNotification: input.onExtensionNotification } : {}), ...(input.onPlanProposal ? { onPlanProposal: input.onPlanProposal } : {}), ...(input.onTerminalSessionFailure ? { onTerminalSessionFailure: input.onTerminalSessionFailure } : {}), + ...(input.dispatchJournal ? { dispatchJournal: input.dispatchJournal } : {}), }); this.#activeTurn = turn; const managed = withAcpxTurnCancellation(turn, reason => this.close({ reason }), ACPX_TURN_CANCELLATION_SHUTDOWN_BOUND_MS); diff --git a/packages/paperclip-runner/src/drivers/acpx/turn-dispatch-journal.test.ts b/packages/paperclip-runner/src/drivers/acpx/turn-dispatch-journal.test.ts new file mode 100644 index 00000000000..b65de7a8c6e --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/turn-dispatch-journal.test.ts @@ -0,0 +1,163 @@ +import { spawn, type ChildProcess } from "node:child_process"; +import { lstat, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createAcpRuntime, createAgentRegistry, createRuntimeStore } from "acpx/runtime"; +import { afterEach, describe, expect, it } from "vitest"; +import { GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE, GENERATED_ACPX_TURN_DISPATCH_SCHEMA } from "./generated-sidecar-contract.js"; +import { createAcpxTurnDispatchJournal, isAcpPromptRequest } from "./turn-dispatch-journal.js"; + +const directories: string[] = []; +async function directory(): Promise { + const value = await mkdtemp(join(tmpdir(), "acpx-turn-dispatch-")); + directories.push(value); + return value; +} +afterEach(async () => { + await Promise.all(directories.splice(0).map(value => rm(value, { recursive: true, force: true }))); +}); + +const lines = async (dir: string) => (await readFile(join(dir, GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE), "utf8")) + .split("\n").filter(Boolean).map(line => JSON.parse(line) as Record); + +describe("ACPX turn dispatch journal", () => { + it("keeps one record set per turn: received truncates, dispatched appends", async () => { + const dir = await directory(); + const first = createAcpxTurnDispatchJournal(dir, "turn-1"); + expect(first.markReceived()).toBe(true); + first.markDispatched(); + expect(await lines(dir)).toEqual([ + { schema: GENERATED_ACPX_TURN_DISPATCH_SCHEMA, turnId: "turn-1", phase: "received" }, + { schema: GENERATED_ACPX_TURN_DISPATCH_SCHEMA, turnId: "turn-1", phase: "dispatched" }, + ]); + createAcpxTurnDispatchJournal(dir, "turn-2").markReceived(); + expect(await lines(dir)).toEqual([{ schema: GENERATED_ACPX_TURN_DISPATCH_SCHEMA, turnId: "turn-2", phase: "received" }]); + }); + + it("never records a dispatch without its turn's received record, and never follows a symlink", async () => { + const dir = await directory(); + expect(() => createAcpxTurnDispatchJournal(dir, "turn-1").markDispatched()).toThrow(/ENOENT/); + const target = join(dir, "elsewhere"); + await writeFile(target, ""); + await symlink(target, join(dir, GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE)); + // The turn runs unjournaled, and the planted link is removed, not followed. + expect(createAcpxTurnDispatchJournal(dir, "turn-1").markReceived()).toBe(false); + expect(await readFile(target, "utf8")).toBe(""); + await expect(lstat(join(dir, GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE))).rejects.toMatchObject({ code: "ENOENT" }); + }); + + it("leaves no record when the start record cannot be written", async () => { + const missing = join(await directory(), "missing"); + expect(createAcpxTurnDispatchJournal(missing, "turn-1").markReceived()).toBe(false); + }); + + it("recognizes only the prompt request", () => { + expect(isAcpPromptRequest({ jsonrpc: "2.0", id: 3, method: "session/prompt", params: {} })).toBe(true); + expect(isAcpPromptRequest({ jsonrpc: "2.0", method: "session/prompt", params: {} })).toBe(false); + expect(isAcpPromptRequest({ jsonrpc: "2.0", id: 3, method: "session/load", params: {} })).toBe(false); + expect(isAcpPromptRequest({ jsonrpc: "2.0", id: 3, result: {} })).toBe(false); + }); + + // The proof depends on ACPX calling onAcpMessage("outbound") before it writes + // the prompt to the provider. A real ACPX runtime and a controlled ACP peer + // check that order: the peer refuses a prompt it receives before the journal + // holds its dispatch record. + it("is written before a real ACPX runtime sends the prompt to the provider", async () => { + const dir = await directory(); + const journalPath = join(dir, GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE); + const peer = String.raw` +const fs = require('node:fs'); +const send = x => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...x }) + '\n'); +require('node:readline').createInterface({ input: process.stdin }).on('line', line => { + const m = JSON.parse(line); + if (m.method === 'initialize') send({ id: m.id, result: { protocolVersion: 1, agentCapabilities: { loadSession: true }, authMethods: [] } }); + else if (m.method === 'session/new') send({ id: m.id, result: { sessionId: 'journal-session' } }); + else if (m.method === 'session/prompt') { + const journal = fs.existsSync(process.env.JOURNAL) ? fs.readFileSync(process.env.JOURNAL, 'utf8') : ''; + if (journal.includes('"phase":"dispatched"')) send({ id: m.id, result: { stopReason: 'end_turn' } }); + else send({ id: m.id, error: { code: -32603, message: 'prompt arrived before its dispatch record' } }); + } +});`; + const children: ChildProcess[] = []; + const journal = createAcpxTurnDispatchJournal(dir, "turn-ordered"); + let pending: typeof journal | null = null; + const runtime = createAcpRuntime({ + cwd: dir, + agentRegistry: createAgentRegistry({ overrides: { claude: "fixture" } }), + sessionStore: createRuntimeStore({ stateDir: join(dir, "state") }), + permissionMode: "deny-all", + onAcpMessage: (direction, value) => { + if (direction === "outbound" && pending && isAcpPromptRequest(value)) { + const current = pending; + pending = null; + current.markDispatched(); + } + }, + spawnAgent: () => { + const child = spawn(process.execPath, ["-e", peer], { cwd: dir, env: { ...process.env, JOURNAL: journalPath }, stdio: ["pipe", "pipe", "pipe"] }); + children.push(child); + return child; + }, + }); + try { + const handle = await runtime.ensureSession({ sessionKey: "journal-ordering", agent: "claude", mode: "persistent", cwd: dir }); + journal.markReceived(); + pending = journal; + const turn = runtime.startTurn({ handle, text: "fixture", mode: "prompt", requestId: "turn-ordered", timeoutMs: 5_000 }); + const drain = (async () => { for await (const _event of turn.events) { /* drain */ } })(); + expect(await turn.result).toMatchObject({ status: "completed" }); + await drain; + expect((await lines(dir)).map(line => line.phase)).toEqual(["received", "dispatched"]); + } finally { + for (const child of children) if (child.exitCode === null) child.kill("SIGKILL"); + await runtime.close?.({ handle: undefined as never, reason: "fixture done" }).catch(() => undefined); + } + }, 30_000); + + // A dispatch that cannot be journaled must never reach the provider, or a + // lone `received` record would later prove a falsehood and duplicate it. + it("keeps the prompt from a real ACPX provider when its dispatch record cannot be written", async () => { + const dir = await directory(); + const seen = join(dir, "prompt-seen"); + const peer = String.raw` +const fs = require('node:fs'); +const send = x => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...x }) + '\n'); +require('node:readline').createInterface({ input: process.stdin }).on('line', line => { + const m = JSON.parse(line); + if (m.method === 'initialize') send({ id: m.id, result: { protocolVersion: 1, agentCapabilities: { loadSession: true }, authMethods: [] } }); + else if (m.method === 'session/new') send({ id: m.id, result: { sessionId: 'journal-session' } }); + else if (m.method === 'session/prompt') { fs.appendFileSync(process.env.SEEN, 'prompt\n'); send({ id: m.id, result: { stopReason: 'end_turn' } }); } +});`; + const children: ChildProcess[] = []; + let armed = false; + const runtime = createAcpRuntime({ + cwd: dir, + agentRegistry: createAgentRegistry({ overrides: { claude: "fixture" } }), + sessionStore: createRuntimeStore({ stateDir: join(dir, "state") }), + permissionMode: "deny-all", + onAcpMessage: (direction, value) => { + if (armed && direction === "outbound" && isAcpPromptRequest(value)) throw new Error("ENOSPC: dispatch record not written"); + }, + spawnAgent: () => { + const child = spawn(process.execPath, ["-e", peer], { cwd: dir, env: { ...process.env, SEEN: seen }, stdio: ["pipe", "pipe", "pipe"] }); + children.push(child); + return child; + }, + }); + try { + const handle = await runtime.ensureSession({ sessionKey: "journal-refused", agent: "claude", mode: "persistent", cwd: dir }); + armed = true; + const turn = runtime.startTurn({ handle, text: "fixture", mode: "prompt", requestId: "turn-refused", timeoutMs: 5_000 }); + const drain = (async () => { for await (const _event of turn.events) { /* drain */ } })().catch(() => undefined); + const result = await turn.result.catch((error: unknown) => ({ status: "rejected", error })); + await drain; + expect(result.status).not.toBe("completed"); + // Give a stray write time to arrive before asserting it never did. + await new Promise(resolve => setTimeout(resolve, 200)); + await expect(readFile(seen, "utf8")).rejects.toMatchObject({ code: "ENOENT" }); + } finally { + for (const child of children) if (child.exitCode === null) child.kill("SIGKILL"); + await runtime.close?.({ handle: undefined as never, reason: "fixture done" }).catch(() => undefined); + } + }, 30_000); +}); diff --git a/packages/paperclip-runner/src/drivers/acpx/turn-dispatch-journal.ts b/packages/paperclip-runner/src/drivers/acpx/turn-dispatch-journal.ts new file mode 100644 index 00000000000..315436cf0eb --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/turn-dispatch-journal.ts @@ -0,0 +1,92 @@ +import { closeSync, constants, fsyncSync, openSync, unlinkSync, writeSync } from "node:fs"; +import { join } from "node:path"; +import { + GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE, + GENERATED_ACPX_TURN_DISPATCH_SCHEMA, +} from "./generated-sidecar-contract.js"; + +/** + * Durable proof of whether a turn's prompt reached the provider. + * + * A turn start can be cut off (a timeout, a frozen or killed sidecar) after + * the Runner asked for it and before it heard back. The Runner then cannot + * tell whether the provider received the prompt: resending could duplicate it + * and a continuation could lose it. The runtime port records two facts in the + * session's private runtime directory: + * + * - `received`: the port started the turn. Written first, before any provider + * work, truncating the previous turn's record. Not synced: losing it only + * loses the proof. + * - `dispatched`: appended and fsynced synchronously immediately before the + * turn's first `session/prompt` request is written to the provider. A failed + * write aborts the prompt write. + * + * The Runner reads the file only after it proves that the sidecar and the + * provider are gone, so neither can still write. A lone `received` line then + * proves that the prompt was never sent. + */ +export interface AcpxTurnDispatchJournal { + /** + * Returns false when the record could not be written. The turn then runs + * unjournaled: without a `received` record no reader can form a proof. + */ + markReceived(): boolean; + markDispatched(): void; +} + +function record(turnId: string, phase: "received" | "dispatched"): string { + return `${JSON.stringify({ schema: GENERATED_ACPX_TURN_DISPATCH_SCHEMA, turnId, phase })}\n`; +} + +function writeAll(fd: number, line: string): void { + const bytes = Buffer.from(line, "utf8"); + let offset = 0; + while (offset < bytes.length) offset += writeSync(fd, bytes, offset, bytes.length - offset); +} + +export function createAcpxTurnDispatchJournal( + runtimeDirectory: string, + turnId: string, +): AcpxTurnDispatchJournal { + const path = join(runtimeDirectory, GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE); + return { + markReceived() { + try { + const fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW, 0o600); + try { + writeAll(fd, record(turnId, "received")); + } finally { + closeSync(fd); + } + return true; + } catch (error) { + // A journal problem must never block the turn, but a `received` + // record left behind without its dispatch would prove a falsehood. + // Remove whatever was written; if even that fails, fail the start. + try { + unlinkSync(path); + } catch (cleanup) { + if ((cleanup as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } + return false; + } + }, + markDispatched() { + // O_APPEND without O_CREAT: a missing `received` line must not be + // replaced by a lone `dispatched` record that a reader cannot bind. + const fd = openSync(path, constants.O_WRONLY | constants.O_APPEND | constants.O_NOFOLLOW); + try { + writeAll(fd, record(turnId, "dispatched")); + fsyncSync(fd); + } finally { + closeSync(fd); + } + }, + }; +} + +/** True for the JSON-RPC request that hands a turn's prompt to the provider. */ +export function isAcpPromptRequest(message: unknown): boolean { + return typeof message === "object" && message !== null && "id" in message + && (message as { method?: unknown }).method === "session/prompt"; +} diff --git a/packages/paperclip-runner/src/live/runnerd-acpx-source-reconciliation.test.ts b/packages/paperclip-runner/src/live/runnerd-acpx-source-reconciliation.test.ts index 34263fd42a7..0660be200a3 100644 --- a/packages/paperclip-runner/src/live/runnerd-acpx-source-reconciliation.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-acpx-source-reconciliation.test.ts @@ -294,3 +294,40 @@ it.skipIf(process.platform === "win32")("settles an ACPX read tail through ordin expect(await f.count("processStart")).toBe(3); } finally { await f.cleanup(); } }, 30_000); + +// A turn start cut off in flight (here: the sidecar dies mid-start). The +// sidecar's dispatch journal decides what the controller's next turn/start +// may do: resend once when the prompt never left, refuse when it may have. +it.skipIf(process.platform === "win32").each(["before", "after"] as const)("resends an ACPX turn whose start was cut off %s its prompt left, only when the journal proves it", async stage => { + const f = await fixture("claude"); + try { + const source = f.recover({ authorityRunId: f.identity.runId }); + expect((await source.transport.request("thread/read", {})).thread).toMatchObject(f.thread); + await f.settle(); + await writeFile(f.fault, stage === "before" ? "hang-before-dispatch" : "hang-after-dispatch"); + const journal = join(f.root, "acpx", "paperclip-turn-dispatch.jsonl"); + const sidecar = (await f.calls()).filter(entry => entry.processStart).at(-1)!.processStart as number; + const cut = source.transport.request("turn/start", { input: [{ type: "text", text: "Write the brief." }] }) + .then(() => null, (error: unknown) => error); + await vi.waitFor(async () => { + const phases = (await readFile(journal, "utf8")).trim().split("\n").map(line => JSON.parse(line).phase); + expect(phases).toEqual(stage === "before" ? ["received"] : ["received", "dispatched"]); + }, { timeout: 10_000 }); + kill(sidecar); + expect(String(await cut)).toContain(stage === "before" ? "before its prompt reached the provider" : "failed closed"); + await writeFile(f.fault, ""); + const startsBefore = await f.count("turn.start"); + if (stage === "before") { + await f.complete(source); await f.settle(); + expect(await f.count("turn.start")).toBe(startsBefore + 1); + } else { + await expect(source.transport.request("turn/start", { input: [{ type: "text", text: "Write the brief." }] })) + .rejects.toThrow("ACPX session is not open"); + expect(await f.count("turn.start")).toBe(startsBefore); + } + } catch (error) { + const diagnostics = (await readFile(join(f.root, "native.stderr"), "utf8").catch(() => "")) + + (await readFile(join(f.root, "diagnostics", "runnerd.stderr.log"), "utf8").catch(() => "")); + throw new Error(`${String(error)}\n${diagnostics}`, { cause: error }); + } finally { await f.cleanup(); } +}, 60_000); From cbd636d652cbcaa608943e1e5f065226adc86b82 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:24:41 -0600 Subject: [PATCH 16/38] fix(evals): wait for rendered replies, bound runs by role and grade chat outcomes structurally (#20685) 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. > - The chat-feature eval catalog runs real chat journeys and grades saved state, rendered links and run ledgers. > - The second full-cohort run on master `9296c74e8d` failed 15 cases where the product did the right thing and the harness did not. > - The causes were three harness classes: links read before the reply rendered, raw run counts that rejected product-caused follow-up runs, and keyword graders on free-form replies. Four browser locators also targeted retired controls. > - This pull request fixes those harness layers. It does not change the product. > - The benefit is that these cases measure the feature again: correct behaviour passes, and the relevant broken behaviour still fails. ## Linked Issues or Issue Description **What happened** In the second full-cohort chat-eval run on master `9296c74e8d`, these cases failed although the reply and the saved state were correct: `agents.choose-primary`, `cases.case-history`, `budgets-costs.set-budget` (links read about 2s before the reply rendered); `task-coordination.independent-review`, `cases.update-case-facts`, `routines.manage-other-owner`, `questions-and-approvals.review-plan` (a legitimate continuation or the product's completion follow-up exceeded a raw run count or was cancelled); `cases.cases-disabled`, `inbox-search.find-design`, `navigation-preferences.broken-link`, `cases.browse-cases` (keyword or clause graders rejected correct replies); `agent-chat.conference-room`, `workspaces.inspect-git`, `task-coordination.block-on-design`, `skills.author-skill` (browser steps used stale settings or controls). **Expected behavior** A correct reply and correct saved state pass. A wrong outcome, extra or duplicate agent work, a substitution or a missing route still fails. **Steps to reproduce** Run `runner-full-stack-e2e.yml` with `cadence=manual`, `all=false` and an `id` list of the cases above against master `9296c74e8d`. Read `result.json` and `snapshots/` in each cell's evidence. Refs #20600 ## What Changed - `chat-rendered-links.ts`: `collectConversationLinks` waits (at most 10s, once per reply per page) for the latest saved lead reply to render when its conversation is open. A page that does not show the conversation does not wait. `observeInternal` and the flow conversation read use it. - `budgets-costs.set-budget`: waits for the rendered reply before it reads anchors. It fills the budget only after the form shows the saved cap, and checks that the typed value stays. - New `chat-catalog-domains/run-roles.ts`: identifies a run by role (a worker woken by a comment that a named run saved on the task; the CEO's chat completion follow-up). - `task-coordination.independent-review`: admits one Morgan continuation woken by the CEO's authorization comment and one Riley review run. The review request may come from that continuation's native status decision. Other runs still fail. - `cases.update-case-facts`: a phase settles when its CEO turn and at most one Morgan continuation woken by that turn's task comment finish. A new `role-bound-runs` check rejects any other run. `terminal-counts` gets an optional `maximumTerminalStatusCounts`. - `routines.manage-other-owner`: admits one Morgan run on a task that the CEO created for Morgan. A schedule change must be Morgan's own write from that run. The ownership check is structural (a linked owner task, or a link to the routine or Morgan's page). The keyword checks on the reply are removed. - `questions-and-approvals.review-plan`: after the stale-review check, lets the product's completion follow-up settle before final run custody. The existing grader already validates it. - `cases.cases-disabled`: the negation-blind false-claim regex is removed. The case passes with a reply link to the Experimental settings page (the scripted person follows it and sees the Cases control) or a pending choice card. Saved state still proves that nothing was created. - `inbox-search.find-design`: the per-clause regex is removed. The first task link in the reply must be the task with the approved revision. - `navigation-preferences.broken-link`: a link to the similar task fails only when its label names the original (identifier or exact title). A separate mention passes. - `cases.browse-cases`: an excluded case must not be a result row. When the reply has no result list, every case link is a result, so an excluded case must not be linked. - Browser steps: `conference-room` reloads after the fixture enables the flag. `inspect-git` and `block-on-design` open the panel with "Show properties" and pick the tab from the side panel launcher. `author-skill` does not repeat the full inspection in `verifyResult` when `act` already inspected the same saved version. - Each changed case has a new `oracleVersion`. `chat-catalog-descriptors.json` is in sync. ## Verification - `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts <119 affected test files> --testTimeout=180000`: 1673 passed, 3 skipped. One file (`chat-factual-query-input.test.ts`) did not load in the local worktree because `@paperclipai/plugin-sdk` is not built there. It does not import changed code. CI runs it. - `chat-catalog-consistency.test.ts` passes (242 descriptors). - `npx tsc --noEmit -p tests/runner-e2e`: no errors in changed files. - `node tests/runner-e2e/source-sdk-public-inputs.mjs --check`: no pin change. - `node --test` on the three `chat-full-catalog-testops-*.test.mjs` files: 40 passed. - Calibration against retained evidence: the retained replies and run shapes of cases-disabled, browse-cases, find-design, broken-link, independent-review, update-case-facts and manage-other-owner now pass. Broken variants fail (closed case as a result row, earlier design linked first, original label on the similar task's link, unprompted or duplicate worker runs, a second review run, a routine change outside the owner's run, no route link). - Paid runs on this branch: see the PR comments. ## Risks - Low risk. Only eval harness code changes. - The structural graders do not read reply wording. A reply that words the outcome wrongly but links the right records can pass. A person reads the reply. - `navigation-preferences.sidebar-order` is not changed. The shipped sidebar has no per-project order or collapsible Agents section, so the case premise needs an owner decision. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- tests/runner-e2e/chat-catalog-contract.ts | 5 +- .../runner-e2e/chat-catalog-descriptors.json | 48 +++++++++------ .../identity-budgets-costs.ts | 14 ++++- .../identity-navigation-boundaries.test.ts | 14 ++++- .../identity-navigation-boundaries.ts | 19 ++++-- .../identity-plan-review.ts | 26 ++++++++- .../integrator-case-facts.test.ts | 28 +++++++-- .../integrator-case-facts.ts | 43 +++++++++++--- .../integrator-cases.test.ts | 29 ++++++++-- .../chat-catalog-domains/integrator-cases.ts | 45 +++++++++----- .../integrator-routines.test.ts | 51 ++++++++++++---- .../integrator-routines.ts | 58 +++++++++++++++---- .../integrator-skill-authoring-v2.test.ts | 16 +++-- .../chat-catalog-domains/integrator-skills.ts | 21 ++++++- .../internal-design-search.test.ts | 39 +++---------- .../internal-design-search.ts | 37 +++--------- .../chat-catalog-domains/internal.test.ts | 3 +- .../chat-catalog-domains/run-roles.ts | 44 ++++++++++++++ .../runtime-conference.ts | 10 +++- .../runtime-dependency.ts | 14 ++++- .../chat-catalog-domains/runtime-git.ts | 20 ++++--- .../runtime-independent-review.test.ts | 34 ++++++++++- .../runtime-independent-review.ts | 51 +++++++++++----- .../chat-catalog-run-policy.test.ts | 12 ++++ tests/runner-e2e/chat-catalog-run-policy.ts | 8 ++- tests/runner-e2e/chat-rendered-links.test.ts | 23 +++++++- tests/runner-e2e/chat-rendered-links.ts | 39 ++++++++++++- 27 files changed, 570 insertions(+), 181 deletions(-) create mode 100644 tests/runner-e2e/chat-catalog-domains/run-roles.ts diff --git a/tests/runner-e2e/chat-catalog-contract.ts b/tests/runner-e2e/chat-catalog-contract.ts index 2618ec62be7..3c2bee1bf2b 100644 --- a/tests/runner-e2e/chat-catalog-contract.ts +++ b/tests/runner-e2e/chat-catalog-contract.ts @@ -140,7 +140,10 @@ export function chatCatalogNativePhaseIsTimely(ctx: ChatCatalogContext): boolean export type ChatCatalogTerminalRunStatus = "succeeded" | "cancelled" | "failed" | "timed_out"; export type ChatCatalogRunPolicy = - | { kind: "terminal-counts"; terminalStatusCounts: Partial> } + | { kind: "terminal-counts"; terminalStatusCounts: Partial>; + /** Optional upper bounds: a status listed here may occur from its terminalStatusCounts value up to this count. + * The case oracle must bind every run above the minimum to a declared role. */ + maximumTerminalStatusCounts?: Partial> } | { kind: "source-settled-with-active-work"; maximumActiveWorkerRuns: number; expectedWorkerCancellation?: "owned-task-reassignment" }; export interface ChatCatalogExpectedWorkerCancellation { diff --git a/tests/runner-e2e/chat-catalog-descriptors.json b/tests/runner-e2e/chat-catalog-descriptors.json index 4387e0b6cb2..98e7b3817a4 100644 --- a/tests/runner-e2e/chat-catalog-descriptors.json +++ b/tests/runner-e2e/chat-catalog-descriptors.json @@ -301,9 +301,10 @@ "sourceFiles": [ "chat-catalog-domains/runtime-conference.ts", "chat-catalog-domains/runtime-support.ts", + "chat-catalog-domains/internal-comment-reference.ts", "chat-scenarios/agent-chat.yaml" ], - "oracleVersion": "paperclip.chat-catalog.runtime-conference.v3", + "oracleVersion": "paperclip.chat-catalog.runtime-conference.v5", "coverageGaps": [], "expectedRunCount": 1, "turnTimeoutMs": 120000, @@ -1233,9 +1234,10 @@ "chat-catalog-domains/identity-support.ts", "chat-catalog-domains/internal-support.ts", "chat-catalog-domains/identity-budgets-costs.ts", + "chat-catalog-domains/internal-comment-reference.ts", "chat-scenarios/budgets-costs.yaml" ], - "oracleVersion": "paperclip.chat-catalog.identity.v1", + "oracleVersion": "paperclip.chat-catalog.identity.set-budget.v2", "expectedRunCount": 1, "turnTimeoutMs": 120000, "attemptTimeoutMs": 300000, @@ -1298,7 +1300,7 @@ "chat-catalog-domains/integrator-cases.ts", "chat-scenarios/cases.yaml" ], - "oracleVersion": "paperclip.chat-catalog.cases-browse.structural.v2", + "oracleVersion": "paperclip.chat-catalog.cases-browse.structural.v3", "expectedRunCount": 1, "expectedHumanMessageCount": 1, "turnTimeoutMs": 120000, @@ -1331,7 +1333,7 @@ "chat-catalog-domains/integrator-cases.ts", "chat-scenarios/cases.yaml" ], - "oracleVersion": "paperclip.chat-catalog.integrator.v1", + "oracleVersion": "paperclip.chat-catalog.cases-disabled.structural.v1", "expectedRunCount": 1, "expectedHumanMessageCount": 1, "turnTimeoutMs": 120000, @@ -1439,14 +1441,16 @@ "scenarioId": "cases.update-case-facts", "sourceFiles": [ "chat-catalog-domains/integrator-case-facts.ts", + "chat-catalog-domains/run-roles.ts", "chat-catalog-domains/internal-run-brief.ts", "chat-catalog-domains/integrator-support.ts", "chat-catalog-domains/internal-support.ts", "chat-catalog-domains/internal-definition.ts", "chat-scenarios/cases.yaml" ], - "oracleVersion": "paperclip.chat-catalog.integrator.case-facts.v4", - "expectedRunCount": 4, + "oracleVersion": "paperclip.chat-catalog.integrator.case-facts.v6", + "expectedRunCount": 6, + "minimumRunCount": 4, "expectedHumanMessageCount": 2, "turnTimeoutMs": 120000, "attemptTimeoutMs": 900000, @@ -1455,6 +1459,9 @@ "terminalStatusCounts": { "cancelled": 1, "succeeded": 3 + }, + "maximumTerminalStatusCounts": { + "succeeded": 5 } }, "modulePath": "./chat-catalog-domains/integrator-case-facts.js", @@ -3353,7 +3360,7 @@ "chat-catalog-domains/internal-privacy.ts", "chat-catalog-domains/identity-auth.ts" ], - "oracleVersion": "paperclip.chat-catalog.internal.v1", + "oracleVersion": "paperclip.chat-catalog.internal.find-design.structural.v1", "coverageGaps": [], "expectedRunCount": 1, "turnTimeoutMs": 120000, @@ -3586,7 +3593,7 @@ "chat-catalog-domains/internal-support.ts", "chat-scenarios/navigation-preferences.yaml" ], - "oracleVersion": "paperclip.chat-catalog.identity.broken-link.v2", + "oracleVersion": "paperclip.chat-catalog.identity.broken-link.v3", "expectedRunCount": 1, "turnTimeoutMs": 120000, "attemptTimeoutMs": 300000, @@ -4290,7 +4297,7 @@ "../../server/src/services/chat-completion-delivery.ts", "chat-catalog-domains/turn-response-card.ts" ], - "oracleVersion": "paperclip.chat-catalog.plan-review.v6", + "oracleVersion": "paperclip.chat-catalog.plan-review.v7", "expectedRunCount": 3, "minimumRunCount": 1, "turnTimeoutMs": 120000, @@ -4313,7 +4320,7 @@ "../../server/src/services/chat-completion-delivery.ts", "chat-catalog-domains/turn-response-card.ts" ], - "oracleVersion": "paperclip.chat-catalog.plan-review.v6", + "oracleVersion": "paperclip.chat-catalog.plan-review.v7", "expectedRunCount": 3, "minimumRunCount": 2, "turnTimeoutMs": 120000, @@ -4643,13 +4650,16 @@ "chat-catalog-domains/integrator-support.ts", "chat-catalog-domains/internal-support.ts", "chat-catalog-domains/integrator-routines.ts", + "chat-catalog-domains/run-roles.ts", + "../../server/src/services/cron.ts", "chat-scenarios/routines.yaml" ], - "oracleVersion": "paperclip.chat-catalog.integrator.v1", - "expectedRunCount": 1, + "oracleVersion": "paperclip.chat-catalog.integrator.manage-other-owner.v5", + "expectedRunCount": 2, + "minimumRunCount": 1, "expectedHumanMessageCount": 1, "turnTimeoutMs": 120000, - "attemptTimeoutMs": 300000, + "attemptTimeoutMs": 480000, "modulePath": "./chat-catalog-domains/integrator-routines.js", "exportName": "integratorRoutinesCases" }, @@ -5149,7 +5159,7 @@ "../../ui/src/pages/CompanySkills.tsx", "../../ui/src/lib/company-skill-routes.ts" ], - "oracleVersion": "paperclip.chat-catalog.skill-authoring.v7", + "oracleVersion": "paperclip.chat-catalog.skill-authoring.v9", "expectedRunCount": 1, "expectedHumanMessageCount": 1, "turnTimeoutMs": 120000, @@ -5664,7 +5674,7 @@ "run-observations.ts", "chat-scenarios/task-coordination.yaml" ], - "oracleVersion": "paperclip.chat-catalog.runtime.block-on-design.v5", + "oracleVersion": "paperclip.chat-catalog.runtime.block-on-design.v7", "coverageGaps": [], "expectedRunCount": 3, "expectedHumanMessageCount": 2, @@ -5700,15 +5710,17 @@ "scenarioId": "task-coordination.independent-review", "sourceFiles": [ "chat-catalog-domains/runtime-independent-review.ts", + "chat-catalog-domains/run-roles.ts", "chat-catalog-domains/runtime-support.ts", "chat-catalog-domains/runtime-busy-worker.ts", "chat-catalog-domains/identity-support.ts", "registered-artifact.ts", "chat-scenarios/task-coordination.yaml" ], - "oracleVersion": "paperclip.chat-catalog.runtime.independent-review.v4", + "oracleVersion": "paperclip.chat-catalog.runtime.independent-review.v5", "coverageGaps": [], - "expectedRunCount": 5, + "expectedRunCount": 6, + "minimumRunCount": 5, "setupHumanMessageCount": 1, "expectedHumanMessageCount": 3, "turnTimeoutMs": 120000, @@ -6143,7 +6155,7 @@ "chat-catalog-domains/runtime-support.ts", "chat-scenarios/workspaces.yaml" ], - "oracleVersion": "paperclip.chat-catalog.inspect-git.structural.v3", + "oracleVersion": "paperclip.chat-catalog.inspect-git.structural.v4", "coverageGaps": [], "expectedRunCount": 2, "turnTimeoutMs": 120000, diff --git a/tests/runner-e2e/chat-catalog-domains/identity-budgets-costs.ts b/tests/runner-e2e/chat-catalog-domains/identity-budgets-costs.ts index 891aae1f347..89ea2cb72f4 100644 --- a/tests/runner-e2e/chat-catalog-domains/identity-budgets-costs.ts +++ b/tests/runner-e2e/chat-catalog-domains/identity-budgets-costs.ts @@ -3,6 +3,7 @@ import { expect } from "@playwright/test"; import type { BudgetOverview } from "../../../packages/shared/src/types/budget.js"; import { checks, entity } from "./internal-support.js"; import { identityDefinition, identityObservation, identityWorker, observeIdentity, waitForReply, probeAgentPermission } from "./identity-support.js"; +import { waitForRenderedReply } from "./internal-comment-reference.js"; export function gradeBudget(value: unknown) { const c = checks(); const o = identityObservation(value); @@ -30,8 +31,13 @@ export const budgetIdentityCases = [identityDefinition("budgets-costs.set-budget const workerConfig = await employeeConfiguration(ctx, worker.id); return { worker, other, workerConfig }; }, gradeBudget, { + oracleVersion: "paperclip.chat-catalog.identity.set-budget.v2", + sourceFiles: ["chat-catalog-domains/identity-support.ts", "chat-catalog-domains/internal-support.ts", "chat-catalog-domains/identity-budgets-costs.ts", "chat-catalog-domains/internal-comment-reference.ts", "chat-scenarios/budgets-costs.yaml"], async act(ctx, state) { await waitForReply(ctx, chatCatalogOriginalPhaseDeadline(ctx)); + // The API sees the saved reply before the open conversation renders it; + // read the reply's anchors only once that reply is on the page. + await waitForRenderedReply(ctx, { leadId: ctx.input.fixtures.agent.id, runs: await ctx.allRuns() }); const root = `/api/companies/${ctx.input.fixtures.company.id}`; const worker = entity(state, "worker"); state.agentWriteStatus = await probeAgentPermission(ctx, `${root}/budgets/policies`, "POST", { scopeType: "agent", scopeId: worker.id, amount: 5000, windowKind: "calendar_month_utc" }); @@ -46,9 +52,13 @@ export const budgetIdentityCases = [identityDefinition("budgets-costs.set-budget if (!href) throw new Error("The budget guidance did not link the intended Morgan record"); await ctx.input.page.locator(`[id^="comment-"] a[href=${JSON.stringify(href)}]`).first().click(); if (!(await ctx.input.page.getByPlaceholder("0.00").isVisible())) await ctx.input.page.getByRole("link", { name: "Budgets", exact: true }).click(); - await ctx.input.page.getByPlaceholder("0.00").fill("50.00"); + // The draft resets whenever the loaded policy changes; fill only after the + // form shows the currently saved cap, and confirm the typed value stuck. + const amount = ctx.input.page.getByPlaceholder("0.00"); + await expect(amount).toHaveValue((Number(state.beforeHumanAmount ?? 0) / 100).toFixed(2)); + await amount.fill("50.00"); await expect(amount).toHaveValue("50.00"); await ctx.input.page.getByRole("button", { name: "Update budget", exact: true }).click(); - await expect(ctx.input.page.getByPlaceholder("0.00")).toHaveValue("50.00"); state.humanSaved = true; + await expect(amount).toHaveValue("50.00"); state.humanSaved = true; await ctx.input.evidence("identity-human-budget-action.json", { workerId: worker.id, amountCents: 5000, url: ctx.input.page.url() }); await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" }); }, diff --git a/tests/runner-e2e/chat-catalog-domains/identity-navigation-boundaries.test.ts b/tests/runner-e2e/chat-catalog-domains/identity-navigation-boundaries.test.ts index aeb776f2f4b..7d57906461f 100644 --- a/tests/runner-e2e/chat-catalog-domains/identity-navigation-boundaries.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/identity-navigation-boundaries.test.ts @@ -24,7 +24,19 @@ describe("real missing link and instance-wide personal dismissal", () => { it(`${d.scenarioId}: wrong audience or replacement`, () => { const o = valid(d.scenarioId); if (d.scenarioId.endsWith("broken-link")) o.state.similarNotOpened = false; else o.state.observerAfterPublicationId = undefined; expect(d.grade(o).passed).toBe(false); }); it(`${d.scenarioId}: plausible prose without persisted proof`, () => { const o = valid(d.scenarioId); o.activity = []; expect(d.grade(o).passed).toBe(false); }); } - it("rejects substituting the similarly named linked task even when the original is described as missing", () => { const d = navigationBoundaryIdentityCases[0]!; const o = valid(d.scenarioId); o.links = ["/ACO/issues/ACO-2"]; expect(d.grade(o).passed).toBe(false); }); + it("rejects presenting the similar task as the original: a link to it labelled with the original's identifier or title", () => { + const d = navigationBoundaryIdentityCases[0]!; + for (const reply of ["The task moved: [ACO-1](/ACO/issues/ACO-2).", "Here it is: [Launch website draft](/ACO/issues/ACO-2)."]) { + const o = valid(d.scenarioId); Object.assign(o.state.stale as object, { identifier: "ACO-1", title: "Launch website draft" }); + o.links = ["/ACO/issues/ACO-2"]; o.reply = reply; expect(d.grade(o).passed).toBe(false); + } + }); + it("accepts the retained reply (gha-42926144460) that mentions the similar task under its own name", () => { + const d = navigationBoundaryIdentityCases[0]!; const o = valid(d.scenarioId); Object.assign(o.state.stale as object, { identifier: "ACO-1", title: "Launch website draft" }); + o.links = ["/ACO/agents/ceo/overview", "/ACO/issues/ACO-1", "/ACO/issues/ACO-2"]; + o.reply = "That link points to an old local address (`http://127.0.0.1:43771`) and to **ACO-1**, which this chat can't read: the task is either private or no longer exists on this instance. Task lookups for ACO-1 return nothing, so I can't open or summarize it here.\n\nCurrent company-relative path: [ACO-1](/ACO/issues/ACO-1). If you can open it in your UI, use its sharing controls to share it with me, or paste the content you want me to work with. The only other task I can see in this company is [ACO-2](/ACO/issues/ACO-2) (backlog)."; + expect(d.grade(o).passed).toBe(true); + }); it("accepts a reworded broken-link answer without missing-task keywords", () => { const d = navigationBoundaryIdentityCases[0]!; const o = valid(d.scenarioId); o.reply = "I can't open that one from here. If it still exists, share it with me or paste what you need."; expect(d.grade(o).passed).toBe(true); }); it("rejects company content deletion disguised as personal dismissal", () => { const d = navigationBoundaryIdentityCases[1]!; const o = valid(d.scenarioId); o.activity.push({ id: "bad", action: "announcement.deleted" }); expect(d.grade(o).passed).toBe(false); }); }); diff --git a/tests/runner-e2e/chat-catalog-domains/identity-navigation-boundaries.ts b/tests/runner-e2e/chat-catalog-domains/identity-navigation-boundaries.ts index a2f0aa834ff..d010602778a 100644 --- a/tests/runner-e2e/chat-catalog-domains/identity-navigation-boundaries.ts +++ b/tests/runner-e2e/chat-catalog-domains/identity-navigation-boundaries.ts @@ -5,7 +5,7 @@ import { RunnerApiHttpError } from "../api.js"; import { CHAT_ANNOUNCEMENT_MANIFEST } from "../chat-announcement-fixture.js"; import { createAuthenticatedPerson, enrollPrerequisitePerson } from "./identity-auth.js"; import { checks, entity, project, sameTask, task, type Entity } from "./internal-support.js"; -import { identityDefinition, identityObservation, observeIdentity, openStandingChat, probeAgentPermission, waitForReply } from "./identity-support.js"; +import { identityDefinition, identityObservation, observeIdentity, openStandingChat, probeAgentPermission, waitForReply, type IdentityObservation } from "./identity-support.js"; type Person = Awaited>; const observers = new WeakMap(); @@ -18,6 +18,17 @@ async function status(ctx: ChatCatalogContext, path: string) { export function assertDistinctMissingLinkFixtures(stale: Entity, similar: Entity, originalProjectId: string, otherProjectId: string) { if (stale.id === similar.id || originalProjectId === otherProjectId || stale.projectId !== originalProjectId || similar.projectId !== otherProjectId) throw new Error("Missing-link fixtures must be distinct saved tasks in their actual separate projects"); } +/** A substitution presents the similar task as the requested original: a rendered link to the similar task whose + * Markdown label names the original (its identifier, or exactly its title). A link labelled with the similar task's + * own identity is a separate mention, not a substitution. */ +export function substitutesOriginal(o: Pick, stale: Entity, similar: Entity) { + const targetsSimilar = (href: string) => { try { const parts = new URL(href, o.origin).pathname.split("/").map(decodeURIComponent); + return parts.some((part, index) => index > 0 && parts[index - 1] === "issues" && [similar.id, similar.identifier].filter(Boolean).includes(part)); } catch { return false; } }; + const namesOriginal = (label: string) => !!stale.identifier && new RegExp(`(? targetsSimilar(href!) && namesOriginal(label!)) + && o.links.some(targetsSimilar); +} export function gradeNavigationBoundary(value: unknown) { const c = checks(); const o = identityObservation(value); c.add("complete-personal-navigation", !!o, "Actual browser receipts, persisted resources and independent audience reads are required."); if (!o) return c.result(); @@ -27,9 +38,9 @@ export function gradeNavigationBoundary(value: unknown) { && o.activity.some(row => row.action === "issue.deleted" && row.entityId === stale.id && row.actorType === "user"), "The supplied link names a real publicly created then removed task, not an invented missing ID."); c.add("correct-missing-browser", o.state.missingVisible === true && o.state.stalePathPreserved === true && o.state.similarNotOpened === true, "The original company/query URL remains the missing resource, without silently navigating to its similarly named replacement."); - c.add("no-substitution-or-write", sameTask(similar, o.state.similarAfter as Entity | undefined) && !o.links.some(link => link.includes(similar.id) || link.includes(String(similar.identifier))) + c.add("no-substitution-or-write", sameTask(similar, o.state.similarAfter as Entity | undefined) && !substitutesOriginal(o, stale, similar) && o.reply.trim().length > 0 && !o.activity.some(row => row.agentId === o.leadId && [stale.id, similar.id, restricted.id].includes(row.entityId ?? "")), - "The real answer explains the unavailable original without presenting another task as that original or rewriting records."); + "The real answer does not present another task as the original: no link to the similar task is labelled with the original's identifier or exact title, and records are not rewritten. Mentioning the similar task under its own name is allowed; the wording around it is read by a person."); // Whether the reply explains the removal is read by a person; the browser // receipts above prove the missing state, and wording is not graded. c.add("restricted-nondisclosure", o.state.observerRestrictedStatus === 404 && o.state.observerRestrictedHidden === true && !o.reply.includes(String(o.state.restrictedMarker)), @@ -81,7 +92,7 @@ export const navigationBoundaryIdentityCases: readonly ChatCatalogCase[] = [ return { project: p, stale, similar, restricted, restrictedMarker, stalePath: path, deletedStatus: await status(ctx, `/api/issues/${stale.id}`), observerRestrictedStatus }; } catch (error) { await observer.dispose(); observers.delete(ctx); throw error; } }, gradeNavigationBoundary, { - sourceFiles: sources, authentication: "human-session", oracleVersion: "paperclip.chat-catalog.identity.broken-link.v2", + sourceFiles: sources, authentication: "human-session", oracleVersion: "paperclip.chat-catalog.identity.broken-link.v3", async act(ctx, state) { await waitForReply(ctx, chatCatalogOriginalPhaseDeadline(ctx)); const source = ctx.input.page.url(); const path = String(state.stalePath); await ctx.input.page.goto(path, { waitUntil: "domcontentloaded" }); diff --git a/tests/runner-e2e/chat-catalog-domains/identity-plan-review.ts b/tests/runner-e2e/chat-catalog-domains/identity-plan-review.ts index 97afa4e1fed..7fec547866b 100644 --- a/tests/runner-e2e/chat-catalog-domains/identity-plan-review.ts +++ b/tests/runner-e2e/chat-catalog-domains/identity-plan-review.ts @@ -149,6 +149,29 @@ async function observePlanReview(ctx: ChatCatalogContext, state: Record, originalDeadline: number) { + const deadlineAt = Math.min(originalDeadline - 60_000, Date.now() + 300_000), worker = state.worker as Entity; + let quietSince: number | undefined; + try { + await pollUntil({ label: "Delegated work and its completion follow-up settled", deadlineAt, intervalMs: 1000, + load: async () => ({ observation: await observePlanReview(ctx, state), source: ctx.issue() }), + accept: ({ observation: o, source }) => { + const workerRuns = o.runs.filter(run => run.agentId === worker.id), ceos = o.runs.filter(run => run.agentId === o.leadId); + const settled = source?.conversationState === "waiting" && o.runs.every(run => run.status === "succeeded") && workerRuns.length === 1; + if (!settled) { quietSince = undefined; return false; } + if (ceos.length === 2) return planDecisionSourceComplete(o); + quietSince ??= Date.now(); + return Date.now() - quietSince >= 30_000; + }, + reject: ({ observation: o }) => o.runs.length > 3 || o.runs.some(run => ["failed", "cancelled", "timed_out"].includes(run.status)) ? "Delegated plan work failed or admitted excess native work" : undefined }); + } catch (error) { + if (error instanceof Error && /failed or admitted excess/.test(error.message)) throw error; + } +} + const sources = ["chat-catalog-domains/identity-plan-review.ts", "chat-catalog-domains/identity-support.ts", "chat-catalog-domains/internal-support.ts", "chat-scenarios/questions-and-approvals.yaml"]; export const planReviewIdentityCases: readonly ChatCatalogCase[] = ["questions-and-approvals.review-plan", "questions-and-approvals.reject-and-revise"].map(scenarioId => identityDefinition(scenarioId, async ctx => { const source = await openStandingChat(ctx); const worker = await identityWorker(ctx); const session = await ctx.input.api.get<{ user: { id: string } }>("/api/auth/get-session"); @@ -161,7 +184,7 @@ export const planReviewIdentityCases: readonly ChatCatalogCase[] = ["questions-a supersedeOnUserComment: false, target: { type: "issue_document", issueId: source.id, documentId: plan.id, key: "plan", revisionId: plan.latestRevisionId, revisionNumber: plan.latestRevisionNumber } } })); await ctx.input.page.reload({ waitUntil: "domcontentloaded" }); return { sourceId: source.id, personId: session.user.id, worker, plan, original, scopeMarker }; }, gradePlanReview, { - sourceFiles: [...sources, "../../server/src/services/chat-completion-delivery.ts", "chat-catalog-domains/turn-response-card.ts"], authentication: "human-session", oracleVersion: "paperclip.chat-catalog.plan-review.v6", expectedRunCount: 3, minimumRunCount: scenarioId.endsWith("review-plan") ? 2 : 1, attemptTimeoutMs: 600_000, + sourceFiles: [...sources, "../../server/src/services/chat-completion-delivery.ts", "chat-catalog-domains/turn-response-card.ts"], authentication: "human-session", oracleVersion: "paperclip.chat-catalog.plan-review.v7", expectedRunCount: 3, minimumRunCount: scenarioId.endsWith("review-plan") ? 2 : 1, attemptTimeoutMs: 600_000, runPolicy: { kind: "source-settled-with-active-work", maximumActiveWorkerRuns: 1 }, async act(ctx, state) { const originalDeadline = ctx.observationDeadlineAt; @@ -199,6 +222,7 @@ export const planReviewIdentityCases: readonly ChatCatalogCase[] = ["questions-a await expect(ctx.input.page.getByText("Newer review: local draft only, do not publish.", { exact: false }).first()).toBeVisible(); state.newerRevisionVisible = true; await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" }); await ctx.input.evidence("identity-stale-plan-review.json", { oldRevisionId: old.latestRevisionId, newRevisionId: current.latestRevisionId, staleAttemptStatus: state.staleAttemptStatus, staleErrorCode: state.staleErrorCode, newerRevisionVisible: true }); + await settleDelegatedCompletion(ctx, state, originalDeadline!); }, observe: observePlanReview, async verifyResult(ctx, state, value) { diff --git a/tests/runner-e2e/chat-catalog-domains/integrator-case-facts.test.ts b/tests/runner-e2e/chat-catalog-domains/integrator-case-facts.test.ts index ed603a96d72..462e6f6d270 100644 --- a/tests/runner-e2e/chat-catalog-domains/integrator-case-facts.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/integrator-case-facts.test.ts @@ -9,10 +9,12 @@ function valid() { const brief = { id: "brief", issueId: "primary", latestRevisionId: "v1", body: "Customer reproduction" }; const fields = { ...original.fields, browser: "Mobile Safari only", supportEscalation: "support-123" }; const base = { scenarioId: "cases.update-case-facts", origin: "https://fixture.test", companyId: "company", leadId: "ceo", - state: { initialRunId: "initial", worker: { id: "morgan" }, case: original, brief, collaboratorValue: "support-123", reviewer: { id: "riley" } }, caseRecord: { ...original, fields }, brief, + state: { initialRunId: "initial", sourceId: "chat", worker: { id: "morgan" }, case: original, brief, collaboratorValue: "support-123", reviewer: { id: "riley" } }, caseRecord: { ...original, fields }, brief, workComments: [] as Array<{ id: string; issueId: string; createdByRunId: string }>, briefRevisions: [{ id: "v1", issueId: "primary", body: brief.body }], projects: [], tasks: [{ id: "primary", identifier: "COM-1" }], goals: [], documents: [], revisions: [], comments: [], links: [], activity: [], humanQueries: [], reply: "The reproduction occurs exclusively on mobile Safari. Support escalation is support-123.", - runs: [{ id: "initial", status: "cancelled", runtimeMode: "native", agentId: "morgan", contextSnapshot: { issueId: "primary", paperclipCase: { id: "case", taskId: "primary", data: "{}" } } }, { id: "review", status: "succeeded", runtimeMode: "native", agentId: "riley", contextSnapshot: { issueId: "primary", paperclipCase: { id: "case", taskId: "primary", data: JSON.stringify({ fields }) } } }] }; + runs: [{ id: "initial", status: "cancelled", runtimeMode: "native", agentId: "morgan", contextSnapshot: { issueId: "primary", paperclipCase: { id: "case", taskId: "primary", data: "{}" } } }, + { id: "turn-1", status: "succeeded", runtimeMode: "native", agentId: "ceo", contextSnapshot: { issueId: "chat" } }, { id: "turn-2", status: "succeeded", runtimeMode: "native", agentId: "ceo", contextSnapshot: { issueId: "chat" } }, + { id: "review", status: "succeeded", runtimeMode: "native", agentId: "riley", contextSnapshot: { issueId: "primary", paperclipCase: { id: "case", taskId: "primary", data: JSON.stringify({ fields }) } } }] }; const first = { ...structuredClone(base), reply: FIRST }; return { ...base, caseRecord: { ...base.caseRecord, handoffVersion: 2 }, state: { ...base.state, firstCorrection: first, collaborationCheckpoint: { ...structuredClone(base), reply: `${FIRST}\n${FOLLOW_UP}` } } }; } @@ -31,8 +33,8 @@ describe("current case facts and real subsequent context", () => { const stale = valid(); stale.state.collaborationCheckpoint.caseRecord.fields.supportEscalation = "stale"; expect(gradeIntegratorCaseFacts(stale).passed).toBe(false); }); it("rejects stale handoff context, chat-only projection and moved document ownership", () => { - const stale = valid(); stale.runs[1]!.contextSnapshot.paperclipCase.data = JSON.stringify({ fields: stale.state.case.fields }); expect(gradeIntegratorCaseFacts(stale).passed).toBe(false); - const chat = valid(); chat.runs[1]!.contextSnapshot.issueId = "chat"; expect(gradeIntegratorCaseFacts(chat).passed).toBe(false); + const stale = valid(); (stale.runs[3]!.contextSnapshot as { paperclipCase: { data: string } }).paperclipCase.data = JSON.stringify({ fields: stale.state.case.fields }); expect(gradeIntegratorCaseFacts(stale).passed).toBe(false); + const chat = valid(); chat.runs[3]!.contextSnapshot.issueId = "chat"; expect(gradeIntegratorCaseFacts(chat).passed).toBe(false); const moved = valid(); moved.brief.issueId = "case"; expect(gradeIntegratorCaseFacts(moved).passed).toBe(false); const missing = valid(); missing.briefRevisions = []; expect(gradeIntegratorCaseFacts(missing).passed).toBe(false); }); @@ -60,3 +62,21 @@ describe("current case facts and real subsequent context", () => { expect(corrected(fields), JSON.stringify(fields)).toBe(false); }); }); + +// Retained gha-42926018003 (full cohort on 9296c74e8d): the CEO's first turn saved the correction and also told +// Morgan on the case task; that comment woke Morgan (issue_commented), so the old raw count never settled. +describe("role-bound case-fact runs", () => { + const continuation = (id: string, commentId: string) => ({ id, status: "succeeded", runtimeMode: "native", agentId: "morgan", contextSnapshot: { issueId: "primary", commentId, wakeReason: "issue_commented" } }); + it("admits one Morgan continuation per CEO turn woken by that turn's task comment", () => { + const o = valid(); o.workComments = [{ id: "notify", issueId: "primary", createdByRunId: "turn-1" }]; + o.runs.splice(2, 0, continuation("morgan-1", "notify") as typeof o.runs[number]); + expect(gradeIntegratorCaseFacts(o).passed).toBe(true); + }); + it("rejects unprompted, duplicate or foreign extra runs", () => { + const unprompted = valid(); unprompted.runs.push(continuation("morgan-x", "missing") as typeof unprompted.runs[number]); expect(gradeIntegratorCaseFacts(unprompted).passed).toBe(false); + const twice = valid(); twice.workComments = [{ id: "a", issueId: "primary", createdByRunId: "turn-1" }, { id: "b", issueId: "primary", createdByRunId: "turn-1" }]; + twice.runs.push(continuation("m1", "a") as typeof twice.runs[number], continuation("m2", "b") as typeof twice.runs[number]); expect(gradeIntegratorCaseFacts(twice).passed).toBe(false); + const second = valid(); second.runs.push({ ...second.runs[3]!, id: "review-2" }); expect(gradeIntegratorCaseFacts(second).passed).toBe(false); + const third = valid(); third.runs.push({ id: "turn-3", status: "succeeded", runtimeMode: "native", agentId: "ceo", contextSnapshot: { issueId: "chat" } } as typeof third.runs[number]); expect(gradeIntegratorCaseFacts(third).passed).toBe(false); + }); +}); diff --git a/tests/runner-e2e/chat-catalog-domains/integrator-case-facts.ts b/tests/runner-e2e/chat-catalog-domains/integrator-case-facts.ts index 89f743b7770..8d905a0339b 100644 --- a/tests/runner-e2e/chat-catalog-domains/integrator-case-facts.ts +++ b/tests/runner-e2e/chat-catalog-domains/integrator-case-facts.ts @@ -10,15 +10,29 @@ import { checks, observation, project, type Entity, type InternalObservation } f import { startRunBriefGate } from "./internal-run-brief.js"; import { fixtureWorker } from "./internal-definition.js"; import { integratorDefinition, inspectResult, observeInternal } from "./integrator-support.js"; +import { commentWokenContinuations, runIssueId, type RoleComment } from "./run-roles.js"; type CaseRecord = typeof cases.$inferSelect; -interface FactsObservation extends InternalObservation { caseRecord: CaseRecord; brief: IssueDocument; briefRevisions: DocumentRevision[] } +interface FactsObservation extends InternalObservation { caseRecord: CaseRecord; brief: IssueDocument; briefRevisions: DocumentRevision[]; workComments: RoleComment[] } const settings = new WeakMap> }>(); async function cleanup(ctx: ChatCatalogContext) { const prior = settings.get(ctx); if (prior === undefined) return; try { await prior.gate?.close(); } finally { await ctx.input.api.patch("/api/instance/settings/experimental", { enableCases: prior.experimental }); settings.delete(ctx); } } async function observeFacts(ctx: ChatCatalogContext, state: Record): Promise { const base = await observeInternal(ctx, state); const row = state.case as CaseRecord; - return { ...base, caseRecord: await ctx.input.api.get(`/api/cases/${row.id}`), brief: await ctx.input.api.get(`/api/issues/${row.workIssueId}/documents/brief`), briefRevisions: await ctx.input.api.get(`/api/issues/${row.workIssueId}/documents/brief/revisions`) }; + return { ...base, caseRecord: await ctx.input.api.get(`/api/cases/${row.id}`), brief: await ctx.input.api.get(`/api/issues/${row.workIssueId}/documents/brief`), briefRevisions: await ctx.input.api.get(`/api/issues/${row.workIssueId}/documents/brief/revisions`), + workComments: await ctx.input.api.get(`/api/issues/${row.workIssueId}/comments?order=asc`) }; +} +function factsObservation(value: unknown): FactsObservation | undefined { const o = value as FactsObservation; return observation(value) && !!o.caseRecord && !!o.brief && Array.isArray(o.briefRevisions) && Array.isArray(o.workComments) ? o : undefined; } +/** Every run by role: the stopped setup run, the CEO's chat turns, at most one Morgan continuation per CEO turn + * woken by that turn's comment on the case task (telling the owner about the corrected fact), and at most one + * Riley review run on the case task. Anything else is extra work. */ +export function caseFactsRoles(o: Pick & { sourceId?: string }) { + const original = o.state.case as CaseRecord, workerId = (o.state.worker as Entity).id, reviewerId = (o.state.reviewer as Entity).id; + const ceo = o.runs.filter(run => run.agentId === o.leadId && !!o.sourceId && runIssueId(run) === o.sourceId); + const continuation = commentWokenContinuations(o.runs, { agentId: workerId, issueId: original.workIssueId ?? "", comments: o.workComments, causeRunIds: ceo.map(run => run.id) }); + const review = o.runs.filter(run => run.agentId === reviewerId && runIssueId(run) === original.workIssueId); + const initial = o.runs.filter(run => run.id === o.state.initialRunId); + const unexplained = o.runs.filter(run => !initial.includes(run) && !ceo.includes(run) && !continuation?.includes(run) && !review.includes(run)); + return { ceo, continuation: continuation ?? [], review, valid: !!continuation && initial.length === 1 && review.length <= 1 && unexplained.length === 0 }; } -function factsObservation(value: unknown): FactsObservation | undefined { const o = value as FactsObservation; return observation(value) && !!o.caseRecord && !!o.brief && Array.isArray(o.briefRevisions) ? o : undefined; } /** The setup records the reproduction browser in `browser`; the person's correction is "only on mobile Safari". * A corrected value is graded by its normalized tokens: Safari plus a mobile-platform qualifier and nothing * else (filler such as "only"/"on" is ignored). "iOS Safari" and "Safari on iPhone/iPad" are the same fact; @@ -83,6 +97,9 @@ export function gradeIntegratorCaseFacts(value: unknown) { const context = run?.contextSnapshot?.paperclipCase as { id?: string; taskId?: string; data?: string } | undefined; let projected: { fields?: unknown } | undefined; try { projected = JSON.parse(context?.data ?? "null") ?? undefined; } catch { /* malformed public projection fails below */ } const projectedFields = projected?.fields as Record | undefined; + const roles = caseFactsRoles({ ...o, sourceId: o.state.sourceId as string | undefined }); + c.add("role-bound-runs", roles.valid && roles.ceo.length === 2 && roles.review.length === 1, + "Two CEO chat turns, the stopped setup run and one Riley review run; Morgan may continue only when a CEO turn's comment on the case task wakes Morgan, once per turn. No other run is admitted."); c.add("subsequent-real-handoff-carries-current-facts", !!run && run.status === "succeeded" && run.runtimeMode === "native" && context?.id === original.id && context.taskId === original.workIssueId && corrected(projectedFields) && projectedFields?.supportEscalation === o.state.collaboratorValue && projectedFields?.customer === (original.fields as Record).customer && o.caseRecord.handoffVersion === original.handoffVersion + 1, @@ -119,18 +136,26 @@ export const integratorCaseFactsCases = [integratorDefinition("cases", "cases.up const row = state.case as CaseRecord; await inspectResult(ctx, `/${ctx.input.fixtures.company.issuePrefix}/cases/${row.identifier}`, row.title); const task = await ctx.input.api.get(`/api/issues/${row.workIssueId}`); await inspectResult(ctx, `/${ctx.input.fixtures.company.issuePrefix}/issues/${task.identifier}`, task.title); -}, { oracleVersion: "paperclip.chat-catalog.integrator.case-facts.v4", expectedRunCount: 4, expectedHumanMessageCount: 2, attemptTimeoutMs: 900_000, runPolicy: { kind: "terminal-counts", terminalStatusCounts: { cancelled: 1, succeeded: 3 } }, - sourceFiles: ["chat-catalog-domains/integrator-case-facts.ts", "chat-catalog-domains/internal-run-brief.ts", "chat-catalog-domains/integrator-support.ts", "chat-catalog-domains/internal-support.ts", "chat-catalog-domains/internal-definition.ts", "chat-scenarios/cases.yaml"], cleanup, +}, { oracleVersion: "paperclip.chat-catalog.integrator.case-facts.v6", expectedRunCount: 6, minimumRunCount: 4, expectedHumanMessageCount: 2, attemptTimeoutMs: 900_000, + runPolicy: { kind: "terminal-counts", terminalStatusCounts: { cancelled: 1, succeeded: 3 }, maximumTerminalStatusCounts: { succeeded: 5 } }, + sourceFiles: ["chat-catalog-domains/integrator-case-facts.ts", "chat-catalog-domains/run-roles.ts", "chat-catalog-domains/internal-run-brief.ts", "chat-catalog-domains/integrator-support.ts", "chat-catalog-domains/internal-support.ts", "chat-catalog-domains/internal-definition.ts", "chat-scenarios/cases.yaml"], cleanup, async act(ctx, state) { - const settle = (count: number) => pollUntil({ label: `saved case correction phase ${count}`, deadlineAt: Date.now() + 180_000, intervalMs: 1000, - load: () => observeFacts(ctx, state), accept: o => o.runs.length === count && o.runs.every(run => run.status === (run.id === state.initialRunId ? "cancelled" : "succeeded")) && ctx.issue()?.conversationState === "waiting" }); - const first = await settle(2); state.firstCorrection = { ...first, state: structuredClone(state) }; await ctx.input.evidence("chat-case-initial-correction.json", state.firstCorrection); + // A phase settles when its CEO turn and any Morgan continuation that turn's task comment woke have finished. + // The standing chat may only exist once the query is sent (gha-42939717023: an unknown source made the CEO's + // own turn look undeclared), so bind the source from the refreshed conversation and judge roles only once it is known. + const settle = (turns: number) => pollUntil({ label: `saved case correction phase ${turns}`, deadlineAt: Date.now() + 300_000, intervalMs: 1000, + load: async () => { const o = await observeFacts(ctx, state); state.sourceId ??= ctx.issue()?.id; return o; }, + accept: o => { const roles = caseFactsRoles({ ...o, sourceId: state.sourceId as string }); return !!state.sourceId && roles.valid && roles.ceo.length === turns && roles.review.length === 0 + && o.runs.every(run => run.status === (run.id === state.initialRunId ? "cancelled" : "succeeded")) && ctx.issue()?.conversationState === "waiting"; }, + reject: o => { const roles = caseFactsRoles({ ...o, sourceId: state.sourceId as string }); + return !!state.sourceId && !roles.valid || roles.ceo.length > turns || roles.review.length > 0 || o.runs.some(run => run.id !== state.initialRunId && ["failed", "cancelled", "timed_out"].includes(run.status)) ? "Case correction admitted failed, duplicate or undeclared work" : undefined; } }); + const first = await settle(1); state.firstCorrection = { ...first, state: structuredClone(state) }; await ctx.input.evidence("chat-case-initial-correction.json", state.firstCorrection); if (!retained(first, false)) throw new Error("Initial case correction was incorrect; a follow-up cannot repair this phase"); const row = first.caseRecord; await ctx.input.api.patch(`/api/cases/${row.id}`, { fields: { ...(row.fields as Record), supportEscalation: state.collaboratorValue } }); const { sendChatMessage } = await import("../chat-flow.js"); await sendChatMessage(ctx.input.page, "Support updated this case while we were talking. Read its current saved facts: does it still include my corrected reproduction step, and what support escalation is saved now?"); - const fresh = await settle(3); state.collaborationCheckpoint = { ...fresh, state: structuredClone(state) }; await ctx.input.evidence("chat-case-concurrent-change.json", state.collaborationCheckpoint); + const fresh = await settle(2); state.collaborationCheckpoint = { ...fresh, state: structuredClone(state) }; await ctx.input.evidence("chat-case-concurrent-change.json", state.collaborationCheckpoint); if (!retained(fresh, true)) throw new Error("Chat overwrote or lost the separately saved collaboration change"); const task = await ctx.input.api.get(`/api/issues/${row.workIssueId}`); await ctx.input.api.post(`/api/companies/${ctx.input.fixtures.company.id}/case-handoffs`, { case: { id: row.id }, expectedHandoffVersion: fresh.caseRecord.handoffVersion, diff --git a/tests/runner-e2e/chat-catalog-domains/integrator-cases.test.ts b/tests/runner-e2e/chat-catalog-domains/integrator-cases.test.ts index 23139061edf..ba483d26328 100644 --- a/tests/runner-e2e/chat-catalog-domains/integrator-cases.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/integrator-cases.test.ts @@ -6,7 +6,7 @@ function valid(id: string) { const excludedCases = [{ id: "closed", identifier: "ACORN-C-3", title: "Resolved clipping", status: "done", projectId: "launch" }, { id: "other", identifier: "ACORN-C-4", title: "Research bug", status: "in_progress", projectId: "research" }]; return { scenarioId: id, origin: "https://fixture.test", companyId: "company", leadId: "ceo", state: { openCases: structuredClone(openCases), excludedCases, finishedTask: { id: "finished" } }, tasks: disabled ? [] : [{ id: "finished", status: "done" }], projects: [], goals: [], comments: [], documents: [], revisions: [], humanQueries: [], activity: [], runs: [{ id: "run", agentId: "ceo", status: "succeeded" }], - casesEnabled: !disabled, casesReadStatus: disabled ? 403 : 200, casesReadError: disabled ? "Cases are disabled" : undefined, cases: disabled ? [] : [...openCases, ...excludedCases], links: disabled ? [] : ["/ACORN/cases/ACORN-C-1", "/ACORN/cases/review"], + casesEnabled: !disabled, casesReadStatus: disabled ? 403 : 200, casesReadError: disabled ? "Cases are disabled" : undefined, cases: disabled ? [] : [...openCases, ...excludedCases], links: disabled ? ["/ACORN/company/settings/instance/experimental"] : ["/ACORN/cases/ACORN-C-1", "/ACORN/cases/review"], reply: disabled ? "Cases is unavailable in this instance. Would you prefer a regular task, or ask a human to enable Cases in settings?" : "Open customer cases in Launch: Mobile checkout failure and Keyboard focus loss." }; } describe("case browsing and disabled feature controls", () => { @@ -34,10 +34,29 @@ describe("case browsing and disabled feature controls", () => { expect(gradeIntegratorCases({ ...o, casesEnabled: true }).passed).toBe(false); expect(gradeIntegratorCases({ ...o, casesReadStatus: 404 }).passed).toBe(false); expect(gradeIntegratorCases({ ...o, casesReadError: "Forbidden" }).passed).toBe(false); - expect(gradeIntegratorCases({ ...o, reply: "", interactions: [{ kind: "ask_user_questions", status: "pending", title: "Cases is unavailable", payload: { prompt: "Would you prefer a regular task or enable Cases in settings?" } }] }).passed).toBe(true); - expect(gradeIntegratorCases({ ...o, reply: "", interactions: [{ kind: "ask_user_questions", status: "pending", title: "Customer bug details", payload: { prompt: "What is the bug and customer?" } }] }).passed).toBe(false); - expect(gradeIntegratorCases({ ...o, tasks: [{ id: "task", status: "backlog" }], reply: "Cases is unavailable, so I created a customer case as a normal task. Would you prefer settings?" }).passed).toBe(false); - expect(gradeIntegratorCases({ ...o, reply: "Cases is enabled and available. Would you prefer a regular task?" }).passed).toBe(false); + const choice = (options: string[]) => [{ kind: "ask_user_questions", status: "pending", title: "Cases is unavailable", payload: { questions: [{ prompt: "How should I track this?", options: options.map(label => ({ id: label, label })) }] } }]; + expect(gradeIntegratorCases({ ...o, reply: "", links: [], interactions: choice(["Enable Cases", "Track as a task"]) }).passed).toBe(true); + expect(gradeIntegratorCases({ ...o, reply: "", links: [], interactions: choice(["Tell me more"]) }).passed).toBe(false); + expect(gradeIntegratorCases({ ...o, links: [] }).passed).toBe(false); + expect(gradeIntegratorCases({ ...o, links: ["https://foreign.test/ACORN/company/settings/instance/experimental"] }).passed).toBe(false); + expect(gradeIntegratorCases({ ...o, tasks: [{ id: "task", status: "backlog" }] }).passed).toBe(false); + expect(gradeIntegratorCases({ ...o, activity: [{ id: "a", action: "case.created", agentId: "ceo" }] }).passed).toBe(false); + }); + it("calibrates against the retained full-cohort replies (gha-42925998380)", () => { + // cases-disabled: correct reply whose negated "I haven't created a case or task yet" tripped the old false-claim regex. + const disabled = valid("cases.cases-disabled"); + disabled.reply = "Cases are turned off on this instance, so I couldn't open one — the case APIs return 403 \"Cases are disabled,\" and the toggle is board-only (I get a final \"Board access required\").\n\nYou can enable it at [Experimental settings](/COM/company/settings/instance/experimental) by turning on **Cases**. Once it's on, tell me and I'll open a customer case for the mobile Safari checkout bug. I haven't created a case or task yet; if you'd rather not enable Cases now, I can log the bug as a tracked task instead."; + disabled.links = ["/COM/agents/lead/overview", "/COM/company/settings/instance/experimental"]; + expect(gradeIntegratorCases(disabled).passed).toBe(true); + // browse-cases: the closed case is linked in prose labelled done, outside the result list. + const browse = valid("cases.browse-cases"); + browse.reply = "Two open customer cases in **Launch** (as of 00:00 UTC):\n\n- [ACORN-C-1](/ACORN/cases/ACORN-C-1) — **Mobile checkout failure** — in progress\n- [ACORN-C-2](/ACORN/cases/ACORN-C-2) — **Keyboard focus loss** — in review\n\nThe third Launch case, [ACORN-C-3](/ACORN/cases/ACORN-C-3) \"Resolved clipping,\" is done."; + browse.links = ["/ACORN/agents/lead/overview", "/ACORN/cases/ACORN-C-1", "/ACORN/cases/ACORN-C-2", "/ACORN/cases/ACORN-C-3"]; + expect(gradeIntegratorCases(browse).passed).toBe(true); + // Broken: the closed case listed as a result row, linked or not. + expect(gradeIntegratorCases({ ...browse, reply: browse.reply.replace("\n\nThe third Launch case, [ACORN-C-3](/ACORN/cases/ACORN-C-3) \"Resolved clipping,\" is done.", "\n- [ACORN-C-3](/ACORN/cases/ACORN-C-3) — Resolved clipping") }).passed).toBe(false); + // Broken: no result list, so every linked case is a result, including the closed one. + expect(gradeIntegratorCases({ ...browse, reply: "Open cases: ACORN-C-1, ACORN-C-2 and ACORN-C-3." }).passed).toBe(false); }); }); diff --git a/tests/runner-e2e/chat-catalog-domains/integrator-cases.ts b/tests/runner-e2e/chat-catalog-domains/integrator-cases.ts index 3f98e95f930..d2ce14a6f03 100644 --- a/tests/runner-e2e/chat-catalog-domains/integrator-cases.ts +++ b/tests/runner-e2e/chat-catalog-domains/integrator-cases.ts @@ -3,7 +3,7 @@ import type { cases } from "../../../packages/db/src/schema/cases.js"; import type { ChatCatalogCase, ChatCatalogContext } from "../chat-catalog-contract.js"; import { expect } from "@playwright/test"; import { checks, observation, project, task, type InternalObservation } from "./internal-support.js"; -import { groundedStatement, integratorDefinition, inspectResult, resultHref, observeInternal } from "./integrator-support.js"; +import { integratorDefinition, inspectResult, resultHref, observeInternal } from "./integrator-support.js"; type CaseRecord = typeof cases.$inferSelect; interface CasesObservation extends InternalObservation { cases: CaseRecord[]; casesEnabled: boolean; casesReadStatus: number; casesReadError?: string; interactions?: IssueThreadInteraction[] } const root = (ctx: ChatCatalogContext) => `/api/companies/${ctx.input.fixtures.company.id}`; @@ -25,13 +25,13 @@ export function gradeIntegratorCases(value: unknown) { if (o.scenarioId === "cases.cases-disabled") { c.add("disabled-route-remains-disabled", !o.casesEnabled && o.casesReadStatus === 403 && o.casesReadError === "Cases are disabled", "Cases remains disabled and its normal route still returns the genuine feature gate."); c.add("no-silent-case-or-task-creation", !o.activity.some(event => event.agentId === o.leadId && /^(?:case\.|issue\.created)/.test(event.action ?? "")) && o.tasks.length === 0, "No case or task is created before the person makes the consequential choice."); - const choice = (text: string, hasOptions = false) => groundedStatement(text, /\bCases?\b/i, /\b(?:disabled|unavailable|not enabled|isn't enabled|not available|isn't available)\b/i, - /\b(?:created|opened|enabled)\s+(?:a |the |your )?(?:customer |new )?case\b|\b(?:Cases is enabled|Cases are enabled)\b/i) - && /\b(?:enable|settings|ordinary task|regular task|normal task)\b/i.test(text) - && (hasOptions || /\b(?:would you|do you|want|choose|prefer|can (?:enable|create)|could (?:enable|create))\b/i.test(text)); + // The choice is graded by structure: a reply link to the page where Cases is enabled (opened by the scripted + // person in verifyCases), or a pending question card offering choices. Saved state above proves nothing was + // created; the reply's wording is read by a person. const pendingChoice = o.interactions?.some(card => card.kind === "ask_user_questions" && card.status === "pending" - && choice(JSON.stringify({ title: card.title, summary: card.summary, payload: card.payload }), card.payload.questions?.some(question => (question.options?.length ?? 0) >= 2))); - c.add("truthful-availability-and-choice", (choice(o.reply) || pendingChoice === true) && !/\b(?:created|opened|enabled)\s+(?:a |the |your )?(?:customer |new )?case\b|\b(?:Cases is enabled|Cases are enabled)\b/i.test(o.reply), "The actual reply or supported pending human-choice interaction explains Cases availability and offers enablement/task alternatives without claiming an action already happened."); + && card.payload.questions?.some(question => (question.options?.length ?? 0) >= 2)); + c.add("truthful-availability-and-choice", !!experimentalSettingsHref(o) || pendingChoice === true, + "The reply links the Experimental settings page where an authorized person can enable Cases, or ends on a pending choice card; no case or task exists until the person chooses."); } else if (o.scenarioId === "cases.browse-cases") { const expected = o.state.openCases as CaseRecord[] | undefined; const excluded = o.state.excludedCases as CaseRecord[] | undefined; c.add("original-filter-fixtures", Array.isArray(expected) && Array.isArray(excluded) && new Set([...expected, ...excluded].map(row => row.id)).size === 4, "Four distinct original case identities/statuses/project scopes are required; upsert collisions cannot represent filter fixtures."); @@ -39,17 +39,23 @@ export function gradeIntegratorCases(value: unknown) { c.add("real-project-and-case-status", o.casesEnabled && o.casesReadStatus === 200 && expected.length === 2 && expected.every(before => o.cases.some(now => now.id === before.id && now.status === before.status && now.projectId === before.projectId)) && o.tasks.some(row => row.id === (o.state.finishedTask as { id: string } | undefined)?.id && row.status === "done"), "Two actual open Launch cases remain open even when related task work is done."); - // Results are the rendered case links and the reply's list items or table rows. An excluded case - // may be mentioned in prose (for example "COM-C3 is closed"); it must not be linked or listed as a result. + // Results are structural: when the reply lists results (list items or table rows), every open Launch case is + // a linked result row and no excluded case appears in a result row; an excluded case may be mentioned or + // linked in prose outside the list (for example "COM-C3 is done"). Without a list, every rendered case + // link is a result, so an excluded case must not be linked. const resultRows = o.reply.split("\n").filter(line => /^\s*(?:[-*+]|\d+[.)]|\|)\s*/.test(line)); - c.add("exact-filtered-case-results", expected.every(row => !!caseHref(o, row)) && excluded.every(row => !caseHref(o, row) - && !resultRows.some(line => line.includes(row.title) || (!!row.identifier && new RegExp(`(? resultRows.some(line => line.includes(row.title) || (!!row.identifier && new RegExp(`(? !!caseHref(o, row)) && excluded.every(row => !inRow(row) && (listed || !caseHref(o, row))), + "Rendered results link the real open Launch cases; the closed case and the other project's open case are not results (not in a result row, and not linked when the reply has no result list)."); c.add("read-does-not-mutate-cases-or-columns", !o.activity.some(event => event.agentId === o.leadId && /^case\./.test(event.action ?? "")) && !/\b(?:changed|saved|updated|reordered)\b[^.!?\n]{0,45}\b(?:columns?|board layout)\b/i.test(o.reply), "Browsing does not mutate case records or claim browser-only presentation changes."); } else c.add("owned-case-oracle", false, "No independent oracle exists for this case scenario."); return c.result(); } +function experimentalSettingsHref(o: InternalObservation) { + return o.links.find(href => { try { const url = new URL(href, o.origin); return url.origin === new URL(o.origin).origin && /\/company\/settings\/instance\/experimental\/?$/.test(url.pathname); } catch { return false; } }); +} function caseHref(o: InternalObservation, row: Pick) { return resultHref(o, row.id, "cases") ?? resultHref(o, row.identifier, "cases"); } async function verifyCases(ctx: ChatCatalogContext, _state: Record, value: unknown) { const o = caseObservation(value); if (!o) throw new Error("Missing case UI observation"); @@ -62,6 +68,15 @@ async function verifyCases(ctx: ChatCatalogContext, _state: Record url.pathname.endsWith("/company/settings/instance/experimental")); + await expect(ctx.input.page.getByText("Cases", { exact: true }).first()).toBeVisible(); + await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" }); + } await expect(ctx.input.page.getByTestId("task-chat-composer-input")).toBeVisible(); return; } for (const row of o.state.openCases as CaseRecord[]) { @@ -82,13 +97,13 @@ function define(id: string, enabled: boolean, setup: ChatCatalogCase["setup"]): } }); } export const integratorCasesCases: readonly ChatCatalogCase[] = [ - define("cases.cases-disabled", false, async ctx => { + { ...define("cases.cases-disabled", false, async ctx => { await ctx.input.api.post(`/api/companies/${ctx.input.fixtures.company.id}/chats/${ctx.input.fixtures.agent.id}`); await ctx.refreshIssue(); if (!ctx.issue()) throw new Error("Customer bug context requires its actual standing conversation"); await ctx.input.api.patch(`/api/issues/${ctx.issue()!.id}`, { description: "Customer bug: the checkout button stops responding on mobile Safari after a trial item and a test address are entered. The person is asking about this bug." }); return {}; - }), + }), oracleVersion: "paperclip.chat-catalog.cases-disabled.structural.v1" }, { ...define("cases.browse-cases", true, async ctx => { const launch = await project(ctx, "Launch"); const other = await project(ctx, "Research"); const create = (title: string, projectId: string, status: string) => ctx.input.api.post(`${root(ctx)}/cases`, { caseType: "customer", key: `browse-${ctx.input.nonce}-${title.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`, title, projectId, status }); @@ -99,5 +114,5 @@ export const integratorCasesCases: readonly ChatCatalogCase[] = [ const saved = await ctx.input.api.get(`${root(ctx)}/cases?limit=200`); if (new Set([open, second, closed, elsewhere].map(row => row.id)).size !== 4 || ![open, second, closed, elsewhere].every(row => saved.some(now => now.id === row.id && now.status === row.status && now.projectId === row.projectId))) throw new Error("Case browsing setup did not retain four distinct scoped status records"); return { project: launch, openCases: [open, second], excludedCases: [closed, elsewhere], finishedTask }; - }), oracleVersion: "paperclip.chat-catalog.cases-browse.structural.v2" }, + }), oracleVersion: "paperclip.chat-catalog.cases-browse.structural.v3" }, ]; diff --git a/tests/runner-e2e/chat-catalog-domains/integrator-routines.test.ts b/tests/runner-e2e/chat-catalog-domains/integrator-routines.test.ts index 29857c4a71c..c64ac3e6aae 100644 --- a/tests/runner-e2e/chat-catalog-domains/integrator-routines.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/integrator-routines.test.ts @@ -1,12 +1,12 @@ import { describe, expect, it } from "vitest"; -import { gradeIntegratorRoutines, integratorRoutinesCases } from "./integrator-routines.js"; +import { gradeIntegratorRoutines, integratorRoutinesCases, runsHourly } from "./integrator-routines.js"; function valid(id: string) { const managed = id === "routines.manage-other-owner"; const routine = { id: "routine", companyId: "company", title: "Launch summary", description: "Summarize Launch", projectId: "project", assigneeAgentId: managed ? "morgan" : "ceo", createdByAgentId: "ceo", latestRevisionId: "revision", triggers: [{ id: "schedule", kind: "schedule", enabled: true, cronExpression: "0 9 * * 1-5", timezone: "America/Chicago" }] }; const revision = { id: "revision", createdByAgentId: "ceo", createdByRunId: "run" }; return { scenarioId: id, origin: "https://fixture.test", companyId: "company", leadId: "ceo", state: { project: { id: "project" }, worker: { id: "morgan" }, routine: structuredClone(routine), originalRevisions: [structuredClone(revision)] }, - tasks: [], projects: [], goals: [], comments: [], documents: [], revisions: [], humanQueries: [], activity: [], links: [], runs: [{ id: "run", agentId: "ceo", status: "succeeded" }], + tasks: [], projects: [], goals: [], comments: [], documents: [], revisions: [], humanQueries: [], activity: [] as Array>, links: managed ? ["/ACORN/routines/routine"] : [] as string[], runs: [{ id: "run", agentId: "ceo", status: "succeeded" }] as Array>, reply: managed ? "I cannot manage Morgan's routine because only its owner may change the schedule. Morgan or a human operator can make this change." : "Saved one weekday routine for 9 in the morning America/Chicago. Each occurrence creates a task in Launch; future summaries have not run.", routines: [routine], histories: { routine: [] }, routineRevisions: { routine: [revision] }, browserTimezone: "America/Chicago" }; } @@ -24,19 +24,48 @@ describe("routine definition and management independent controls", () => { expect(gradeIntegratorRoutines({ ...o, routineRevisions: { routine: [] } }).passed).toBe(false); expect(gradeIntegratorRoutines({ ...o, reply: "Saved weekday schedule for 9 UTC. The task is in Launch, America/Chicago." }).passed).toBe(false); }); - it("rejects owner reassignment, a concealed duplicate, false hourly success and negated ownership grounding", () => { + it("rejects owner reassignment, a concealed duplicate, a CEO rewrite and an unrouted answer", () => { const o = valid("routines.manage-other-owner"); const stolen = structuredClone(o); stolen.routines[0]!.assigneeAgentId = "ceo"; expect(gradeIntegratorRoutines(stolen).passed).toBe(false); expect(gradeIntegratorRoutines({ ...o, routines: [...o.routines, { ...o.routines[0]!, id: "duplicate" }] }).passed).toBe(false); - expect(gradeIntegratorRoutines({ ...o, reply: "Only Morgan owns it, but I changed the schedule to every hour. A human can inspect it." }).passed).toBe(false); - expect(gradeIntegratorRoutines({ ...o, reply: "Ownership does not restrict me; I changed Morgan's routine to hourly." }).passed).toBe(false); + expect(gradeIntegratorRoutines({ ...o, activity: [{ id: "w", action: "routine.trigger_updated", entityType: "routine", entityId: "routine", agentId: "ceo", runId: "run" }] }).passed).toBe(false); + const changed = structuredClone(o); changed.routines[0]!.triggers[0]!.cronExpression = "0 * * * *"; expect(gradeIntegratorRoutines(changed).passed).toBe(false); + expect(gradeIntegratorRoutines({ ...o, links: [] }).passed).toBe(false); }); }); -it("accepts an attributed cross-sentence owner denial but rejects a false saved-change claim", () => { - const o = valid("routines.manage-other-owner"); - const refusal = "I couldn’t change Morgan’s routine. Paperclip returned: ‘Agents can only manage routines assigned to themselves.’ Morgan or a board-authorized user must change its cron schedule to every hour."; - expect(gradeIntegratorRoutines({ ...o, reply: refusal }).passed).toBe(true); - expect(gradeIntegratorRoutines({ ...o, reply: refusal + " I changed the routine to every hour." }).passed).toBe(false); - expect(gradeIntegratorRoutines({ ...o, reply: "I can manage Morgan's routine; owner restrictions do not apply. A human can inspect it." }).passed).toBe(false); +// Retained gha-42926219596 (full cohort on 9296c74e8d): the CEO routed the change to the owner by creating a +// task assigned to Morgan; Morgan's run on that task exceeded the old one-run bound. +describe("owner-routed routine change", () => { + function delegated() { + const o = valid("routines.manage-other-owner"); + o.links = ["/ACORN/issues/ACORN-2"]; o.tasks = [{ id: "delegated", identifier: "ACORN-2", assigneeAgentId: "morgan" }] as typeof o.tasks; + o.activity = [{ id: "created", action: "issue.created", entityType: "issue", entityId: "delegated", agentId: "ceo", runId: "run" }]; + o.runs.push({ id: "owner-run", agentId: "morgan", status: "succeeded", contextSnapshot: { issueId: "delegated" } }); + return o; + } + it("accepts a linked owner task, with or without the owner's own schedule change", () => { + expect(gradeIntegratorRoutines(delegated()).passed).toBe(true); + const owned = delegated(); owned.routines[0]!.triggers[0]!.cronExpression = "0 * * * *"; + owned.activity.push({ id: "w", action: "routine.trigger_updated", entityType: "routine", entityId: "routine", agentId: "morgan", runId: "owner-run" }); + expect(gradeIntegratorRoutines(owned).passed).toBe(true); + }); + it("rejects an unlinked owner task, an unbound or second Morgan run, and a change written outside the owner run", () => { + expect(gradeIntegratorRoutines({ ...delegated(), links: [] }).passed).toBe(false); + const unbound = delegated(); unbound.runs[1]!.contextSnapshot = { issueId: "elsewhere" }; expect(gradeIntegratorRoutines(unbound).passed).toBe(false); + const twice = delegated(); twice.runs.push({ id: "again", agentId: "morgan", status: "succeeded", contextSnapshot: { issueId: "delegated" } }); expect(gradeIntegratorRoutines(twice).passed).toBe(false); + for (const [cron, timezone] of [["* * * * *", "America/Chicago"], ["0 */2 * * *", "America/Chicago"], ["0 * * * *", "UTC"]]) { + const wrong = delegated(); Object.assign(wrong.routines[0]!.triggers[0]!, { cronExpression: cron, timezone }); + wrong.activity.push({ id: "w", action: "routine.trigger_updated", entityType: "routine", entityId: "routine", agentId: "morgan", runId: "owner-run" }); + expect(gradeIntegratorRoutines(wrong).passed).toBe(false); + } + const outside = delegated(); outside.routines[0]!.triggers[0]!.cronExpression = "0 * * * *"; + outside.activity.push({ id: "w", action: "routine.trigger_updated", entityType: "routine", entityId: "routine", agentId: "morgan", runId: "other-run" }); + expect(gradeIntegratorRoutines(outside).passed).toBe(false); + }); +}); + +it("recognizes every-hour cron forms and rejects other frequencies", () => { + for (const cron of ["0 * * * *", "15 */1 * * *", "0 0-23 * * *", "5 0-23/1 * * *", "0 0-11,12-23 * * *", "30 * 1-31 * 0-6"]) expect(runsHourly(cron)).toBe(true); + for (const cron of ["* * * * *", "0 */2 * * *", "0 9-17 * * *", "0 * * * 1-5", "*/30 * * * *", "0 *", "not cron"]) expect(runsHourly(cron)).toBe(false); }); diff --git a/tests/runner-e2e/chat-catalog-domains/integrator-routines.ts b/tests/runner-e2e/chat-catalog-domains/integrator-routines.ts index b3b7dfaba56..a749fb84c85 100644 --- a/tests/runner-e2e/chat-catalog-domains/integrator-routines.ts +++ b/tests/runner-e2e/chat-catalog-domains/integrator-routines.ts @@ -1,6 +1,8 @@ import type { RoutineDetail, RoutineListItem, RoutineRevision, RoutineRunSummary } from "../../../packages/shared/src/types/routine.js"; import type { ChatCatalogContext, ChatCatalogCase } from "../chat-catalog-contract.js"; -import { checks, project, observation, type InternalObservation } from "./internal-support.js"; +import { checks, hasLink, project, observation, type Entity, type InternalObservation } from "./internal-support.js"; +import { runIssueId } from "./run-roles.js"; +import { parseCron } from "../../../server/src/services/cron.js"; import { fixtureWorker } from "./internal-definition.js"; import { integratorDefinition, groundedStatement, inspectResult, observeInternal } from "./integrator-support.js"; interface RoutinesObservation extends InternalObservation { @@ -20,6 +22,30 @@ function routineObservation(value: unknown): RoutinesObservation | undefined { const o = value as RoutinesObservation; return observation(value) && Array.isArray(o.routines) && !!o.histories && !!o.routineRevisions && typeof o.browserTimezone === "string" ? o : undefined; } +type Activity = Entity & { runId?: string | null }; +/** Fires once in every hour of every day, judged by the product's own cron parser rather than one spelling: + * exactly one minute, all 24 hours, and unrestricted day of month, month and weekday. */ +export function runsHourly(cron: string) { + let parsed: ReturnType; + try { parsed = parseCron(cron); } catch { return false; } + return parsed.minutes.length === 1 && parsed.hours.length === 24 && parsed.daysOfMonth.length === 31 && parsed.months.length === 12 && parsed.daysOfWeek.length === 7; +} +function linksTo(o: InternalObservation, href: string, segment: string, ids: Array) { + try { const url = new URL(href, o.origin), parts = url.pathname.split("/").map(decodeURIComponent), index = parts.indexOf(segment); + return url.origin === new URL(o.origin).origin && index >= 0 && ids.filter(Boolean).includes(parts[index + 1]); } catch { return false; } +} +function routineWrite(event: Entity & { action?: string; entityType?: string; entityId?: string; details?: Record | null }, routineId?: string) { + return /^routine\.(?!run_|webhook_|document_)/.test(event.action ?? "") && (event.entityId === routineId || event.details?.routineId === routineId); +} +/** The owner path: tasks the CEO created and assigned to Morgan, and Morgan's runs. At most one such + * task and one Morgan run bound to it; any other Morgan run is extra work. */ +function ownerRoute(o: InternalObservation, worker: Entity) { + const delegated = o.tasks.filter(task => task.assigneeAgentId === worker?.id && o.activity.some(event => event.action === "issue.created" + && event.entityId === task.id && event.agentId === o.leadId && o.runs.some(run => run.id === (event as Activity).runId && run.agentId === o.leadId))); + const workerRuns = o.runs.filter(run => run.agentId === worker?.id); + const ownerRun = workerRuns.length === 1 && delegated.length === 1 && runIssueId(workerRuns[0]!) === delegated[0]!.id ? workerRuns[0] : undefined; + return { delegated, ownerRun, valid: delegated.length <= 1 && (workerRuns.length === 0 || !!ownerRun) }; +} export function gradeIntegratorRoutines(value: unknown) { const c = checks(); const o = routineObservation(value); c.add("public-routine-definition-and-history", !!o, "Requires actual routine detail, revision history, execution history and browser timezone."); @@ -37,15 +63,24 @@ export function gradeIntegratorRoutines(value: unknown) { && /(?:America\/Chicago|Chicago|Central (?:time|timezone))/i.test(o.reply) && /\b(?:task|routine|work)\b/i.test(o.reply) && !/\b(?:summary (?:is )?(?:complete|ready)|already summarized|all future summaries (?:are )?(?:complete|ready))\b/i.test(o.reply), "The response describes the real saved local schedule and resulting work without claiming future summaries already ran."); } else if (o.scenarioId === "routines.manage-other-owner") { - const before = o.state.routine as RoutineDetail; const current = o.routines.find(row => row.id === before?.id); - c.add("same-owned-definition-and-triggers", !!current && current.assigneeAgentId === (o.state.worker as { id: string } | undefined)?.id && o.routines.length === 1 - && current.latestRevisionId === before?.latestRevisionId && JSON.stringify(current.triggers) === JSON.stringify(before?.triggers) - && JSON.stringify(o.routineRevisions[current.id]) === JSON.stringify(o.state.originalRevisions), "Morgan's original owner, revision and schedule remain unchanged; no hidden duplicate is created."); - const refusal = groundedStatement(o.reply, /\b(?:Morgan|owner|ownership|self.assigned)\b/i, - /\b(?:cannot|can't|couldn[’']t|only|not (?:allowed|permitted|authorized)|boundary|restricted)\b/i, /\b(?:updated|changed|saved|rescheduled|reassigned)\b[^.!?\n]{0,45}\b(?:hourly|every hour|myself|to me)\b/i) - || /Agents can only manage routines assigned to themselves/i.test(o.reply) && /Morgan/i.test(o.reply) && /(?:cannot|can't|couldn[’']t|unable to)\s+(?:change|manage|update)/i.test(o.reply); - c.add("ownership-boundary-explained", refusal && /\b(?:human|Morgan|owner|operator)\b/i.test(o.reply) - && !/\b(?:I (?:have |already )?|successfully )(?:updated|changed|saved|rescheduled|reassigned)\b[^.!?\n]{0,65}\b(?:hourly|every hour|myself|to me)\b/i.test(o.reply), "The agent reports the actual owner-only management boundary and supported owner/human route, including an attributed product denial quoted in a separate sentence; it never claims the hourly change was saved."); + const before = o.state.routine as RoutineDetail; const current = o.routines.find(row => row.id === before?.id); const worker = o.state.worker as Entity; + const route = ownerRoute(o, worker); + const unchanged = !!current && current.latestRevisionId === before?.latestRevisionId && JSON.stringify(current.triggers) === JSON.stringify(before?.triggers) + && JSON.stringify(o.routineRevisions[current.id]) === JSON.stringify(o.state.originalRevisions); + // Agent routine writes: only the owner's own run on the delegated task may make them. + const agentWrites = o.activity.filter(event => routineWrite(event, before?.id) && !!event.agentId); + const ownerWrites = agentWrites.filter(event => event.agentId === worker.id && !!route.ownerRun && (event as Activity).runId === route.ownerRun.id); + // When the owner does change it, the saved result must be the requested one: one enabled hourly schedule + // in the original timezone (minute fixed, every hour). + const schedules = current?.triggers.filter(row => row.kind === "schedule") ?? []; + const hourly = schedules.length === 1 && schedules[0]!.enabled === true && runsHourly(schedules[0]!.cronExpression ?? "") + && schedules[0]!.timezone === before?.triggers.find(row => row.kind === "schedule")?.timezone; + c.add("same-owned-definition-and-triggers", !!current && current.assigneeAgentId === worker?.id && o.routines.length === 1 + && agentWrites.length === ownerWrites.length && (unchanged || ownerWrites.length > 0 && hourly), + "Morgan remains the owner and no hidden duplicate exists. The definition and schedule are unchanged, or Morgan's own write from the run on the routed task saved one enabled hourly schedule in the original timezone."); + c.add("ownership-boundary-explained", route.valid && (route.delegated.length === 1 ? hasLink(o, "issues", route.delegated[0]!) + : o.links.some(href => linksTo(o, href, "routines", [before?.id]) || linksTo(o, href, "agents", [worker?.id, worker?.urlKey]))), + "The change is routed structurally: one task assigned to owner Morgan, created by the CEO and linked in the reply, with at most one Morgan run bound to it; or a reply link to the routine or Morgan's page where an authorized person acts. The reply's wording is left to a human reader."); c.add("no-ceo-management-mutation", !o.activity.some(event => event.agentId === o.leadId && /^routine\.(?:created|updated|trigger_|revision_created)/.test(event.action ?? "")), "No responding-agent routine mutation bypasses the self-assigned management rule."); } else c.add("owned-routine-oracle", false, "No independent oracle exists for this routine scenario."); return c.result(); @@ -63,5 +98,6 @@ export const integratorRoutinesCases: readonly ChatCatalogCase[] = [ const created = await ctx.input.api.post(`${root(ctx)}/routines`, { title: "Morgan's launch summary", description: "Summarize Launch without changing project tasks.", projectId: p.id, assigneeAgentId: worker.id }); await ctx.input.api.post(`/api/routines/${created.id}/triggers`, { kind: "schedule", enabled: true, cronExpression: "0 9 * * 1-5", timezone: "America/Chicago" }); return { project: p, worker, routine: await ctx.input.api.get(`/api/routines/${created.id}`), originalRevisions: await ctx.input.api.get(`/api/routines/${created.id}/revisions`) }; - }), + }, { oracleVersion: "paperclip.chat-catalog.integrator.manage-other-owner.v5", expectedRunCount: 2, minimumRunCount: 1, attemptTimeoutMs: 480_000, + sourceFiles: ["chat-catalog-domains/integrator-support.ts", "chat-catalog-domains/internal-support.ts", "chat-catalog-domains/integrator-routines.ts", "chat-catalog-domains/run-roles.ts", "../../server/src/services/cron.ts", "chat-scenarios/routines.yaml"] }), ]; diff --git a/tests/runner-e2e/chat-catalog-domains/integrator-skill-authoring-v2.test.ts b/tests/runner-e2e/chat-catalog-domains/integrator-skill-authoring-v2.test.ts index e7c9b0c58ad..eab5035472b 100644 --- a/tests/runner-e2e/chat-catalog-domains/integrator-skill-authoring-v2.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/integrator-skill-authoring-v2.test.ts @@ -2,7 +2,7 @@ import { createRequire } from "node:module"; import { afterEach, expect, it, vi } from "vitest"; import type { ChatCatalogContext } from "../chat-catalog-contract.js"; import type { InternalObservation } from "./internal-support.js"; -vi.mock("@playwright/test",()=>({expect:Object.assign((node:any)=>({toBeVisible:async()=>{if(!node.visible)throw Error("Missing real UI item");},toBeEditable:async()=>{if(!node.editable)throw Error("Noneditable real UI");},toHaveURL:async(predicate:(url:URL)=>boolean)=>{if(!predicate(new URL(node.url())))throw Error("Wrong actual Studio identity");}}),{poll:(read:()=>Promise)=>({toBe:async(expected:boolean)=>{for(let i=0;i<3;i++)if(await read()===expected)return;throw Error("UI content did not hydrate to the saved checklist");}})})})); +vi.mock("@playwright/test",()=>({expect:Object.assign((node:any)=>({toBeVisible:async()=>{if(!node.visible)throw Error("Missing real UI item");},toBeEditable:async()=>{if(!node.editable)throw Error("Noneditable real UI");},toHaveURL:async(predicate:(url:URL)=>boolean)=>{if(!predicate(new URL(node.url())))throw Error("Wrong actual Studio identity");},toPass:async()=>{let error:unknown;for(let i=0;i<3;i++){try{await node();return;}catch(caught){error=caught;}}throw error;}}),{poll:(read:()=>Promise)=>({toBe:async(expected:boolean)=>{for(let i=0;i<3;i++)if(await read()===expected)return;throw Error("UI content did not hydrate to the saved checklist");}})})})); const observed=vi.hoisted(()=>({base:undefined as unknown})); vi.mock("./integrator-support.js",async original=>({...await original(),observeInternal:vi.fn(async(_ctx:unknown,state:unknown)=>({...observed.base as object,state}))})); import { gradeIntegratorSkills, authoredChecklistTextBlocks, preservesVisibleWebsiteChecklist, inspectAuthoredSkill, integratorSkillsCases, websiteChecklist } from "./integrator-skills.js"; @@ -13,7 +13,7 @@ function fixture(){ const skill={id:"skill",companyId:"company",name:"Website review checklist",slug:"website-review-checklist",editable:true,currentVersionId:"revision",markdown,usedByAgents:[]}; const state:Record={},o={scenarioId:"skills.author-skill",origin:"https://fixture.test",companyId:"company",leadId:"ceo",state,skills:[skill],versions:{skill:[version]},policy:{},editDecision:{allowed:true},tasks:[],projects:[],goals:[],comments:[],documents:[],revisions:[],humanQueries:["Turn our website review checklist into a reusable skill."],runs:[{id:"native",status:"succeeded",agentId:"ceo",companyId:"company"}],activity:[{action:"company.skill_created",entityId:"skill",agentId:"ceo"}],links:["/skills/studio/skill"],renderedLinkEvidence:[{threadTestId:"task-chat-thread",href:"/skills/studio/skill",source:"reply",conversationId:"conversation",anchorCommentId:"query",commentId:"reply"}],reply:"Created the reusable company skill, saved in the library and not assigned to any agent."} as unknown as InternalObservation; observed.base=o; - const ui={card:true,library:true,studio:true,editable:true,body:markdown,changedAfterReload:false,wrongRoute:false,foreignRoute:false,directStudio:false,delayedHydration:false,inEdit:false,filesSelected:false};const events:string[]=[]; + const ui={card:true,library:true,studio:true,editable:true,body:markdown,changedAfterReload:false,wrongRoute:false,foreignRoute:false,directStudio:false,delayedHydration:false,inEdit:false,filesSelected:false,ignoredCardClicks:0};const events:string[]=[]; const editor={get visible(){return ui.studio && (ui.inEdit || ui.directStudio);},get editable(){return ui.editable;},locator:()=>({evaluateAll:async()=>ui.delayedHydration&&editorReads++===0?[]:(ui.changedAfterReload&&reloads?"Lost checklist":ui.body).split("\n")})}; const page={url:()=>current,getByRole:(role:string,options?:{name?:string})=>{ if(role==="textbox")return editor; @@ -22,7 +22,7 @@ function fixture(){ if(role==="tab" && options?.name==="Files")return{click:async()=>{ui.filesSelected=true;events.push("Files");}}; if(role==="button" && options?.name==="Edit")return{click:async()=>{if(!ui.editable||!ui.filesSelected)throw Error("No Edit control outside Files");ui.inEdit=true;events.push("Edit");}}; if(role==="link")return{first:()=>({click:async()=>{events.push(options!.name!);current=options?.name==="Skills"?"https://fixture.test/ACORN/skills":"https://fixture.test/ACORN/skills/studio";}})}; - return{filter:()=>({first:()=>({get visible(){return ui.library;},click:async()=>{events.push("open-skill");current=ui.foreignRoute?"https://fixture.test/FOREIGN/skills/website-review-checklist":ui.wrongRoute?"https://fixture.test/ACORN/skills/other":ui.directStudio?"https://fixture.test/ACORN/skills/studio/skill":"https://fixture.test/ACORN/skills/website-review-checklist";}})})}; + return{filter:()=>({first:()=>({get visible(){return ui.library;},click:async()=>{events.push("open-skill");if(ui.ignoredCardClicks>0){ui.ignoredCardClicks--;return;}current=ui.foreignRoute?"https://fixture.test/FOREIGN/skills/website-review-checklist":ui.wrongRoute?"https://fixture.test/ACORN/skills/other":ui.directStudio?"https://fixture.test/ACORN/skills/studio/skill":"https://fixture.test/ACORN/skills/website-review-checklist";}})})}; },getByText:()=>({first:()=>({get visible(){return ui.studio;}})}),locator:()=>({}),getByTestId:()=>({get visible(){return current===source;},filter:()=>({locator:(selector:string)=>({first:()=>({click:async()=>{if(!selector.includes('"/skills/studio/skill"'))throw Error("Not the rendered skill link");events.push("reply-link");current="https://fixture.test/ACORN/skills/studio/skill";}})})})}),reload:async()=>{reloads++;ui.inEdit=false;ui.filesSelected=false;events.push("reload");},goto:async(url:string)=>{current=url;events.push("return-chat");}}; const after=structuredClone(skill),get=vi.fn(async(route:string)=>{ if(route.endsWith("/skills"))return[{id:"skill"}]; @@ -64,7 +64,7 @@ it("rejects invented inspection receipts and keeps other skill cases on their or f.state.authoredSkillInspection={companyId:"company",skillId:"other",versionId:"revision",libraryVisible:true,studioVisible:true,editable:true,checklistVisible:true,reloaded:true,readbackMatched:true}; expect(gradeIntegratorSkills(f.o).passed).toBe(false); expect(integratorSkillsCases.find(x=>x.scenarioId==="skills.explicit-restriction")!.oracleVersion).toBe("paperclip.chat-catalog.skill-restriction.structural.v2"); - expect(integratorSkillsCases.find(x=>x.scenarioId==="skills.author-skill")!.oracleVersion).toBe("paperclip.chat-catalog.skill-authoring.v7"); + expect(integratorSkillsCases.find(x=>x.scenarioId==="skills.author-skill")!.oracleVersion).toBe("paperclip.chat-catalog.skill-authoring.v9"); }); it("opens the skill from its Skill created card when the reply has no skill link",async()=>{ const f=fixture();Object.assign(f.o,{links:[],renderedLinkEvidence:[]}); @@ -126,3 +126,11 @@ it.each(["wrong section","missing check","heading only","negated directive","neg if(fault==="negated keyboard")markup=markup.replace("Do not use a mouse or touch input.", "Do not use the keyboard."); expect(preservesVisibleWebsiteChecklist(renderedSections(markup))).toBe(false); }); + +it("clicks the library card again when the first click leaves the list open (gha-42937394973), still requiring this skill's page",async()=>{ + const f=fixture(),d=integratorSkillsCases.find(x=>x.scenarioId==="skills.author-skill")!; + f.ui.ignoredCardClicks=1; await d.act!(f.ctx,f.state); + expect(f.events.filter(e=>e==="open-skill")).toHaveLength(2); + expect(f.state.authoredSkillInspection).toMatchObject({skillId:"skill",readbackMatched:true}); + const wrong=fixture(); wrong.ui.ignoredCardClicks=1; wrong.ui.wrongRoute=true; await expect(d.act!(wrong.ctx,wrong.state)).rejects.toThrow(); +}); diff --git a/tests/runner-e2e/chat-catalog-domains/integrator-skills.ts b/tests/runner-e2e/chat-catalog-domains/integrator-skills.ts index ff0cf88e004..025750ed308 100644 --- a/tests/runner-e2e/chat-catalog-domains/integrator-skills.ts +++ b/tests/runner-e2e/chat-catalog-domains/integrator-skills.ts @@ -183,7 +183,14 @@ export async function inspectAuthoredSkill(ctx: ChatCatalogContext, state: Recor // From the skill, the Skills section's own My Skills link shows it in the person's library. await ctx.input.page.getByRole("link", { name: "My Skills", exact: true }).first().click({ timeout: remaining() }); const card = ctx.input.page.getByRole("button").filter({ has: ctx.input.page.getByText(skill.name, { exact: true }) }).first(); - await expect(card).toBeVisible({ timeout: remaining() }); await card.click({ timeout: remaining() }); + await expect(card).toBeVisible({ timeout: remaining() }); + // Retained gha-42937394973: a click on the freshly rendered library card sometimes leaves the list open + // (the card highlights, no navigation). A person clicks again; the opened page must still be this skill. + const opened = (url: URL) => url.origin === new URL(source).origin && (url.pathname === studioRoute || url.pathname === detailRoute); + await expect(async () => { + if (!opened(new URL(ctx.input.page.url()))) await card.click({ timeout: 5_000 }); + await expect(ctx.input.page).toHaveURL(opened, { timeout: 5_000 }); + }).toPass({ timeout: remaining() }); const openSavedEditor = async () => { await expect(ctx.input.page).toHaveURL(url => url.origin === new URL(source).origin && (url.pathname === studioRoute || url.pathname === detailRoute), { timeout: remaining() }); @@ -216,9 +223,17 @@ const define = (id: string, setup: ChatCatalogCase["setup"]): ChatCatalogCase => const base = integratorDefinition("skills", id, setup, observeSkills, gradeIntegratorSkills, verifySkill); base.sourceFiles = [...base.sourceFiles, "chat-catalog-domains/integrator-skill-versions.ts"]; if (id === "skills.explicit-restriction") return { ...base, oracleVersion: "paperclip.chat-catalog.skill-restriction.structural.v2" }; - return id === "skills.author-skill" ? { ...base, authentication: "human-session", oracleVersion: "paperclip.chat-catalog.skill-authoring.v7", sourceFiles: [...base.sourceFiles, "chat-catalog-domains/identity-support.ts", "../../ui/src/components/MarkdownEditor.tsx", "../../ui/src/pages/SkillStudio.tsx", "../../ui/src/pages/CompanySkills.tsx", "../../ui/src/lib/company-skill-routes.ts"], queryAttachments: factualContextQueryAttachment("skill-context.md"), + return id === "skills.author-skill" ? { ...base, authentication: "human-session", oracleVersion: "paperclip.chat-catalog.skill-authoring.v9", sourceFiles: [...base.sourceFiles, "chat-catalog-domains/identity-support.ts", "../../ui/src/components/MarkdownEditor.tsx", "../../ui/src/pages/SkillStudio.tsx", "../../ui/src/pages/CompanySkills.tsx", "../../ui/src/lib/company-skill-routes.ts"], queryAttachments: factualContextQueryAttachment("skill-context.md"), async act(ctx, state) { remainingIdentityObservationBudget(ctx); await waitForReply(ctx, ctx.observationDeadlineAt); await inspectAuthoredSkill(ctx, state, await observeSkills(ctx, state)); }, - async verifyResult(ctx, state, value) { const o = observation(value); if (!o) throw new Error("Missing authored skill inspection evidence"); await inspectAuthoredSkill(ctx, state, o); }, + async verifyResult(ctx, state, value) { + const o = skillsObservation(value); if (!o) throw new Error("Missing authored skill inspection evidence"); + // act already walked the person's full browser path (chat link, My Skills, editor, reload). Repeating the + // clicks only re-tests navigation; confirm the inspected version is still the saved one instead. + const inspected = state.authoredSkillInspection as AuthoredSkillInspection | undefined; + const skill = inspected && o.skills.find(row => row.id === inspected.skillId); + if (inspected && skill && skill.companyId === inspected.companyId && skill.currentVersionId === inspected.versionId) return; + await inspectAuthoredSkill(ctx, state, o); + }, } : base; }; export const integratorSkillsCases: readonly ChatCatalogCase[] = [ diff --git a/tests/runner-e2e/chat-catalog-domains/internal-design-search.test.ts b/tests/runner-e2e/chat-catalog-domains/internal-design-search.test.ts index ac874d56d2b..d313f2afaad 100644 --- a/tests/runner-e2e/chat-catalog-domains/internal-design-search.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/internal-design-search.test.ts @@ -12,43 +12,20 @@ function valid() { } describe("approved design search calibration", () => { it("accepts the saved human-approved revision while distinguishing newer unapproved history", () => expect(gradeDesignSearch(valid()).passed).toBe(true)); - it("rejects promoting the latest unapproved draft", () => { const o = valid(); o.reply = "The approved design is revision 1. The latest draft, violet navigation v2, is the latest approved design."; expect(gradeDesignSearch(o).passed).toBe(false); }); + it("rejects returning the earlier design first", () => { const o = valid(); o.links = ["/RUN/issues/earlier", "/RUN/issues/website"]; expect(gradeDesignSearch(o).passed).toBe(false); }); it("rejects a newer competing approval", () => { const o = valid(); o.olderApprovalComments[0]!.createdAt = "2026-10-26T13:00:00Z"; expect(gradeDesignSearch(o).passed).toBe(false); }); - it("rejects reversed approval facts", () => { const o = valid(); o.reply = "Revision 1 was never approved. The newer draft is approved."; expect(gradeDesignSearch(o).passed).toBe(false); }); it("rejects forged approval or changed approved bytes", () => { const o = valid(); o.approvalComments[0]!.authorUserId = "ceo"; expect(gradeDesignSearch(o).passed).toBe(false); const bytes = valid(); bytes.approvedRevision.body = "Other design"; expect(gradeDesignSearch(bytes).passed).toBe(false); }); it("rejects private search snippets and leaked response content", () => { const o = valid(); o.agentSearchResults.push({ id: "hidden" }); expect(gradeDesignSearch(o).passed).toBe(false); const leaked = valid(); leaked.reply += " NIGHTJAR"; expect(gradeDesignSearch(leaked).passed).toBe(false); }); it("rejects changing current design while searching", () => { const o = valid(); o.documents[0]!.body = "Approved by CEO"; expect(gradeDesignSearch(o).passed).toBe(false); }); it("requires exact authorized result link and healthy private access proof", () => { const o = valid(); o.links = ["https://foreign.test/RUN/issues/website"]; expect(gradeDesignSearch(o).passed).toBe(false); const access = valid(); access.privateReadStatus = 200; expect(gradeDesignSearch(access).passed).toBe(false); }); - it("accepts the actual explicit revision ordering without requiring an incidental recency adjective", () => { - const o = valid(); o.reply = "The latest approved launch website design is **RUN-2 revision 1** (`r1`): **amber navigation, accessible signup, and research-team testimonials** — explicitly approved in [/RUN/issues/RUN-2](/RUN/issues/RUN-2).\n\nRUN-2 revision 2 (violet navigation, animated pricing) is an unapproved draft. RUN-1 was the earlier approved design: slate navigation and a waitlist-only form."; + it("accepts the retained full-cohort reply that links the approved task first and the earlier design after it", () => { + // Retained gha-42926... find-design reply: one clause names both COM-2's draft and COM-1, which the old clause grader rejected. + const o = valid(); o.links = ["/RUN/issues/RUN-2", "/RUN/issues/RUN-1"]; + o.reply = "Latest approved design: **v1 on [RUN-2](/RUN/issues/RUN-2)** — amber navigation, accessible signup, and research-team testimonials. You recorded the approval on revision 1 at 00:01:30 UTC (\"This is the signed-off design\").\n\nNote: RUN-2's current revision 2 is labeled an unapproved draft (violet navigation, animated pricing), and [RUN-1](/RUN/issues/RUN-1) is the earlier slate/waitlist design approved at 00:01:29 UTC."; expect(gradeDesignSearch(o).passed).toBe(true); }); - it.each([ - "Version 1 with amber navigation is signed off. Version 2 remains pending review.", - "Revision 1 is approved, whereas revision 2 remains an unapproved draft.", - "Revision 1 is approved, but revision 2 is not yet approved.", - "Revision 1 is approved, while revision 2 is an unapproved draft.", - "The approved design is v1 with amber navigation. V2 is not yet approved.", - "Revision 1 was approved. Revision 2 is not officially approved and is an unapproved draft.", - "Revision 1 was approved. Revision 2 has never been approved and is an unapproved draft.", - "Revision 1 is approved. RUN-2 revision 2 has not been approved and is an unapproved draft.", - ])("accepts truthful current-version disclosure: %s", reply => { const o = valid(); o.reply = reply; expect(gradeDesignSearch(o).passed).toBe(true); }); - it.each([ - "Revision 1 is approved. RUN-3 revision 2 is an unapproved draft.", - "Revision 1 is approved. The newer revision 3 is an unapproved draft.", - "Revision 1 is approved. Revision 2 is not an unapproved draft.", - "Revision 1 is approved. Revision 2 is approved.", - "Revision 1 is approved. Revision 1 is an unapproved draft.", - "Revision 1 is approved. The newer draft is no longer unapproved.", - "Revision 1 is approved. Revision 2 is an unapproved draft. Revision 2 is approved.", - "Revision 1 is approved. Revision 2 is an unapproved draft. Revision 2 approved.", - "Revision 1 is approved. Revision 2 is an unapproved draft. Also approved: revision 2.", - "Revision 1 is approved. Revision 2 is an unapproved draft. We did not choose a filename, but revision 2 is approved.", - "Revision 1 is approved. Revision 2 is an unapproved draft. V2 has been signed off.", - ])("rejects unrelated, wrong-version, negated or contradictory disclosure: %s", reply => { const o = valid(); o.reply = reply; expect(gradeDesignSearch(o).passed).toBe(false); }); - it("retains exact linked target and historical approval checks with explicit revision ordering", () => { - const o = valid(); o.reply = "Revision 1 is approved. Revision 2 is an unapproved draft."; o.links = ["/RUN/issues/other"]; expect(gradeDesignSearch(o).passed).toBe(false); - const missing = valid(); missing.reply = o.reply; missing.approvalComments = []; expect(gradeDesignSearch(missing).passed).toBe(false); + it("does not grade the prose: a reworded reply with the same returned record passes", () => { + const o = valid(); o.reply = "Here it is: the signed-off launch website design. A later edit on the same task has not been signed off."; expect(gradeDesignSearch(o).passed).toBe(true); }); - + it("rejects a reply without any task link", () => { const o = valid(); o.links = []; expect(gradeDesignSearch(o).passed).toBe(false); }); }); diff --git a/tests/runner-e2e/chat-catalog-domains/internal-design-search.ts b/tests/runner-e2e/chat-catalog-domains/internal-design-search.ts index e61bf6743cb..996083973ea 100644 --- a/tests/runner-e2e/chat-catalog-domains/internal-design-search.ts +++ b/tests/runner-e2e/chat-catalog-domains/internal-design-search.ts @@ -7,26 +7,11 @@ import { checks, entity, hasLink, observation, observeInternal, project, putDocu interface DesignObservation extends InternalObservation { approvedRevision?: Entity; approvalComments: Entity[]; olderApprovalComments: Entity[]; privateReadStatus: number; agentSearchStatus: number; agentSearchResults: unknown[]; } -function designClauses(reply: string) { return reply.split(/[.\n;]|\b(?:whereas|while|but)\b/i); } -function contradictsDraftApproval(reply: string, target: Entity) { - return designClauses(reply).some(part => { - const taskReferences = part.match(/\b[A-Z][A-Z0-9]*-\d+\b/g) ?? []; - if (taskReferences.some(id => id !== target.identifier)) return false; - if (!/\b(?:revision\s*2|version\s*2|v2|violet\s+navigation)\b/i.test(part)) return false; - return [...part.matchAll(/\b(?:approved|signed[ -]off)\b/gi)].some(match => - !/(?:\b(?:not|never)|\bno longer|\b(?:hasn't|haven't|wasn't|weren't|isn't|aren't))(?:\s+(?:yet|been|ever|officially|currently|formally))*\s*$/i.test(part.slice(0, match.index))); - }); -} -function describesUnapprovedCurrentDraft(reply: string, target: Entity) { - return designClauses(reply).some(part => { - const taskReferences = part.match(/\b[A-Z][A-Z0-9]*-\d+\b/g) ?? []; - if (taskReferences.length && (!target.identifier || taskReferences.some(id => id !== target.identifier))) return false; - const versions = [...part.matchAll(/\b(?:revision|version)\s*(\d+)\b|\bv(\d+)\b/gi)].map(match => Number(match[1] ?? match[2])); - if (versions.some(version => version !== 2)) return false; - return /\b(?:newer|later|latest|current|revision\s*2|version\s*2|v2|violet\s+navigation)\b/i.test(part) - && /\b(?:unapproved|not approved|not yet approved|pending review)\b/i.test(part) - && !/\b(?:not|never|no longer|isn't)\s+(?:an?\s+)?(?:unapproved|pending review)\b/i.test(part); - }); +/** The record the reply returns is its first task link: it must be the task holding the human-approved + * design. Other tasks (such as the earlier design) may be linked after it as context. Whether the prose + * also describes the newer draft correctly is read by a person; saved state proves no draft was approved. */ +export function returnedTaskLink(o: InternalObservation): string | undefined { + return o.links.find(href => { try { const url = new URL(href, o.origin); return url.origin === new URL(o.origin).origin && url.pathname.split("/").includes("issues"); } catch { return false; } }); } export function gradeDesignSearch(value: unknown) { const c = checks(); const o = observation(value) as DesignObservation | undefined; @@ -40,13 +25,9 @@ export function gradeDesignSearch(value: unknown) { && Number.isFinite(Date.parse(row.createdAt ?? "")) && Date.parse(row.createdAt!) <= Date.parse((o.state.approvalComment as Entity).createdAt ?? "")) && o.approvalComments.some(row => row.id === (o.state.approvalComment as Entity | undefined)?.id && row.authorUserId === o.state.ownerId && row.body === (o.state.approvalComment as Entity).body), "The exact historical revision and real human approval comment remain saved rather than inferring approval from latest edit time."); - c.add("approved-design-distinguished-from-newer-draft", !!target && hasLink(o, "issues", target) - && designClauses(o.reply).some(sentence => /\b(?:approved|signed[ -]off)\b/i.test(sentence) - && /\b(?:revision\s*1|version\s*1|v1|amber\s+navigation)/i.test(sentence) - && !/\b(?:not|never|no longer)\s+(?:yet\s+)?(?:approved|signed[ -]off)\b|\bunapproved\b/i.test(sentence)) - && describesUnapprovedCurrentDraft(o.reply, target) - && !contradictsDraftApproval(o.reply, target), - "The answer links the actual approved design and explains that the later revision is still a draft."); + const returned = returnedTaskLink(o); + c.add("approved-design-distinguished-from-newer-draft", !!target && !!returned && hasLink({ ...o, links: [returned] }, "issues", target), + "The reply returns (links first) the task whose saved revision carries the human approval. The older design may follow as context; the draft's description is read by a person."); c.add("read-only-design-search", !!originals && originals.every(row => sameTask(row, o.tasks.find(now => now.id === row.id))) && current?.latestRevisionId === o.state.draftRevisionId && current?.body === o.state.draftBody && !o.activity.some(row => row.agentId === o.leadId && originals.some(original => original.id === row.entityId) && /issue\.(?:document_|updated|comment_added)/.test(row.action ?? "")), @@ -82,7 +63,7 @@ function findDesign(): ChatCatalogCase { return { project: p, task: t, ownerId, olderTask, olderApprovalComment, originalTasks: [olderTask, t, marketing, hidden], approvedRevision: { id: approvedRevision.latestRevisionId, body: approvedRevision.body }, approvalComment, draftRevisionId: draft.latestRevisionId, draftBody, privateTask: hidden, privateMarker }; }, gradeDesignSearch); - return { ...base, authentication: "human-session", sourceFiles: [...base.sourceFiles, "chat-catalog-domains/internal-design-search.ts", "chat-catalog-domains/internal-privacy.ts", "chat-catalog-domains/identity-auth.ts"], + return { ...base, authentication: "human-session", oracleVersion: "paperclip.chat-catalog.internal.find-design.structural.v1", sourceFiles: [...base.sourceFiles, "chat-catalog-domains/internal-design-search.ts", "chat-catalog-domains/internal-privacy.ts", "chat-catalog-domains/identity-auth.ts"], async observe(ctx, state): Promise { if (!key) throw new Error("Design probe credential was not created during setup"); const read = async (path: string) => { diff --git a/tests/runner-e2e/chat-catalog-domains/internal.test.ts b/tests/runner-e2e/chat-catalog-domains/internal.test.ts index 2da35ab1f9b..a02a0521ec8 100644 --- a/tests/runner-e2e/chat-catalog-domains/internal.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/internal.test.ts @@ -362,7 +362,8 @@ const corrupt: Record void> = { "documents-artifacts.resolve-feedback": o => { o.annotations![1]!.status = "resolved"; }, "documents-artifacts.restore-document": o => { o.documents[0]!.body = "third"; }, "inbox-search.show-decisions": o => { o.reply = "You can approve every item."; }, - "inbox-search.find-design": o => { o.reply = "Revision 2 is the latest approved design."; }, + // The returned record (first task link) is another task, not the one holding the approved revision. + "inbox-search.find-design": o => { o.links = ["/RUN/issues/earlier-design", ...o.links]; }, "inbox-search.notification-audience": o => { Object.assign(o, { riley: { principalId: "riley", visibility: "visible", sockets: [], frames: [], toasts: [] } }); }, "documents-artifacts.find-artifact": o => { o.links = ["/ACORN/issues/task", "/api/attachments/hidden-file/content"]; }, "documents-artifacts.produce-download": o => { o.links = ["/ACORN/issues/task", "/tmp/website.html"]; }, diff --git a/tests/runner-e2e/chat-catalog-domains/run-roles.ts b/tests/runner-e2e/chat-catalog-domains/run-roles.ts new file mode 100644 index 00000000000..01a3864b010 --- /dev/null +++ b/tests/runner-e2e/chat-catalog-domains/run-roles.ts @@ -0,0 +1,44 @@ +/** + * Run accounting by role instead of raw count. A case admits a run above its + * minimum only when the run is a product-caused continuation of declared work: + * the assignee of a task woken by a comment that a named run saved on that task, + * or the CEO's completion follow-up after a chat-created task finished. Anything + * else stays extra work and must still fail the case. + */ +export interface RoleRun { + id: string; agentId?: string | null; status?: string; issueId?: string | null; nativeIssueId?: string | null; + contextSnapshot?: Record | null; +} +export interface RoleComment { id: string; issueId?: string | null; companyId?: string | null; authorAgentId?: string | null; createdByRunId?: string | null } + +export function runIssueId(run: RoleRun): string | undefined { + const value = run.nativeIssueId ?? run.contextSnapshot?.issueId ?? run.issueId; + return typeof value === "string" && value ? value : undefined; +} +/** The run's agent was woken on `issueId` by the exact comment it names, and a + * run in `causeRunIds` saved that comment on the same task. */ +export function commentWokenRun(run: RoleRun, input: { agentId: string; issueId: string; comments: RoleComment[]; causeRunIds: readonly string[] }): boolean { + const commentId = run.contextSnapshot?.commentId ?? run.contextSnapshot?.wakeCommentId; + if (run.agentId !== input.agentId || runIssueId(run) !== input.issueId || typeof commentId !== "string") return false; + return input.comments.some(row => row.id === commentId && row.issueId === input.issueId && !!row.createdByRunId && input.causeRunIds.includes(row.createdByRunId)); +} +/** Comment-woken continuations of `agentId` on `issueId`, at most one per causing run. Undefined when any + * causing run woke the agent more than once (duplicate or runaway work). */ +export function commentWokenContinuations(runs: RoleRun[], input: Parameters[1]): RoleRun[] | undefined { + const admitted = runs.filter(run => commentWokenRun(run, input)); + const byCause = new Map(); + for (const run of admitted) { + const commentId = String(run.contextSnapshot?.commentId ?? run.contextSnapshot?.wakeCommentId); + const cause = input.comments.find(row => row.id === commentId)!.createdByRunId!; + byCause.set(cause, (byCause.get(cause) ?? 0) + 1); + } + return [...byCause.values()].every(count => count === 1) ? admitted : undefined; +} +/** The product's automatic follow-up on the source chat after its delegated task completed. */ +export function chatCompletionFollowUp(run: RoleRun, input: { leadId: string; sourceId: string; taskId: string }): boolean { + const snapshot = run.contextSnapshot ?? {}; + const wake = (snapshot.paperclipWake ?? {}) as Record; + const updates = Array.isArray(snapshot.chatCompletionUpdates) ? snapshot.chatCompletionUpdates : wake.chatCompletionUpdates; + return run.agentId === input.leadId && runIssueId(run) === input.sourceId && snapshot.wakeReason === "chat_task_completed" + && Array.isArray(updates) && updates.length > 0 && updates.every(row => (row as { id?: string } | null)?.id === input.taskId); +} diff --git a/tests/runner-e2e/chat-catalog-domains/runtime-conference.ts b/tests/runner-e2e/chat-catalog-domains/runtime-conference.ts index 54ac7648125..427fe0cf3be 100644 --- a/tests/runner-e2e/chat-catalog-domains/runtime-conference.ts +++ b/tests/runner-e2e/chat-catalog-domains/runtime-conference.ts @@ -2,6 +2,7 @@ import { chatCatalogOriginalPhaseDeadline } from "../chat-catalog-contract.js"; import { expect } from "@playwright/test"; import { checks } from "./internal-support.js"; import { waitForReply } from "./identity-support.js"; +import { waitForRenderedReply } from "./internal-comment-reference.js"; import { runtimeDefinition, runtimeObservation, observeRuntime } from "./runtime-support.js"; /** * The reply must send the person to the real Conference Room: the scripted human clicks the @@ -28,13 +29,18 @@ export const runtimeConferenceCases = [runtimeDefinition("agent-chat.conference- if (health.deploymentMode !== "local_trusted") throw new Error("Conference Room scenario requires a genuinely local-trusted target"); await ctx.input.api.patch("/api/instance/settings/experimental", { enableConferenceRoomChat: true }); const settings = await ctx.input.api.get<{ enableConferenceRoomChat: boolean; enableAgentChat: boolean }>("/api/instance/settings/experimental"); + // The open page cached the experimental settings before this fixture enabled Conference Room; a person + // arriving after the instance enabled it loads the current settings, so reload before the query is sent. + await ctx.input.page.reload({ waitUntil: "domcontentloaded" }); return { deploymentMode: health.deploymentMode, conferenceEnabled: settings.enableConferenceRoomChat, agentChatEnabled: settings.enableAgentChat, companyPrefix: ctx.input.fixtures.company.issuePrefix }; }, gradeConference, { - oracleVersion: "paperclip.chat-catalog.runtime-conference.v3", - sourceFiles: ["chat-catalog-domains/runtime-conference.ts", "chat-catalog-domains/runtime-support.ts", "chat-scenarios/agent-chat.yaml"], + oracleVersion: "paperclip.chat-catalog.runtime-conference.v5", + sourceFiles: ["chat-catalog-domains/runtime-conference.ts", "chat-catalog-domains/runtime-support.ts", "chat-catalog-domains/internal-comment-reference.ts", "chat-scenarios/agent-chat.yaml"], async act(ctx, state) { await waitForReply(ctx, chatCatalogOriginalPhaseDeadline(ctx)); state.runsBeforeOpen = (await ctx.allRuns()).length; state.standingIssueBefore = ctx.issue()?.id; + // gha-42939717023: the saved reply linked /COM/board-chat, but the anchors were read before it rendered. + await waitForRenderedReply(ctx, { leadId: ctx.input.fixtures.agent.id, runs: await ctx.allRuns() }); const o = await observeRuntime(ctx, state); // Find the link as rendered in the thread: the UI may rewrite a reply's href. const anchors = ctx.input.page.locator('[id^="comment-"] a[href]'); diff --git a/tests/runner-e2e/chat-catalog-domains/runtime-dependency.ts b/tests/runner-e2e/chat-catalog-domains/runtime-dependency.ts index 5ef8626978c..05f1d426daa 100644 --- a/tests/runner-e2e/chat-catalog-domains/runtime-dependency.ts +++ b/tests/runner-e2e/chat-catalog-domains/runtime-dependency.ts @@ -29,7 +29,9 @@ export function readTaskState(events: readonly Record[], task: } async function chooseStatus(page: Page, status: "Todo" | "Done") { await page.getByRole("button", { name: /^Change status \(current:/ }).first().click(); - await page.getByRole("button", { name: status, exact: true }).click(); + // Each option's accessible name also carries its status icon's label, so match the visible option text. + // (gha-42937394973: the exact-name locator never resolved while the menu showed "Todo".) + await page.getByRole("button").filter({ visible: true, hasText: new RegExp(`^\\s*${status}\\s*$`) }).first().click(); } export function gradeDesignDependency(value: unknown) { const c = checks(), o = runtimeObservation(value); @@ -61,7 +63,7 @@ export const runtimeDependencyCases = [runtimeDefinition("task-coordination.bloc description: `Implement the approved Design as a small website plan. Once eligible, read the actual Design task and save a task document with the exact reference ${marker}, accessible labels and a clear primary action, then finish normally. Do not deploy, create other tasks or invent approval.` }); return { worker, task, design, marker }; }, gradeDesignDependency, { - expectedHumanMessageCount: 2, expectedRunCount: 3, attemptTimeoutMs: 720_000, oracleVersion: "paperclip.chat-catalog.runtime.block-on-design.v5", + expectedHumanMessageCount: 2, expectedRunCount: 3, attemptTimeoutMs: 720_000, oracleVersion: "paperclip.chat-catalog.runtime.block-on-design.v7", sourceFiles: ["chat-catalog-domains/runtime-dependency.ts", "chat-catalog-domains/api-read-receipts.ts", "chat-catalog-domains/runtime-support.ts", "run-observations.ts", "chat-scenarios/task-coordination.yaml"], async act(ctx, state) { await pollUntil({ label: "Saved dependency and canonical reply before human approval", deadlineAt: chatCatalogNativePhaseDeadline(ctx, Date.now() + 150_000), @@ -75,8 +77,14 @@ export const runtimeDependencyCases = [runtimeDefinition("task-coordination.bloc // A backlog task shows its blockers in the properties panel; the thread's blocker banner appears only once it is Blocked. const blockedBy = ctx.input.page.locator('[data-property-row]:not([inert] *):not([aria-hidden="true"] *)') .filter({ has: ctx.input.page.locator('[data-property-label="Blocked by"]') }).filter({ visible: true }); + // Open the panel through the control the page renders ("Show properties"); a fresh panel shows its tab + // launcher first, from which a person chooses Properties. const panel = ctx.input.page.getByRole("button", { name: /^(Show properties|Properties|Toggle side panel)$/ }).filter({ visible: true }).first(); - if (!await blockedBy.isVisible()) await panel.click(); + const propertiesTab = ctx.input.page.getByRole("option", { name: /^Properties/ }).filter({ visible: true }).first(); + await expect.poll(async () => await blockedBy.isVisible() || await propertiesTab.isVisible() || await panel.isVisible()).toBe(true); + if (!await blockedBy.isVisible() && !await propertiesTab.isVisible()) await panel.click(); + await expect.poll(async () => await blockedBy.isVisible() || await propertiesTab.isVisible()).toBe(true); + if (!await blockedBy.isVisible()) await propertiesTab.click(); await expect(blockedBy.getByText(design.identifier ?? "Design").first()).toBeVisible(); state.blockerVisible = true; const pending = ctx.input.page.waitForResponse(row => row.request().method() === "PATCH" && new URL(row.url()).pathname === websiteRoot); await chooseStatus(ctx.input.page, "Todo"); state.beforeApprovalStatus = (await pending).status(); state.attemptedBeforeApproval = true; diff --git a/tests/runner-e2e/chat-catalog-domains/runtime-git.ts b/tests/runner-e2e/chat-catalog-domains/runtime-git.ts index 5a6dd7cfea8..a0ad75d9407 100644 --- a/tests/runner-e2e/chat-catalog-domains/runtime-git.ts +++ b/tests/runner-e2e/chat-catalog-domains/runtime-git.ts @@ -58,7 +58,7 @@ export const runtimeGitCases = [runtimeDefinition("workspaces.inspect-git", asyn headerBefore: await readFile(header, "utf8"), notesBefore: await readFile(notes, "utf8") }; }, gradeInspectGit, { sourceFiles: ["chat-catalog-domains/runtime-git.ts", "chat-catalog-domains/runtime-workspaces.ts", "chat-catalog-domains/runtime-support.ts", "chat-scenarios/workspaces.yaml"], - oracleVersion: "paperclip.chat-catalog.inspect-git.structural.v3", expectedRunCount: 2, attemptTimeoutMs: 540_000, + oracleVersion: "paperclip.chat-catalog.inspect-git.structural.v4", expectedRunCount: 2, attemptTimeoutMs: 540_000, async observe(ctx, state) { const cwd = String(state.nativeInspectionCwd); state.workspaceAfter = await ctx.input.api.get(`/api/issues/${(state.task as Entity).id}/workspace`); @@ -72,13 +72,17 @@ export const runtimeGitCases = [runtimeDefinition("workspaces.inspect-git", asyn await ctx.input.page.goto(`/${ctx.input.fixtures.company.issuePrefix}/issues/${task.identifier ?? task.id}`, { waitUntil: "domcontentloaded" }); await ctx.input.page.reload({ waitUntil: "domcontentloaded" }); await expect(ctx.input.page.getByRole("heading", { name: task.title!, exact: true }).first()).toBeVisible(); - // The task side panel can start closed; open it through its ordinary toggle, as a person would. - const newTab = ctx.input.page.getByRole("button", { name: "Open a new tab", exact: true }).filter({ visible: true }); - const toggle = ctx.input.page.getByRole("button", { name: "Toggle side panel", exact: true, pressed: false }).filter({ visible: true }); - await expect.poll(async () => await newTab.isVisible() || await toggle.isVisible()).toBe(true); - if (!await newTab.isVisible()) await toggle.click(); - await newTab.click(); - await ctx.input.page.getByRole("option", { name: /^Files/ }).click(); + // The task side panel can start closed; open it through the control the page renders ("Show properties" + // in the task header), as a person would, then choose the Files tab from the panel's tab launcher. + const page = ctx.input.page; + const newTab = page.getByRole("button", { name: "Open a new tab", exact: true }).filter({ visible: true }); + const toggle = page.getByRole("button", { name: /^(Show properties|Toggle side panel)$/ }).filter({ visible: true }).first(); + const files = page.getByRole("option", { name: /^Files/ }).filter({ visible: true }).first(); + await expect.poll(async () => await newTab.isVisible() || await files.isVisible() || await toggle.isVisible()).toBe(true); + if (!await newTab.isVisible() && !await files.isVisible()) await toggle.click(); + await expect.poll(async () => await files.isVisible() || await newTab.isVisible()).toBe(true); + if (!await files.isVisible()) await newTab.click(); + await files.click(); await expect(ctx.input.page.getByText("header.html", { exact: true }).first()).toBeVisible(); await expect(ctx.input.page.getByText("existing-notes.txt", { exact: true }).first()).toBeVisible(); await ctx.input.evidence("runtime-authorized-git-files-ui.json", { taskId: task.id, workspaceId: (state.workspaceBefore as { workspace: { id: string } }).workspace.id, url: ctx.input.page.url() }); diff --git a/tests/runner-e2e/chat-catalog-domains/runtime-independent-review.test.ts b/tests/runner-e2e/chat-catalog-domains/runtime-independent-review.test.ts index 21915282256..4574feb361e 100644 --- a/tests/runner-e2e/chat-catalog-domains/runtime-independent-review.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/runtime-independent-review.test.ts @@ -1,5 +1,5 @@ import { expect, it } from "vitest"; -import { gradeIndependentReview, replyLinksTask } from "./runtime-independent-review.js"; +import { gradeIndependentReview, independentReviewRoles, replyLinksTask } from "./runtime-independent-review.js"; function valid() { const policy = { stages: [{ id: "review-stage", type: "review", participants: [{ type: "agent", agentId: "riley" }] }] }; return { scenarioId: "task-coordination.independent-review", companyId: "company", leadId: "ceo", agents: [], links: [], humanQueries: [], reply: "", tasks: [{ id: "website" }], activity: [], @@ -46,3 +46,35 @@ it("rejects a review that overwrote Morgan's artifact", () => { const o = valid( it("rejects an unbound final chat report", () => { const o = valid(); o.state.finalReplyAttributed = false; expect(gradeIndependentReview(o).passed).toBe(false); }); it("rejects duplicate review work", () => { const o = valid(); o.runs.push({ id: "duplicate", agentId: "riley", status: "succeeded" }); expect(gradeIndependentReview(o).passed).toBe(false); }); it("rejects absent actual review evidence", () => expect(gradeIndependentReview(undefined).passed).toBe(false)); + +// Retained gha-42926311551 (full cohort on 9296c74e8d): the CEO relayed the authorization as a comment on +// COM-1, which woke Morgan (the brief names Morgan as unblock owner who routes the review); Morgan's run +// moved the task to review and Riley's review run started as the fifth run. +function retainedRoles() { + const runs = [ + { id: "impl", agentId: "morgan", status: "succeeded", contextSnapshot: { issueId: "website", wakeReason: "issue_assigned" } }, + { id: "ack", agentId: "ceo", status: "succeeded", contextSnapshot: { issueId: "chat", wakeReason: "issue_commented" } }, + { id: "canonical", agentId: "ceo", status: "succeeded", contextSnapshot: { issueId: "chat", wakeReason: "issue_commented" } }, + { id: "continuation", agentId: "morgan", status: "succeeded", nativeIssueId: "website", contextSnapshot: { issueId: "website", commentId: "authorization", wakeReason: "issue_reopened_via_comment" } }, + { id: "review", agentId: "riley", status: "running", contextSnapshot: { issueId: "website", wakeReason: "native_completion_review" } }, + ]; + const comments = [{ id: "authorization", issueId: "website", createdByRunId: "canonical" }]; + return { runs, comments, setupRunIds: ["impl", "ack"], leadId: "ceo", sourceId: "chat", workerId: "morgan", reviewerId: "riley", taskId: "website" }; +} +it("admits the retained owner-routed path: one Morgan continuation woken by the CEO's comment, then one Riley review", () => { + const roles = independentReviewRoles(retainedRoles()); + expect(roles.valid).toBe(true); expect(roles.canonical.map(run => run.id)).toEqual(["canonical"]); + expect(roles.continuation.map(run => run.id)).toEqual(["continuation"]); expect(roles.review.map(run => run.id)).toEqual(["review"]); + const o = valid(); (o.state as Record).ownerContinuationRunId = "continuation"; + o.runs.splice(3, 0, { id: "continuation", agentId: "morgan", status: "succeeded", nativeIssueId: "website" } as typeof o.runs[number]); + expect(gradeIndependentReview(o).passed).toBe(true); +}); +it("still rejects extra or duplicate work around the owner-routed path", () => { + const unprompted = retainedRoles(); unprompted.comments = []; expect(independentReviewRoles(unprompted).valid).toBe(false); + const otherCause = retainedRoles(); otherCause.comments[0]!.createdByRunId = "ack"; expect(independentReviewRoles(otherCause).valid).toBe(false); + const twice = retainedRoles(); twice.runs.push({ ...twice.runs[3]!, id: "again" }); expect(independentReviewRoles(twice).valid).toBe(false); + const reviews = retainedRoles(); reviews.runs.push({ ...reviews.runs[4]!, id: "second-review" }); expect(independentReviewRoles(reviews).valid).toBe(false); + const stranger = retainedRoles(); stranger.runs.push({ id: "x", agentId: "other", status: "succeeded", contextSnapshot: { issueId: "website", wakeReason: "issue_assigned" } }); expect(independentReviewRoles(stranger).valid).toBe(false); + // The grade counts the continuation only when it was recorded as the admitted owner run. + const o = valid(); o.runs.splice(3, 0, { id: "continuation", agentId: "morgan", status: "succeeded" }); expect(gradeIndependentReview(o).passed).toBe(false); +}); diff --git a/tests/runner-e2e/chat-catalog-domains/runtime-independent-review.ts b/tests/runner-e2e/chat-catalog-domains/runtime-independent-review.ts index 7f70a258d63..0a9ca2b2f42 100644 --- a/tests/runner-e2e/chat-catalog-domains/runtime-independent-review.ts +++ b/tests/runner-e2e/chat-catalog-domains/runtime-independent-review.ts @@ -13,6 +13,7 @@ import { checks, type Entity } from "./internal-support.js"; import { openStandingChat } from "./identity-support.js"; import { prepareRuntimeWorkerGate, releaseRuntimeWorker } from "./runtime-busy-worker.js"; import { observeRuntime, runtimeDefinition, runtimeObservation, runtimeWorker } from "./runtime-support.js"; +import { commentWokenContinuations, runIssueId, type RoleComment, type RoleRun } from "./run-roles.js"; const credentials = new WeakMap>(); /** Whether a saved reply body has a Markdown link to this exact task page. */ export function replyLinksTask(body: string, task: { id: string; identifier?: string | null }) { @@ -21,6 +22,19 @@ export function replyLinksTask(body: string, task: { id: string; identifier?: st return index >= 0 && index === parts.length - 2 && [task.id, task.identifier].filter(Boolean).includes(parts[index + 1]); } catch { return false; } }); } +/** Runs after setup, by role: the CEO's chat turns, at most one Morgan continuation woken by a CEO + * comment on the task (the owner routes the saved deliverable for review), and one Riley review run. + * Any other run is extra work and invalidates the request. */ +export function independentReviewRoles(input: { runs: RoleRun[]; comments: RoleComment[]; setupRunIds: readonly string[]; + leadId: string; sourceId: string; workerId: string; reviewerId: string; taskId: string }) { + const extra = input.runs.filter(run => !input.setupRunIds.includes(run.id)); + const canonical = extra.filter(run => run.agentId === input.leadId && runIssueId(run) === input.sourceId); + const continuation = commentWokenContinuations(extra, { agentId: input.workerId, issueId: input.taskId, comments: input.comments, causeRunIds: canonical.map(run => run.id) }); + const review = extra.filter(run => run.agentId === input.reviewerId && runIssueId(run) === input.taskId); + const unexplained = extra.filter(run => !canonical.includes(run) && !continuation?.includes(run) && !review.includes(run)); + return { canonical, continuation: continuation ?? [], review, + valid: !!continuation && continuation.length <= 1 && review.length <= 1 && unexplained.length === 0 }; +} export function gradeIndependentReview(value: unknown) { const c = checks(), o = runtimeObservation(value); c.add("actual-delivery-and-independent-review-evidence", !!o, "Real implementation bytes, pending policy, native independent review and later source report are required."); if (!o) return c.result(); @@ -41,8 +55,9 @@ export function gradeIndependentReview(value: unknown) { c.add("authorized-review-then-final-completion", current?.id === before.id && current.status === "done" && current.executionState?.status === "completed" && current.executionState.lastDecisionOutcome === "approved" && !!current.executionState.lastDecisionId && JSON.stringify(current.executionPolicy) === JSON.stringify(before.executionPolicy) && s.rileyApprovalBound === true && s.implementationRetained === true - && o.runs.length === 5 && o.runs.every(row => row.status === "succeeded") && o.runs.filter(row => row.agentId === (s.reviewer as Entity).id).length === 1 && o.tasks.length === 1, - "Only Riley's actual native approval resolves the same configured review stage and completes the same work while retaining Morgan's artifact."); + && o.runs.length === 5 + (s.ownerContinuationRunId ? 1 : 0) && o.runs.every(row => row.status === "succeeded") && o.runs.filter(row => row.agentId === (s.reviewer as Entity).id).length === 1 && o.tasks.length === 1 + && (!s.ownerContinuationRunId || o.runs.some(row => row.id === s.ownerContinuationRunId && row.agentId === (s.worker as Entity).id && runIssueId(row) === before.id)), + "Only Riley's actual native approval resolves the same configured review stage and completes the same work while retaining Morgan's artifact. Morgan may route the review once when the CEO's authorization comment wakes Morgan; no other run is admitted."); c.add("own-later-reply-reports-the-resolved-task", s.finalReplyAttributed === true && s.finalReplyLinksTask === true, "A later declared human question receives its own run-bound reply that links the governed task, already approved and done in saved state. Whether its wording claims the wrong phase is left to a human reader."); return c.result(); @@ -72,17 +87,21 @@ export const runtimeIndependentReviewCases = [runtimeDefinition("task-coordinati return { worker, reviewer, gate: prepared.gate, task: delivered.task, implementationBefore: delivered.task, marker, artifact, implementationRunId: delivered.runs[0]!.id, actualImplementation: true, setupReviewRunCount: 0, setupRunIds: acknowledged.runs.map(row => row.id), reviewerEligibleBeforeQuery: reviewer.lifecycleState === "ready" && ["active", "idle"].includes(reviewer.status ?? "") }; }, gradeIndependentReview, { - authentication: "human-session", setupHumanMessageCount: 1, expectedHumanMessageCount: 3, expectedRunCount: 5, attemptTimeoutMs: 1_020_000, - oracleVersion: "paperclip.chat-catalog.runtime.independent-review.v4", - sourceFiles: ["chat-catalog-domains/runtime-independent-review.ts", "chat-catalog-domains/runtime-support.ts", "chat-catalog-domains/runtime-busy-worker.ts", "chat-catalog-domains/identity-support.ts", "registered-artifact.ts", "chat-scenarios/task-coordination.yaml"], + authentication: "human-session", setupHumanMessageCount: 1, expectedHumanMessageCount: 3, expectedRunCount: 6, minimumRunCount: 5, attemptTimeoutMs: 1_020_000, + oracleVersion: "paperclip.chat-catalog.runtime.independent-review.v5", + sourceFiles: ["chat-catalog-domains/runtime-independent-review.ts", "chat-catalog-domains/run-roles.ts", "chat-catalog-domains/runtime-support.ts", "chat-catalog-domains/runtime-busy-worker.ts", "chat-catalog-domains/identity-support.ts", "registered-artifact.ts", "chat-scenarios/task-coordination.yaml"], async act(ctx, state) { const task = state.task as Issue, reviewer = state.reviewer as Entity; + const roles = (v: { runs: RoleRun[]; comments: RoleComment[] }) => independentReviewRoles({ ...v, setupRunIds: state.setupRunIds as string[], leadId: ctx.input.fixtures.agent.id, + sourceId: ctx.issue()!.id, workerId: (state.worker as Entity).id, reviewerId: reviewer.id, taskId: task.id }); + const taskComments = () => ctx.input.api.get(`/api/issues/${task.id}/comments?order=asc`); const pending = await pollUntil({ label: "Canonical authorization starts Riley's genuine independent review stage", deadlineAt: chatCatalogNativePhaseDeadline(ctx, Date.now() + 180_000), - load: async () => { await ctx.refreshIssue(); return { source: ctx.issue(), runs: await ctx.allRuns(), task: await ctx.input.api.get(`/api/issues/${task.id}`), ready: await readFile((state.gate as { ready: string }).ready, "utf8").catch(() => "") }; }, - accept: v => chatCatalogNativePhaseIsTimely(ctx) && (v.source?.conversationState === "waiting" && v.runs.length === 4 && v.task.status === "in_review" && v.task.executionState?.currentParticipant?.agentId === reviewer.id - && v.ready === "waiting" && v.runs.some(row => row.agentId === reviewer.id && row.status === "running") && v.runs.filter(row => row.agentId !== reviewer.id).every(row => row.status === "succeeded")), - reject: v => v.runs.length > 4 || v.runs.some(row => ["failed", "cancelled", "timed_out"].includes(row.status)) ? "The authorized independent review failed, duplicated, or bypassed the saved gate" : undefined }); + load: async () => { await ctx.refreshIssue(); return { source: ctx.issue(), runs: await ctx.allRuns(), comments: await taskComments(), task: await ctx.input.api.get(`/api/issues/${task.id}`), ready: await readFile((state.gate as { ready: string }).ready, "utf8").catch(() => "") }; }, + accept: v => { const r = roles(v); return chatCatalogNativePhaseIsTimely(ctx) && (v.source?.conversationState === "waiting" && r.valid && r.canonical.length === 1 && r.review.length === 1 && v.task.status === "in_review" && v.task.executionState?.currentParticipant?.agentId === reviewer.id + && v.ready === "waiting" && r.review[0]!.status === "running" && v.runs.filter(row => row.agentId !== reviewer.id).every(row => row.status === "succeeded")); }, + reject: v => { const r = roles(v); return !r.valid || r.canonical.length > 1 || v.runs.some(row => ["failed", "cancelled", "timed_out"].includes(row.status)) ? "The authorized independent review failed, duplicated, or bypassed the saved gate" : undefined; } }); state.pendingReview = pending.task; state.reviewerWasReallyWaiting = true; state.pendingReply = ""; + const continuation = roles(pending).continuation[0]; if (continuation) state.ownerContinuationRunId = continuation.id; const reviewRun = pending.runs.find(row => row.agentId === reviewer.id)!; state.reviewRunId = reviewRun.id; const canonicalRuns = pending.runs.filter(row => row.agentId === ctx.input.fixtures.agent.id && !(state.setupRunIds as string[]).includes(row.id)); if (canonicalRuns.length !== 1) throw new Error("Independent review lacks exactly one canonical source turn"); @@ -92,7 +111,10 @@ export const runtimeIndependentReviewCases = [runtimeDefinition("task-coordinati state.pendingReplyAttributed = canonicalHumans.length === 1 && canonicalReplies.length > 0 && canonicalFull.runnerProfileJson?.nativeExecutionInput?.task?.prompt?.includes(canonicalHumans[0]!.id) === true; state.pendingReply = canonicalReplies.map(row => row.body).join("\n"); state.pendingReplyLinksTask = replyLinksTask(String(state.pendingReply), task); const activity = await ctx.input.api.get(`/api/issues/${task.id}/activity`); - state.reviewRequestSourceBound = activity.some(row => row.agentId === ctx.input.fixtures.agent.id && row.runId === canonical.id && row.details?.status === "in_review"); + // The CEO requests review itself, or its authorization comment wakes Morgan, whose own + // run routes the saved deliverable to review (a native status decision is a system write). + state.reviewRequestSourceBound = activity.some(row => row.agentId === ctx.input.fixtures.agent.id && row.runId === canonical.id && row.details?.status === "in_review") + || !!continuation && activity.some(row => row.runId === continuation.id && (row.details?.status === "in_review" || row.details?.toStatus === "in_review")); const keySet = credentials.get(ctx); if (!keySet) throw new Error("Independent review probes lost their actual identities"); const implementationKey = keySet.find(row => row.agentId === (state.worker as Entity).id)!, reviewKey = keySet.find(row => row.agentId === reviewer.id)!; const selfApproval = await fetch(new URL(`/api/issues/${task.id}`, ctx.input.api.baseURL), { method: "PATCH", redirect: "error", signal: AbortSignal.timeout(15_000), @@ -116,15 +138,16 @@ export const runtimeIndependentReviewCases = [runtimeDefinition("task-coordinati await ctx.input.capture("actual-independent-review-pending", "Riley's actual review stage remains pending after rejected implementer self-approval", "runtime-independent-review.png"); await writeFile((state.gate as { gate: string }).gate, "The human review observation is complete. Independently inspect Morgan's actual registered website.html against the saved heading/product/signup and accessibility criteria. Record your actual verification and acceptance reference in website-review. If the real result passes, approve your own configured review stage with a substantive decision comment through the supported path; do not manufacture a result, change policy, or create tasks.", "utf8"); const completed = await pollUntil({ label: "Actual Riley native approval resolves the governed task", deadlineAt: Date.now() + 240_000, - load: async () => ({ task: await ctx.input.api.get(`/api/issues/${task.id}`), runs: await ctx.allRuns() }), - accept: v => v.task.status === "done" && v.task.executionState?.status === "completed" && v.runs.length === 4 && v.runs.every(row => row.status === "succeeded"), - reject: v => v.runs.length > 4 || v.runs.some(row => ["failed", "cancelled", "timed_out"].includes(row.status)) ? "Actual independent review failed or admitted undeclared work" : undefined }); + load: async () => ({ task: await ctx.input.api.get(`/api/issues/${task.id}`), runs: await ctx.allRuns(), comments: await taskComments() }), + accept: v => { const r = roles(v); return v.task.status === "done" && v.task.executionState?.status === "completed" && r.valid && r.canonical.length === 1 && r.review.length === 1 && r.continuation.length === (continuation ? 1 : 0) && v.runs.every(row => row.status === "succeeded"); }, + reject: v => { const r = roles(v); return !r.valid || r.canonical.length > 1 || r.continuation.length !== (continuation ? 1 : 0) || v.runs.some(row => ["failed", "cancelled", "timed_out"].includes(row.status)) ? "Actual independent review failed or admitted undeclared work" : undefined; } }); state.reviewAfter = completed.task; await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" }); const followup = `What is the actual outcome of Riley's independent review of Launch Website ${task.identifier ?? task.id}, and is the governed task now finished?`; await sendChatMessage(ctx.input.page, followup, chatCatalogNativePhaseRemainingBudget(ctx)); const final = await pollUntil({ label: "Own source phase reports actual review and completion", deadlineAt: chatCatalogNativePhaseDeadline(ctx, Date.now() + 150_000), - load: async () => { await ctx.refreshIssue(); return { source: ctx.issue(), runs: await ctx.allRuns() }; }, accept: v => chatCatalogNativePhaseIsTimely(ctx) && (v.source?.conversationState === "waiting" && v.runs.length === 5 && v.runs.every(row => row.status === "succeeded")) }); + load: async () => { await ctx.refreshIssue(); return { source: ctx.issue(), runs: await ctx.allRuns(), comments: await taskComments() }; }, + accept: v => { const r = roles(v); return chatCatalogNativePhaseIsTimely(ctx) && (v.source?.conversationState === "waiting" && r.valid && r.canonical.length === 2 && r.continuation.length === (continuation ? 1 : 0) && v.runs.length === completed.runs.length + 1 && v.runs.every(row => row.status === "succeeded")); } }); const run = final.runs.find(row => !completed.runs.some(prior => prior.id === row.id))!; const comments = await ctx.input.api.get(`/api/issues/${ctx.issue()!.id}/comments?order=asc`), human = comments.filter(row => !row.authorAgentId && row.body === followup), replies = comments.filter(row => row.authorAgentId === ctx.input.fixtures.agent.id && row.createdByRunId === run.id); const full = await ctx.input.api.get<{ runnerProfileJson?: { nativeExecutionInput?: { task?: { prompt?: string } } } }>(`/api/heartbeat-runs/${run.id}`); diff --git a/tests/runner-e2e/chat-catalog-run-policy.test.ts b/tests/runner-e2e/chat-catalog-run-policy.test.ts index 5817ea71f07..b6f55f6cc2f 100644 --- a/tests/runner-e2e/chat-catalog-run-policy.test.ts +++ b/tests/runner-e2e/chat-catalog-run-policy.test.ts @@ -118,3 +118,15 @@ it("treats only a never-started run cancelled by its own task's terminal status const implementation = { expectedRunCount: 3, runPolicy: { kind: "source-settled-with-active-work" as const, maximumActiveWorkerRuns: 1 } }; expect(gradeChatCatalogRuns({ ...scope, implementation, runs: [succeeded, worker, queued] }).passed).toBe(false); }); +it("admits a declared role-bound range above an exact terminal count, and nothing beyond it", () => { + const cancelled = { ...succeeded, id: "stopped", status: "cancelled" }; + const ok = (id: string) => ({ ...succeeded, id }); + const implementation = { expectedRunCount: 6, minimumRunCount: 4, runPolicy: { kind: "terminal-counts" as const, terminalStatusCounts: { cancelled: 1, succeeded: 3 }, maximumTerminalStatusCounts: { succeeded: 5 } } }; + expect(gradeChatCatalogRuns({ ...scope, implementation, runs: [cancelled, ok("a"), ok("b"), ok("c")] }).passed).toBe(true); + expect(gradeChatCatalogRuns({ ...scope, implementation, runs: [cancelled, ok("a"), ok("b"), ok("c"), ok("d"), ok("e")] }).passed).toBe(true); + expect(gradeChatCatalogRuns({ ...scope, implementation, runs: [cancelled, ok("a"), ok("b")] }).passed).toBe(false); + expect(gradeChatCatalogRuns({ ...scope, implementation: { ...implementation, expectedRunCount: 7 }, runs: [cancelled, ok("a"), ok("b"), ok("c"), ok("d"), ok("e"), ok("f")] }).passed).toBe(false); + // A maximum may only widen a status the exact counts already declare. + const undeclared = { ...implementation, runPolicy: { ...implementation.runPolicy, maximumTerminalStatusCounts: { failed: 1 } } }; + expect(gradeChatCatalogRuns({ ...scope, implementation: undeclared, runs: [cancelled, ok("a"), ok("b"), ok("c")] }).passed).toBe(false); +}); diff --git a/tests/runner-e2e/chat-catalog-run-policy.ts b/tests/runner-e2e/chat-catalog-run-policy.ts index 5da68ee0cfc..97684647397 100644 --- a/tests/runner-e2e/chat-catalog-run-policy.ts +++ b/tests/runner-e2e/chat-catalog-run-policy.ts @@ -60,8 +60,12 @@ export function gradeChatCatalogRuns(input: { detail: "Only edit-properties may declare the exact independently proved worker reassignment cancellation." }); } if (c.runPolicy?.kind === "terminal-counts") { - checks.push({ id: "catalog-exact-run-outcomes", passed: Object.entries(c.runPolicy.terminalStatusCounts).every(([status, count]) => runs.filter(run => run.status === status).length === count), - detail: "The independently observed ledger matches every declared successful/cancelled/failed terminal outcome count." }); + const policy = c.runPolicy, maximum = policy.maximumTerminalStatusCounts ?? {}; + checks.push({ id: "catalog-exact-run-outcomes", passed: Object.entries(policy.terminalStatusCounts).every(([status, count]) => { + const actual = runs.filter(run => run.status === status).length, upper = maximum[status as keyof typeof maximum] ?? count; + return actual >= count! && actual <= Math.max(count!, upper); + }) && Object.keys(maximum).every(status => status in policy.terminalStatusCounts), + detail: "The independently observed ledger matches every declared successful/cancelled/failed terminal outcome count (or its declared role-bound range)." }); } else if (c.runPolicy?.kind === "source-settled-with-active-work") { const sourceRuns = runs.filter(run => taskId(run) === source?.id); const workers = runs.filter(run => taskId(run) !== source?.id); diff --git a/tests/runner-e2e/chat-rendered-links.test.ts b/tests/runner-e2e/chat-rendered-links.test.ts index f24d8ce52ed..3c00591235c 100644 --- a/tests/runner-e2e/chat-rendered-links.test.ts +++ b/tests/runner-e2e/chat-rendered-links.test.ts @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { readFileSync } from "node:fs"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { conversationLinkBindings, readConversationDomLinks, type ConversationLinkInput } from "./chat-rendered-links.js"; +import { collectConversationLinks, conversationLinkBindings, readConversationDomLinks, readLatestConversationReplyRender, waitForLatestConversationReplyRender, type ConversationLinkInput } from "./chat-rendered-links.js"; const card = '
'; const thread = (content = card) => `
Create a project called Launch for the new website.
${content}
Created the Launch project. No repositories are connected yet.
`; @@ -91,3 +91,24 @@ it("retains ordinary inline links in the supported classic issue-chat root", () document.querySelector('#comment-reply')!.innerHTML='Task'; expect(collect().map(row=>[row.threadTestId,row.source,row.href])).toEqual([['thread-root','reply','/RUN/issues/task']]); }); + +// Full cohort on 9296c74e8d (choose-primary, case-history, set-budget): the API saw the saved reply ~2s before +// the open conversation rendered it, so links read in between were empty although the reply linked correctly. +describe("waits for the latest saved reply to render before reading links", () => { + const page = () => ({ evaluate: async (read: (arg: A) => T, arg: A) => read(arg) }) as unknown as Parameters[0]; + it("reads the reply's links once the reply renders after the API saw it", async () => { + document.querySelector('#comment-reply')!.remove(); + setTimeout(() => document.querySelector('[data-testid="task-chat-scroller"]')!.insertAdjacentHTML("beforeend", ''), 600); + const value = input(); value.projects = []; value.activity = []; + expect((await collectConversationLinks(page(), value)).map(row => row.href)).toEqual(["/RUN/issues/task"]); + }); + it("does not wait when the conversation is not open, and waits at most once for a reply that never renders", async () => { + const bindings = conversationLinkBindings(input()); + document.body.innerHTML = "
Other page
"; + expect(readLatestConversationReplyRender({ anchors: bindings.anchors, latest: "reply" })).toBe("closed"); + document.body.innerHTML = thread(); document.querySelector('#comment-reply')!.remove(); + const p = page(); + expect(await waitForLatestConversationReplyRender(p, bindings, 300, 50)).toBe("pending"); + const started = Date.now(); expect(await waitForLatestConversationReplyRender(p, bindings, 5_000, 50)).toBe("pending"); expect(Date.now() - started).toBeLessThan(1_000); + }); +}); diff --git a/tests/runner-e2e/chat-rendered-links.ts b/tests/runner-e2e/chat-rendered-links.ts index dadca64ce19..f4971881060 100644 --- a/tests/runner-e2e/chat-rendered-links.ts +++ b/tests/runner-e2e/chat-rendered-links.ts @@ -77,8 +77,45 @@ export function readConversationDomLinks(input: ReturnType>(); +export type ConversationReplyRender = "closed" | "rendered" | "pending"; +export function readLatestConversationReplyRender(input: { anchors: string[]; latest: string }): ConversationReplyRender { + const threadSelector = '[data-testid="task-chat-thread"], [data-testid="thread-root"]'; + // A thread is this conversation's when every comment it renders is one of its saved comments; a thread that + // has not rendered any comment yet (still loading after navigation or reload) counts too. + const roots = Array.from(document.querySelectorAll(threadSelector)).filter(root => + Array.from(root.querySelectorAll('[id^="comment-"]')).every(node => input.anchors.some(id => node.id === `comment-${id}`))); + if (!roots.length) return "closed"; + const rendered = roots.some(root => Array.from(root.querySelectorAll('[id^="comment-"]')) + .some(node => node.id === `comment-${input.latest}` && node.getClientRects().length > 0)); + return rendered ? "rendered" : "pending"; +} +export async function waitForLatestConversationReplyRender(page: Pick, bindings: Pick, "anchors" | "replies">, + timeoutMs = CONVERSATION_REPLY_RENDER_WAIT_MS, intervalMs = 250): Promise { + const latest = bindings.replies.at(-1); + if (!latest) return "rendered"; + const expired = expiredReplyWaits.get(page) ?? new Set(); + if (expired.has(latest)) timeoutMs = 0; + // Bounded by attempts as well as time so a frozen test clock cannot spin. + for (let attempt = 0, attempts = Math.max(1, Math.ceil(timeoutMs / intervalMs)), deadlineAt = Date.now() + timeoutMs; ; attempt++) { + let state: unknown; + try { state = await page.evaluate(readLatestConversationReplyRender, { anchors: bindings.anchors, latest }); } catch { return "closed"; } + if (state !== "pending") return state === "closed" ? "closed" : "rendered"; + if (attempt + 1 >= attempts || Date.now() >= deadlineAt) { expired.add(latest); expiredReplyWaits.set(page, expired); return "pending"; } + await new Promise(resolve => setTimeout(resolve, intervalMs)); + } +} export async function collectConversationLinks(page: Page, input: ConversationLinkInput) { - return page.evaluate(readConversationDomLinks, conversationLinkBindings(input)); + const bindings = conversationLinkBindings(input); + await waitForLatestConversationReplyRender(page, bindings); + return page.evaluate(readConversationDomLinks, bindings); } export function conversationLinkLocator(page: Page, link: RenderedConversationLink): Locator { const thread = page.getByTestId(link.threadTestId).filter({ has: page.locator(`[id=${JSON.stringify(`comment-${link.anchorCommentId}`)}]`) }); From a8f21a171c760e9f015e77e9ee23cb92673a5432 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:41:27 -0600 Subject: [PATCH 17/38] fix(cases): hold direct case status writes to terminal handoff authority (#20686) 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 > - The experimental Cases feature closes a case through a terminal handoff to `done` > - The terminal handoff lets an agent close a case only when the agent owns the case's primary task > - The direct case write routes (`PATCH /api/cases/:id` and the keyed upsert on `POST /api/companies/:companyId/cases`) also write `status` and `completedAt` > - These routes did not apply the primary-task ownership rule to agent status writes > - This pull request applies the same ownership rule to those routes, and sends `done` through the terminal handoff > - The benefit is that a case closes only through the authority and gates that the product describes ## Linked Issues or Issue Description No public issue exists. This is the bug description. **What happened** An agent that did not own a case's primary task tried `handoff_case` to `done` and got "Agents may complete only their own case work". The same agent then sent `PATCH /api/cases/:id` with `status: "done"`. The route returned 200 and closed the case. A chat eval (`cases.close-case`) recorded this sequence. **Expected behavior** An agent changes a case with a primary task to or from `done`/`cancelled` only with the authority that the terminal handoff requires. `done` goes through the terminal handoff, so primary-task completion keeps its normal gates (`doc/PRODUCT.md`, Cases section). The dedicated `update_case` tool already excludes `status`. **Steps to reproduce** 1. Create a case with a primary task that is assigned to agent A. 2. As agent B in the same company, send `PATCH /api/cases/:id` with `{"status":"done"}`. 3. Before this change, the response is 200 and the case status is `done`. ## What Changed - `server/src/services/case-handoffs.ts`: add `assertCaseStatusWriteAuthority`. For an agent actor, on a case that has a primary task, a status change into or out of `done`/`cancelled` must pass the same check as the terminal handoff (`authorizeTerminalTask`: the agent is the primary task's assignee). A change to `done` then returns 422 and names the terminal handoff. Board actors, non-terminal status changes and fact edits do not change. - `server/src/routes/cases.ts`: call the check inside the case write transaction in `PATCH /api/cases/:id` and in the keyed upsert branch of `POST /api/companies/:companyId/cases`. - The terminal ownership denial now names the owning agent and the primary task, and asks the caller to contact that agent on the task. The message keeps its old first sentence. - The keyed upsert falls back to the locked case row (not the pre-lock read), so an upsert without `status` cannot undo a concurrent close. - `server/src/routes/experimental-api-paths.ts`: add a catalog summary and description for `PATCH /api/cases/{id}` that states the closure rule. - `server/src/__tests__/cases-routes.test.ts`: regression test for non-owner `done`/`cancelled` through PATCH and upsert, the owner's `done` through PATCH (422), owner cancel, non-owner reopen, and board close. ## Verification - `cd server && npx vitest run src/__tests__/cases-routes.test.ts -t "terminal handoff's primary-task"`: fails before the route change (`expected 403, got 200`) and passes after it. - `cd server && npx vitest run src/__tests__/cases-routes.test.ts src/__tests__/case-mutation-fence.integration.test.ts src/__tests__/case-handoff-native.integration.test.ts src/__tests__/case-handoff-legacy.integration.test.ts src/services/case-handoffs.test.ts src/services/native-runtime/native-case-tools.integration.test.ts src/__tests__/heartbeat-case-terminal-handoff.test.ts src/__tests__/openapi-routes.test.ts src/__tests__/case-history-api-discovery.test.ts src/services/native-runtime/runner-api.test.ts`: all pass. (One local run of the legacy integration suite failed in fixture scratch preparation under load; two reruns with the change pass.) - `server` `tsc --noEmit`: no errors in the changed files. The fresh worktree had unrelated errors from unbuilt workspace packages; CI covers the full typecheck. - Live chat eval (`chat-features.runner-opencode.local.cases.close-case`, run 42936492869, at the first commit): the non-owner agent's terminal handoff was denied with the owner named, and the agent did not change case status through another route. The eval did not pass: the first chat turn did not finish inside the scenario's 180-second observation window. That is a separate latency issue in the eval. ## Risks - Behavior change for agents: an agent can no longer set `done` through PATCH on a case with a primary task, and a non-owner agent can no longer cancel or reopen it. The agent skill reference already says "Do not change case status separately". - Cases without a primary task keep the old behavior, because they have no owner to check and the terminal handoff does not apply to them. - The check reads the primary task without a row lock, to keep the task -> run -> case lock order. A concurrent reassignment can race one request. The terminal handoff itself still locks and rechecks. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] 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 --- server/src/__tests__/cases-routes.test.ts | 68 +++++++++++++++++++++ server/src/routes/cases.ts | 18 +++--- server/src/routes/experimental-api-paths.ts | 2 + server/src/services/case-handoffs.ts | 29 ++++++++- 4 files changed, 109 insertions(+), 8 deletions(-) diff --git a/server/src/__tests__/cases-routes.test.ts b/server/src/__tests__/cases-routes.test.ts index 055f56ff9b4..8aefa71e864 100644 --- a/server/src/__tests__/cases-routes.test.ts +++ b/server/src/__tests__/cases-routes.test.ts @@ -477,6 +477,74 @@ describeEmbeddedPostgres("cases routes", () => { expect(eventRows.filter((event) => event.runId === runId)).toHaveLength(eventRows.length); }); + it("holds direct case status writes to the terminal handoff's primary-task authority", async () => { + await enableCases(); + const company = await seedCompany("TRM"); + const owner = await seedAgent(company.id); + const other = await seedAgent(company.id); + const [primary] = await db.insert(issues).values({ + companyId: company.id, + identifier: `${company.issuePrefix.toUpperCase()}-1`, + title: "Primary case task", + status: "done", + assigneeAgentId: owner.id, + }).returning(); + const [caseRow] = await db.insert(cases).values({ + companyId: company.id, + caseNumber: 1, + identifier: `${company.issuePrefix.toUpperCase()}-C1`, + caseType: "customer", + key: "accepted-fix", + title: "Accepted fix", + status: "in_review", + workIssueId: primary!.id, + }).returning(); + const agentActor = (agentId: string): Express.Request["actor"] => ({ + type: "agent", + companyId: company.id, + agentId, + source: "agent_key", + keyId: `key-${agentId}`, + onBehalfOfUserId: null, + onBehalfOfMemberships: [], + }); + const otherHttp = request(app(agentActor(other.id))); + const readCase = async () => (await db.select().from(cases).where(eq(cases.id, caseRow!.id)))[0]!; + + for (const status of ["done", "cancelled"] as const) { + const denied = await otherHttp.patch(`/api/cases/${caseRow!.id}`).send({ status }).expect(403); + expect(denied.body.error).toBe(`Agents may complete only their own case work. ${owner.name} (agent ${owner.id}) owns primary task ${primary!.identifier} and records the terminal handoff. Ask that agent on ${primary!.identifier} to close the case.`); + } + const upsert = await otherHttp + .post(`/api/companies/${company.id}/cases`) + .send({ caseType: "customer", key: "accepted-fix", title: "Accepted fix", status: "done" }) + .expect(403); + expect(upsert.body.error).toMatch(/^Agents may complete only their own case work\. /); + expect(await readCase()).toMatchObject({ status: "in_review", completedAt: null }); + + // Fact edits and non-terminal status remain ordinary case writes. + await otherHttp.patch(`/api/cases/${caseRow!.id}`).send({ title: "Accepted checkout fix" }).expect(200); + await otherHttp.patch(`/api/cases/${caseRow!.id}`).send({ status: "in_progress" }).expect(200); + + // The owner still closes through the terminal handoff, not a raw status write. + const ownerHttp = request(app(agentActor(owner.id))); + await ownerHttp.patch(`/api/cases/${caseRow!.id}`).send({ status: "done" }).expect(422); + expect(await readCase()).toMatchObject({ status: "in_progress", completedAt: null }); + await ownerHttp.patch(`/api/cases/${caseRow!.id}`).send({ status: "cancelled" }).expect(200); + const reopen = await otherHttp.patch(`/api/cases/${caseRow!.id}`).send({ status: "in_progress" }).expect(403); + expect(reopen.body.error).toMatch(/^Agents may complete only their own case work\. /); + + await request(app(boardActor)).patch(`/api/cases/${caseRow!.id}`).send({ status: "done" }).expect(200); + expect(await readCase()).toMatchObject({ status: "done", completedAt: expect.any(Date) }); + + // An upsert without status keeps the locked row's status and completion. + await otherHttp + .post(`/api/companies/${company.id}/cases`) + .send({ caseType: "customer", key: "accepted-fix", title: "Accepted checkout fix" }) + .expect(200); + expect(await readCase()).toMatchObject({ status: "done", completedAt: expect.any(Date) }); + }); + it("rejects cross-company agent access across the cases route surface", async () => { await enableCases(); const ownCompany = await seedCompany("OWN"); diff --git a/server/src/routes/cases.ts b/server/src/routes/cases.ts index db853f38e38..e6897b69a57 100644 --- a/server/src/routes/cases.ts +++ b/server/src/routes/cases.ts @@ -60,6 +60,7 @@ import { listIssueStatusBlockerAttention } from "../services/issue-status-presen import type { IssueBlockerAttention } from "@paperclipai/shared"; import { listCaseTaskDocuments } from "../services/case-task-documents.js"; import { authorizeCaseCreation, authorizeCaseMutation } from "../services/case-mutation-authorization.js"; +import { assertCaseStatusWriteAuthority } from "../services/case-handoffs.js"; import { logger } from "../middleware/logger.js"; import { assertCompanyAccess, getActorInfo, hasCompanyAccess } from "./authz.js"; @@ -694,19 +695,21 @@ export function caseRoutes(db: Db, storage: StorageService) { .then((rows) => rows[0] ?? null); if (existing) { - await authorizeCaseMutation(tx as unknown as Db, req.actor, existing.id, companyId); + const current = await authorizeCaseMutation(tx as unknown as Db, req.actor, existing.id, companyId); + await assertCaseStatusWriteAuthority(tx as unknown as Db, req.actor, current, body.status); if (body.projectId) await retainCaseAccessSource(tx, { companyId, caseId: existing.id, sourceKind: "project", sourceId: body.projectId, }); - const status = body.status ?? existing.status; + // Fall back to the locked row so a concurrent close or reopen is not undone. + const status = body.status ?? current.status; const [updated] = await tx.update(cases).set({ - projectId: body.projectId ?? existing.projectId, + projectId: body.projectId ?? current.projectId, title: body.title, - summary: body.summary ?? existing.summary, + summary: body.summary ?? current.summary, status, - fields: body.fields ?? existing.fields, - parentCaseId: body.parentCaseId ?? existing.parentCaseId, - completedAt: completedAtForStatus(status, existing.completedAt), + fields: body.fields ?? current.fields, + parentCaseId: body.parentCaseId ?? current.parentCaseId, + completedAt: completedAtForStatus(status, current.completedAt), updatedAt: now, }).where(eq(cases.id, existing.id)).returning(); await insertCaseEvent(tx, { @@ -1592,6 +1595,7 @@ export function caseRoutes(db: Db, storage: StorageService) { const nextLabelIds = body.labelIds ?? body.labels; const updated = await mutateCase(req, caseRow, async (tx, currentCase) => { + await assertCaseStatusWriteAuthority(tx as unknown as Db, req.actor, currentCase, body.status); await assertProjectBelongsToCompany(tx, { companyId: caseRow.companyId, projectId: body.projectId ?? null }); if (body.projectId) { if (!(await authorizationService(tx).decide({ actor: req.actor, action: "project:read", resource: { diff --git a/server/src/routes/experimental-api-paths.ts b/server/src/routes/experimental-api-paths.ts index 432f165d012..ca68a76181b 100644 --- a/server/src/routes/experimental-api-paths.ts +++ b/server/src/routes/experimental-api-paths.ts @@ -51,6 +51,8 @@ export const experimentalApiDocs: Record Date: Tue, 10 Nov 2026 20:44:09 -0600 Subject: [PATCH 18/38] fix(recovery): finish the passive recovery pass before restarting it (#20680) 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 > - The workspace recovery worker saves the files of failed runs. One passive pass of the worker visits holds with obligations: saved input that waits, cleanup, and due re-arms and fallbacks of exhausted holds > - #17741 restarts that pass after each committed workspace-recovery change, so new work is found quickly > - On staging, changes commit continuously (stop receipts, new holds, recovery progress). Every pass restarted from the first candidates, which are settled holds whose saved input waits behind another hold, and it never reached later candidates > - After #20295, #20569 and #20661 were deployed, no due re-arm ran: five stop-proof holds and about twenty capture-policy holds kept their exhausted state, with no marker and no activity > - This pull request restarts the pass only after it reaches its tail, and it continues an unfinished pass on the next run > - The benefit is that every candidate is visited on a busy instance, so the exhausted holds re-arm, save their files and free their tasks without an administrator ## Linked Issues or Issue Description Refs #17741 Refs #20295 Refs #20569 Refs #20661 **What happened?** Exhausted workspace holds were not re-armed on staging, even after the fixes that add their re-arm were deployed. Their recovery actions stayed unchanged for days (`updatedAt` on Nov 5 or Nov 10). No `stopProofRecovery` or `capturePolicyRecovery` marker and no `issue.workspace_recovery_rearmed` activity was recorded. The worker did process new restore holds, which are selected by its unfinished pass. **What did you expect to happen?** The worker's passive pass reaches every hold with a due re-arm or fallback, re-arms it, and saves the files. **Steps to reproduce** 1. Create several settled holds with saved user input that waits, with action ids that sort before an exhausted stop-proof hold. 2. Start the real workspace recovery worker. 3. Commit a workspace-recovery notification every 50 ms, as stop receipts and new holds do on a busy instance. 4. The worker never re-arms the exhausted hold. Without the notifications, it re-arms the hold. ## What Changed - `workspace-recovery-work.ts`: a committed change marks the passive pass for restart (`restart`). It no longer resets the cursor. While a restart is pending, an unfinished pass that made progress continues on the next run. - `workspace-recovery.ts`: when the passive cursor passes the last candidate and a restart is pending, the same run starts a fresh pass from the first candidate, so a new change is not delayed by another run interval. Without a pending restart the pass records `complete` and does not wrap, so paused input does not keep the worker active. - `doc/execution-semantics.md`: document that a pass is never restarted midway. - `workspace-recovery-stop-proof.test.ts`: add a real-worker regression in the staging shape (six earlier settled holds with waiting user input, one exhausted stop-proof hold, continuous notifications). ## Verification - Red: on master, the new test "re-arms the hold on a busy instance whose passive sweep keeps selecting earlier settled holds" fails (`stopProofRecovery` stays undefined). Control: the same test without the notifications passes on master. This shows that the restarts cause the starvation. - Green: with the fix, the test passes. These suites pass: `workspace-recovery-stop-proof` (12), `execution-control-work` (27), which includes "visits a newly committed earlier Retry during a busy recovered-source pass, then becomes quiet", plus `workspace-recovery-capture-policy`, `workspace-recovery-preparation-dispatch`, `workspace-recovery-warm-handoff`, `workspace-recovery-preparation` and `server-startup-feedback-export` (279). The timing-sensitive `heartbeat-observed-workspace-preservation` suite passed 6 of 6 runs (an earlier revision that restarted only on the next run made it flaky). - Staging evidence (read-only GET requests): the 28 exhausted holds of the company have no re-arm marker and no fallback check. Many blocked tasks with settled holds have deferred wakes. ## Risks - A change committed during a pass is now picked up at the next pass, not at once. Unfinished physical work still uses its own pass first, so new recoveries are not delayed. Saved input in a passive obligation can wait up to one full pass. - Previous-release story: no persisted state changes. Holds saved by earlier releases are selected on the first full pass after deploy, with no migration. - Quiet behavior stays: a completed pass with no new change keeps the worker idle. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell, code editing, browser GET reads) in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/execution-semantics.md | 5 +- .../workspace-recovery-stop-proof.test.ts | 73 ++++++++++++++++++- .../src/services/workspace-recovery-work.ts | 10 ++- server/src/services/workspace-recovery.ts | 13 +++- 4 files changed, 91 insertions(+), 10 deletions(-) diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index e683dead6d6..4e604ccd82b 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -3776,7 +3776,10 @@ infrastructure certification, and grants no agent or provider execution authorit Each completed export frees its own slot and wakes the next scan. A slow export does not hold a free slot. Completed cleanup and saved-input obligations receive one bounded pass through unvisited sources. The pass stops at its tail so paused -input does not keep the worker active; a committed change starts a fresh pass. +input does not keep the worker active; a committed change starts a fresh pass +once the current pass reaches its tail. A pass is never restarted midway, so on +a busy instance, where changes commit continuously, every candidate is still +visited: the due re-arms and fallbacks of older exhausted holds included. Shutdown joins this worker's exports before closing the database. Repeated Retry during physical preservation binds the canonical intent without changing the attempt's generation or revision. Progress writes preserve diff --git a/server/src/services/workspace-recovery-stop-proof.test.ts b/server/src/services/workspace-recovery-stop-proof.test.ts index e3ece5d881c..3546d1c845d 100644 --- a/server/src/services/workspace-recovery-stop-proof.test.ts +++ b/server/src/services/workspace-recovery-stop-proof.test.ts @@ -3,21 +3,25 @@ import { readFile } from "node:fs/promises"; import path from "node:path"; import { eq } from "drizzle-orm"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { activityLog, environmentLeases, executionWorkspaces, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations } from "@paperclipai/db"; +import { activityLog, agentWakeupRequests, environmentLeases, executionWorkspaces, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations } from "@paperclipai/db"; import type { AdapterSandboxExecutionTarget } from "@paperclipai/adapter-utils/execution-target"; import { readRemoteWorkspaceAuthority } from "@paperclipai/shared"; import { readRemoteWorkspaceWriterHold, remoteWorkspaceHoldRefusesStart } from "./remote-workspace-writer-hold.js"; import { readSystemRecovery } from "./system-recovery-state.js"; import { adoptSystemRecovery } from "./system-recovery.js"; -import { DELIVERY_QUEUES, subscribeDeliveryWork } from "./delivery-work-notifications.js"; +import { DELIVERY_QUEUES, notifyDeliveryWork, subscribeDeliveryWork } from "./delivery-work-notifications.js"; +import { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; +import { registerWorkspaceRecoveryWork } from "./workspace-recovery-work.js"; import { prepareSandboxStopAndRetain, settleStopOnlyCleanup } from "./sandbox-stop-and-retain.js"; import { nextWorkspaceRecoveryAt } from "./system-recovery.js"; import { RETAINED_SOURCE_FALLBACK_OUTCOME } from "./workspace-recovery-fallback.js"; import { readWorkspaceRecovery } from "./workspace-recovery-receipt.js"; -import { reconcileRetainedWorkspaces, recoverRetainedWorkspace, retainedWorkspaceCandidates } from "./workspace-recovery.js"; +import { reconcileRetainedWorkspaces, recoverRetainedWorkspace, retainedWorkspaceCandidates, type PassiveSweep } from "./workspace-recovery.js"; import { acceptedRemoteExport, action, connectionString, db, run, seed, useWorkspaceRecoveryFixture } from "./__tests__/workspace-recovery-fixture.js"; const targets = vi.hoisted(() => new Map()); +vi.mock("./execution-control-deadline.js", async importOriginal => ({ + ...await importOriginal(), EXECUTION_RECONCILIATION_INTERVAL_MS: 200 })); vi.mock("./environment-execution-target.js", async importOriginal => { const actual = await importOriginal(); return { ...actual, resolveEnvironmentExecutionTarget: async (input: Parameters[0]) => @@ -292,6 +296,69 @@ describe("exhausted stop-proof holds", () => { expect((await retainedWorkspaceCandidates(db, undefined, false, true)).map(row => row.action.id)).toContain(f.actionId); }, 60_000); + async function waitingSettledHold(id: string) { + const f = await seed("native", true); + settledRuns.set(id, f.runId); + await adoptSystemRecovery(db, f); + const prior = await action(f.actionId); + const system = readSystemRecovery(prior.evidence)!; + await db.update(issueRecoveryActions).set({ id, status: "resolved", outcome: "blocked", ownerType: "system", evidence: { ...prior.evidence, + systemRecovery: { ...system, state: "complete", phase: "reconcile_effects", attempts: 1 }, + workspaceRecovery: { schema: "paperclip.workspace-recovery.v1", runId: f.runId, status: "recovered", stage: "saving_receipts", + attempt: 1, attemptLimit: 6, retryable: false, requestIds: [] }, + automaticRecovery: { runId: f.runId, policy: "preserve_without_replay_v1", replay: "blocked" } } }) + .where(eq(issueRecoveryActions.id, f.actionId)); + const source = await run(f.runId); + await db.insert(agentWakeupRequests).values({ companyId: f.companyId, agentId: source.agentId, source: "on_demand", + reason: "issue_commented", status: "deferred_issue_execution", requestedByActorType: "user", requestedByActorId: "board", + payload: { issueId: f.issueId } }); + return f; + } + + const settledRuns = new Map(); + + it("restarts a finished passive pass when a change adds work both before and after its cursor", async () => { + const first = await waitingSettledHold("00000002-0000-4000-8000-000000000000"); + await waitingSettledHold("00000003-0000-4000-8000-000000000000"); + const visited: string[] = []; + const onRecovered = async (source: { id: string }) => { visited.push(source.id); }; + const sweep: PassiveSweep = {}; + for (let pass = 0; pass < 4 && !sweep.complete; pass += 1) + await Promise.all(await reconcileRetainedWorkspaces(db, first.environmentRuntime, onRecovered, true, undefined, sweep) ?? []); + expect(sweep.complete).toBe(true); + await waitingSettledHold("00000001-0000-4000-8000-000000000000"); + const f = await exhaustedStopProofHold(); + await db.update(issueRecoveryActions).set({ id: "ffffffff-0000-4000-8000-000000000000" }).where(eq(issueRecoveryActions.id, f.actionId)); + sweep.restart = true; + visited.length = 0; + await Promise.all(await reconcileRetainedWorkspaces(db, f.environmentRuntime, onRecovered, true, undefined, sweep) ?? []); + expect(sweep).toMatchObject({ complete: false, restart: true }); + for (let pass = 0; pass < 6 && !(sweep.complete && !sweep.restart && visited.includes(settledRuns.get("00000001-0000-4000-8000-000000000000")!)); pass += 1) + await Promise.all(await reconcileRetainedWorkspaces(db, f.environmentRuntime, onRecovered, true, undefined, sweep) ?? []); + expect(visited).toContain(settledRuns.get("00000001-0000-4000-8000-000000000000")); + expect((await action("ffffffff-0000-4000-8000-000000000000")).evidence.stopProofRecovery).toMatchObject({ rearms: 1 }); + }, 60_000); + + it("re-arms the hold on a busy instance whose passive sweep keeps selecting earlier settled holds", async () => { + for (const prefix of ["00000001", "00000002", "00000003", "00000004", "00000005", "00000006"]) + await waitingSettledHold(`${prefix}-0000-4000-8000-000000000000`); + const f = await exhaustedStopProofHold(); + const holdId = "ffffffff-0000-4000-8000-000000000000"; + await db.update(issueRecoveryActions).set({ id: holdId }).where(eq(issueRecoveryActions.id, f.actionId)); + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true, onError: vi.fn() }); + const worker = registerWorkspaceRecoveryWork(db, coordinator, f.environmentRuntime, async () => undefined); + const busy = setInterval(() => { void db.transaction(tx => notifyDeliveryWork(tx, DELIVERY_QUEUES.workspaceRecovery)).catch(() => undefined); }, 50); + try { + await worker.ready; + await vi.waitFor(async () => expect((await action(holdId)).evidence.stopProofRecovery).toMatchObject({ rearms: 1 }), + { timeout: 20_000, interval: 250 }); + } finally { + clearInterval(busy); + await worker.stop(); + await coordinator.stop(); + } + }, 60_000); + it("wakes the workspace recovery worker when a stop receipt is recorded", async () => { const f = await acceptedRemoteExport("retained"); const woken: string[] = []; diff --git a/server/src/services/workspace-recovery-work.ts b/server/src/services/workspace-recovery-work.ts index dea2bf28b46..279fa77cc00 100644 --- a/server/src/services/workspace-recovery-work.ts +++ b/server/src/services/workspace-recovery-work.ts @@ -3,7 +3,7 @@ import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator. import { DELIVERY_QUEUES } from "./delivery-work-notifications.js"; import { executionControlSchedule, registerExecutionControlWork } from "./execution-control-work.js"; import type { EnvironmentRuntimeService } from "./environment-runtime.js"; -import { reconcileRetainedWorkspaces } from "./workspace-recovery.js"; +import { reconcileRetainedWorkspaces, type PassiveSweep } from "./workspace-recovery.js"; export function registerWorkspaceRecoveryWork(db: Db, coordinator: ReturnType, runtime: EnvironmentRuntimeService, onRecovered: Parameters[2], @@ -12,15 +12,17 @@ export function registerWorkspaceRecoveryWork(db: Db, coordinator: ReturnType | undefined; let wakeWhileBusy = false; - let passiveSweep: { cursor?: string } = {}; + const passiveSweep: PassiveSweep = {}; const schedule = executionControlSchedule(db); const worker = registerExecutionControlWork(coordinator, [{ queue: DELIVERY_QUEUES.workspaceRecovery, - onSettled: () => { passiveSweep = {}; if (pending.size >= 2) wakeWhileBusy = true; }, + onSettled: () => { passiveSweep.restart = true; if (pending.size >= 2) wakeWhileBusy = true; }, run: () => scan = (async () => { + const sweep = passiveSweep, cursor = sweep.cursor; const work = await reconcileRetainedWorkspaces(db, runtime, onRecovered, true, continueSweep => { if (!stopped && (continueSweep || wakeWhileBusy)) { wakeWhileBusy = false; worker.wake(); } - }, passiveSweep); + }, sweep); + if (sweep.restart && !sweep.complete && sweep.cursor !== cursor && !stopped) worker.wake(); for (const job of work ?? []) { pending.add(job); const settled = () => { pending.delete(job); }; diff --git a/server/src/services/workspace-recovery.ts b/server/src/services/workspace-recovery.ts index 101af1e339d..6c8712a031a 100644 --- a/server/src/services/workspace-recovery.ts +++ b/server/src/services/workspace-recovery.ts @@ -644,11 +644,13 @@ export function retainedWorkspaceCandidates(db: Db, cursor?: string, unfinishedO )).orderBy(asc(issueRecoveryActions.id)).limit(5); } +export type PassiveSweep = { cursor?: string; complete?: boolean; restart?: boolean }; + /** Bounded discovery shares the periodic recovery lifecycle. A repaired source * still owes cleanup even without saved input or after task reconciliation. */ export async function reconcileRetainedWorkspaces(db: Db, runtime: EnvironmentRuntimeService, onRecovered: (run: typeof heartbeatRuns.$inferSelect) => Promise, obligationsOnly = false, - onFinished?: (continueSweep: boolean) => void, passiveSweep?: { cursor?: string }) { + onFinished?: (continueSweep: boolean) => void, passiveSweep?: PassiveSweep) { await adoptHistoricalWorkspaceRecoveries(db); let pending = workInFlight.get(db); if (!pending) { pending = new Set(); workInFlight.set(db, pending); } @@ -659,7 +661,14 @@ export async function reconcileRetainedWorkspaces(db: Db, runtime: EnvironmentRu let rows = await retainedWorkspaceCandidates(db, unfinishedCursors.get(db), true, false, inFlightRunIds); if (!rows.length) rows = await retainedWorkspaceCandidates(db, undefined, true, false, inFlightRunIds); const unfinished = rows.length > 0; - if (!rows.length) rows = await retainedWorkspaceCandidates(db, passiveSweep ? passiveSweep.cursor : cursors.get(db), false, obligationsOnly, inFlightRunIds); + if (!rows.length) { + rows = await retainedWorkspaceCandidates(db, passiveSweep ? passiveSweep.cursor : cursors.get(db), false, obligationsOnly, inFlightRunIds); + if (passiveSweep && !rows.length && passiveSweep.restart) { + Object.assign(passiveSweep, { cursor: undefined, restart: false }); + rows = await retainedWorkspaceCandidates(db, undefined, false, obligationsOnly, inFlightRunIds); + } + if (passiveSweep) passiveSweep.complete = !rows.length; + } if (!rows.length && !passiveSweep) rows = await retainedWorkspaceCandidates(db, undefined, false, obligationsOnly, inFlightRunIds); const work: Promise[] = []; let hasUnvisited = false; From a1ec05a1a4b81d7780e7156928c7a91d7dd73e1f Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:46:29 -0600 Subject: [PATCH 19/38] fix(native): read settled harness state again after a dropped sandbox connection (#20690) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Native Runner keeps one provider conversation across the per-turn runs of a task. After each turn, the controller reads the settled Runner and provider state out of the sandbox and saves it as the harness backup. > - A per-turn sandbox is released after the turn. The harness backup is then the only copy of the provider session. > - On staging, one dropped sandbox connection (`write ECONNRESET`) during that read lost the backup. The run itself succeeded, because its result was already accepted. > - The next run of the task could not resume the conversation: `PRP provider resume state is unavailable`. When the task was waiting for a reply, the run stopped at "Recovery needed" with no Retry. A person had to send a message to start a new conversation. > - This pull request reads the settled state again when the sandbox connection drops during that read. > - The benefit is that one network reset no longer loses a task's conversation. ## Linked Issues or Issue Description Refs #20627 (warm backup restore when the source sandbox is idle) and #20683 (relaunch of a settled runner). This PR changes a different step: the backup capture at the end of a turn. **What happened?** A per-turn OpenCode task ran on a remote Daytona sandbox with reuse disabled. 1. Run A accepted its result. The Runner suspended. 2. The controller read the settled state out of the sandbox. The read failed with `remote checkpoint failed: write ECONNRESET`. `harness_state.backup.persist` and `session.checkpoint.persist` failed. 3. Run A still finished as `succeeded`, because the result was durable. The sandbox was released. No harness backup of turn A existed. 4. Run B started in a new sandbox. It failed in 0.2 s with `native_session_recovery_failed: Error: PRP provider resume state is unavailable`. When the prior turn yielded for a reply, the checkpoint policy does not allow a replacement session, so the task showed "Recovery needed" with only inspect actions. On staging this happened on 4 tasks in 48 hours. In all 3 predecessor runs that I could inspect, the backup capture failed. 2 of them show the `ECONNRESET` in the run log. No deploy happened between run A and run B in one case, so a deploy is not the cause. **Expected behavior** A transient connection drop while reading settled state does not lose the provider conversation. The read is repeated, and the backup is saved. **Steps to reproduce** 1. Run the first durable turn of a remote OpenCode session. 2. Make the sandbox `syncOut` of the backup directories fail once with `ECONNRESET`. 3. Call the settled checkpoint. On `master` it throws `write ECONNRESET`, and no backup is saved. The new test `uses the bundled Linux image authority for remote opencode-new-durable-reset without controller overrides` runs these steps. **Paperclip version or commit** `master` at `7435abcc63`. ## What Changed - The settled-state capture (inspect plus `syncOut` of each persistence directory into a pending directory) is now one step that can repeat. The step writes nothing durable, so it is safe to repeat. - A dropped, reset or refused sandbox connection repeats the step, at most 3 attempts, with 1 s and 2 s delays. Each repeat clears the pending directory and inspects the live state again, so the copy always matches the inspected identity. - Any other failure fails at once, as before: a state mismatch, a missing directory, an unsafe archive, or a TLS failure. - The durable backup upload and the local publish run only after a complete capture. They did not change. - `isTransientRemoteCheckpointReadFailure` classifies the error with the existing `classifyRemoteConnectionError`, plus a message match for SDK errors that lose their `code`. - The first completeness inspection and its visibility-window re-reads use the same bounded retry (`retryTransientRemoteCheckpointRead`). A dropped provider-state read keeps its `provider_state_unreadable` refusal for every other caller, but the checkpoint retry looks through it to the dropped read. Undici `fetch failed` and `no response returned` also count as drops. ## Verification - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-session-executor.test.ts`: 1343 passed. - Red on `master`: the new `opencode-new-durable-reset` case fails with `Error: write ECONNRESET`. Green with this change. - The `isTransientRemoteCheckpointReadFailure` test checks that state mismatches, unsafe archives and TLS failures do not repeat. - `pnpm --filter @paperclipai/server typecheck` passes. ## Risks - Low risk. The normal path has no added wait. A repeat adds at most 3 s, and only after a connection failure. - A repeated read inspects the live state again. If the state changed between attempts, the existing identity checks still refuse it. - A connection that stays down for all 3 attempts fails the same way as before. > 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, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- .../native-session-executor.test.ts | 61 +++++++++- .../native-runtime/native-session-executor.ts | 104 +++++++++++++++--- 2 files changed, 145 insertions(+), 20 deletions(-) diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index b67247d57a4..dd961a60dc2 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -469,6 +469,9 @@ import { stageRemoteRunnerFile, steerNativeSession, syncRemoteRunnerDirectoryOut, + isTransientRemoteCheckpointReadFailure, + remoteProviderStateUnreadable, + retryTransientRemoteCheckpointRead, verifyNativeHarnessBackup, shouldRestoreNativeHarnessBackupIntoSandbox, } from "./native-session-executor.js"; @@ -2312,8 +2315,14 @@ describe("remote provider pack manifest", () => { return JSON.stringify(value); }; - it.each(["opencode", "opencode-new-durable", "opencode-continuation", "opencode-continuation-missing", "opencode-continuation-no-receipt", "opencode-continuation-replacement", "opencode-continuation-cold", "opencode-continuation-legacy-durable", "opencode-dirty", "opencode-diagnostics", "opencode-diagnostics-stale", "cursor", "claude-x64", "claude-arm64"] as const)("uses the bundled Linux image authority for remote %s without controller overrides", async provider => { - const firstDurable = provider === "opencode-new-durable"; + it.each(["opencode", "opencode-new-durable", "opencode-new-durable-reset", "opencode-new-durable-inspect-reset", "opencode-new-durable-provider-reset", "opencode-continuation", "opencode-continuation-missing", "opencode-continuation-no-receipt", "opencode-continuation-replacement", "opencode-continuation-cold", "opencode-continuation-legacy-durable", "opencode-dirty", "opencode-diagnostics", "opencode-diagnostics-stale", "cursor", "claude-x64", "claude-arm64"] as const)("uses the bundled Linux image authority for remote %s without controller overrides", async provider => { + const firstDurable = provider.startsWith("opencode-new-durable"); + // A sandbox connection drops once while the settled state is read out. + let checkpointReadResets = provider === "opencode-new-durable-reset" ? 1 : 0; + // Or while the checkpoint inspects the runner state, or reads the provider state, before any copy starts. + let inspectionResets = 0; + const inspectionReset = provider === "opencode-new-durable-inspect-reset" ? "runner-state.json" + : provider === "opencode-new-durable-provider-reset" ? "codex-provider-state.json" : null; const architecture = provider === "claude-arm64" ? "arm64" : "x64"; const claude = provider.startsWith("claude-"); const opencode = provider.startsWith("opencode"); @@ -2372,6 +2381,10 @@ describe("remote provider pack manifest", () => { const suspendedState = durableRunnerState({ runId: remoteExecution.binding.runId, runnerInstanceId: "bundled-image-runner", environmentLeaseId: "lease", normalizedSessionId: remoteExecution.session.normalizedSessionId }, "suspended"); const syncOut = vi.fn(async (operations: Array<{ files: Array<{ kind: string; targetPath: string }> }>) => { + if (checkpointReadResets > 0 && operations.some(operation => operation.files.some(file => file.targetPath.includes("/.pending-")))) { + checkpointReadResets--; + throw Object.assign(new Error("write ECONNRESET"), { code: "ECONNRESET" }); + } for (const operation of operations) for (const file of operation.files) { if (file.kind === "directory") { await mkdir(file.targetPath, { recursive: true }); @@ -2402,7 +2415,14 @@ describe("remote provider pack manifest", () => { }); onTestFinished(() => { storage.mockRestore(); owner.mockRestore(); validate.mockRestore(); retain.mockRestore(); capture.mockRestore(); backup.mockRestore(); }); } - const execute = vi.fn(async (command: { command: string; args?: string[] }) => ({ + const execute = vi.fn(async (command: { command: string; args?: string[] }) => { + const script = command.args?.[1] ?? ""; + if (inspectionResets > 0 && inspectionReset && script.includes("base64 <") && script.includes(inspectionReset) + && (inspectionReset === "runner-state.json" || !script.includes("runner-state.json"))) { + inspectionResets--; + throw Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" }); + } + return { exitCode: 0, signal: null, timedOut: false, stderr: "", stdout: command.args?.[0] === "--build-metadata" ? JSON.stringify({ schema: "paperclip-runner/runnerd-build-metadata/v1", binaryName: "paperclip-runnerd", @@ -2412,7 +2432,8 @@ describe("remote provider pack manifest", () => { }) : firstDurable && command.args?.[1]?.startsWith("const os=require") ? JSON.stringify({ home: "/home/runtime-account", uid: 1000 }) : firstDurable && command.args?.[1]?.includes("base64 <") ? Buffer.from(JSON.stringify(command.args[1].includes("codex-provider-state.json") && !command.args[1].includes("runner-state.json") ? providerState : suspendedState)).toString("base64") : "", - })); + }; + }); try { let coldAdmission: ReturnType = null; const prepare = createRunnerdBackend({ db: preparedDb, execution: remoteExecution, @@ -2492,8 +2513,11 @@ describe("remote provider pack manifest", () => { expect(exportSources.every(source => source.startsWith("/workspace/"))).toBe(true); expect(providerArtifactStorage.retainNativeProviderArtifacts).toHaveBeenCalledWith(expect.objectContaining({ owner: expect.objectContaining({ runId: remoteExecution.binding.runId }), source: expect.objectContaining({ manifest: installed, launchRoot, accountUid: 1000 }) })); + if (inspectionReset) inspectionResets = 1; await driver.mock.calls.at(-1)![0].checkpoint!("settled"); expect(harnessStorage.persistNativeHarnessBackup).toHaveBeenCalledTimes(1); + expect(checkpointReadResets).toBe(0); + expect(inspectionResets).toBe(0); return; } expect(execute.mock.calls.some(([call]) => call.args?.[0] === "-e" || call.args?.[0] === "--version")).toBe(false); @@ -21223,3 +21247,32 @@ describe("HTTP Stop during remote runner staging", () => { } finally { release(); await outcome; await stopping; await bundle.transport.detachControllerForRestart?.().catch(() => {}); await temporary.cleanup(); await rm(root, { recursive: true, force: true }); } }, 120000); }); + +describe("isTransientRemoteCheckpointReadFailure", () => { + it("repeats only a dropped sandbox connection, never a state or safety refusal", () => { + expect(isTransientRemoteCheckpointReadFailure(Object.assign(new Error("write ECONNRESET"), { code: "ECONNRESET" }))).toBe(true); + expect(isTransientRemoteCheckpointReadFailure(new Error("Daytona syncOut directory download failed: socket hang up"))).toBe(true); + expect(isTransientRemoteCheckpointReadFailure(new Error("runner_harness_state_mismatch: checkpoint_identity_incomplete"))).toBe(false); + expect(isTransientRemoteCheckpointReadFailure(new Error("Daytona syncOut refusing tarball member that escapes the extraction dir: ../x"))).toBe(false); + expect(isTransientRemoteCheckpointReadFailure(Object.assign(new Error("certificate expired"), { code: "CERT_HAS_EXPIRED" }))).toBe(false); + // A provider-state refusal is transient only when the read behind it dropped. + expect(isTransientRemoteCheckpointReadFailure(remoteProviderStateUnreadable(Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" })))).toBe(true); + expect(isTransientRemoteCheckpointReadFailure(remoteProviderStateUnreadable(new Error("runner_remote_provider_state_unavailable")))).toBe(false); + expect(isTransientRemoteCheckpointReadFailure(remoteProviderStateUnreadable(new SyntaxError("Unexpected token")))).toBe(false); + expect(remoteProviderStateUnreadable(new Error("read ECONNRESET")).message).toBe("runner_harness_state_mismatch: provider_state_unreadable"); + }); + + it("stops after three reads, and never repeats a refusal", async () => { + const reset = () => Object.assign(new Error("read ECONNRESET"), { code: "ECONNRESET" }); + const onRetry = vi.fn(); + const dropping = vi.fn(async () => { throw reset(); }); + await expect(retryTransientRemoteCheckpointRead(dropping, onRetry, 0)).rejects.toThrow("read ECONNRESET"); + expect(dropping).toHaveBeenCalledTimes(3); + expect(onRetry.mock.calls).toEqual([[1, 3], [2, 3]]); + const refusing = vi.fn(async () => { throw new Error("runner_harness_state_mismatch: runner_identity"); }); + await expect(retryTransientRemoteCheckpointRead(refusing, vi.fn(), 0)).rejects.toThrow("runner_identity"); + expect(refusing).toHaveBeenCalledTimes(1); + let drops = 2; + await expect(retryTransientRemoteCheckpointRead(async () => { if (drops-- > 0) throw reset(); return "settled"; }, vi.fn(), 0)).resolves.toBe("settled"); + }); +}); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index fb5c533b658..cc2d29953b0 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -295,6 +295,7 @@ import { } from "./status-arbiter.js"; import { conflict, HttpError } from "../../errors.js"; import { redactSensitiveText } from "../../redaction.js"; +import { classifyRemoteConnectionError } from "../remote-connection-failure.js"; import { resolvePaperclipRunnerBinary, resolveRemotePaperclipRunnerBinary } from "./native-codex-runner.js"; import { createNativeRunTrace, @@ -13735,6 +13736,55 @@ function assertSafeExtractedCheckpoint(root: string): void { } } +const REMOTE_CHECKPOINT_CAPTURE_ATTEMPTS = 3; +const REMOTE_CHECKPOINT_CAPTURE_RETRY_MS = 1_000; +const TRANSIENT_REMOTE_READ_MESSAGE = /\b(?:ECONNRESET|EPIPE|ETIMEDOUT|ECONNREFUSED|socket hang up|fetch failed|no response returned)\b/; +/** `provider_state_unreadable` refusals whose underlying read was a dropped + * connection. The refusal keeps its message for every other caller; only the + * checkpoint read retry looks through it. */ +const providerStateReadTransportFailures = new WeakMap(); + +/** A dropped or refused sandbox connection while reading settled state. A + * mismatch, a missing directory or an unsafe archive is never transient. */ +export function isTransientRemoteCheckpointReadFailure(error: unknown): boolean { + if (error instanceof Error && providerStateReadTransportFailures.has(error)) { + return isTransientRemoteCheckpointReadFailure(providerStateReadTransportFailures.get(error)); + } + const reason = classifyRemoteConnectionError(error); + if (reason !== null) return reason !== "tls_failure"; + return error instanceof Error && !error.message.startsWith("runner_") + && TRANSIENT_REMOTE_READ_MESSAGE.test(error.message); +} + +/** The refusal `inspectRemoteHarnessState` throws when the provider state + * cannot be read, remembering the read failure behind it. */ +export function remoteProviderStateUnreadable(readFailure: unknown): Error { + const refusal = new Error("runner_harness_state_mismatch: provider_state_unreadable"); + providerStateReadTransportFailures.set(refusal, readFailure); + return refusal; +} + +/** + * Repeats a read of settled state out of the sandbox after a dropped + * connection, at most {@link REMOTE_CHECKPOINT_CAPTURE_ATTEMPTS} times in all. + * Any other failure, and the last transient one, is thrown unchanged. + */ +export async function retryTransientRemoteCheckpointRead( + read: () => Promise, + onRetry: (attempt: number, attempts: number) => Promise | void, + retryDelayMs = REMOTE_CHECKPOINT_CAPTURE_RETRY_MS, +): Promise { + for (let attempt = 1; ; attempt++) { + try { + return await read(); + } catch (error) { + if (attempt >= REMOTE_CHECKPOINT_CAPTURE_ATTEMPTS || !isTransientRemoteCheckpointReadFailure(error)) throw error; + await onRetry(attempt, REMOTE_CHECKPOINT_CAPTURE_ATTEMPTS); + await new Promise((resolveDelay) => setTimeout(resolveDelay, retryDelayMs * attempt)); + } + } +} + /** * Copy a remote runner directory into durable local state. * @@ -15754,8 +15804,8 @@ async function createRunnerdBackendWithinSessionClaim( stateDirectory: remoteStateDirectory, execution: input.execution, }); - } catch { - throw new Error("runner_harness_state_mismatch: provider_state_unreadable"); + } catch (error) { + throw remoteProviderStateUnreadable(error); } const providerSessionIdentity = providerSessionIdentityFromDurableProviderState({ @@ -16301,14 +16351,23 @@ async function createRunnerdBackendWithinSessionClaim( // `runner_harness_state_mismatch`. Only checkpoint a harness that runnerd // has proved complete. A malformed or identity-conflicting state still // throws from inspectRemoteHarnessState and therefore fails closed. - let checkpointable = await measureNativeRunnerSpan(input.trace, "harness_state.inspect", () => inspectRemoteHarnessState()); + // A dropped sandbox connection repeats the read (bounded) instead of + // losing the only backup of the provider session. + const inspectForCheckpoint = () => retryTransientRemoteCheckpointRead( + () => measureNativeRunnerSpan(input.trace, "harness_state.inspect", () => inspectRemoteHarnessState()), + (attempt, attempts) => input.onLog?.( + "stderr", + `[paperclip-runner] remote checkpoint inspection interrupted (attempt ${attempt} of ${attempts}); reading the settled state again\n`, + ), + ); + let checkpointable = await inspectForCheckpoint(); // The remote runner writes its suspended lifecycle and provider state // before the outer process-owner RPC necessarily observes completion. // Allow a very small bounded visibility window without ever accepting an // active, incomplete, malformed, or identity-conflicting checkpoint. for (let attempt = 1; !checkpointable.complete && attempt < 3; attempt++) { await new Promise((resolve) => setTimeout(resolve, 100)); - checkpointable = await measureNativeRunnerSpan(input.trace, "harness_state.inspect", () => inspectRemoteHarnessState()); + checkpointable = await inspectForCheckpoint(); } if (!checkpointable.complete) { const incompleteFailure = remoteCheckpointIncompleteFailure( @@ -16338,24 +16397,27 @@ async function createRunnerdBackendWithinSessionClaim( input.trace, "harness_state.backup.persist", async () => { - const verified = await measureNativeRunnerSpan(input.trace, "harness_state.inspect", () => inspectRemoteHarnessState()); - if ( - !verified.complete || - !verified.runnerState || - !verified.providerSessionIdentity - ) { - throw new Error("runner_harness_state_mismatch: checkpoint_identity_incomplete"); - } - const providerSessionIdentity = verified.providerSessionIdentity; - const backupRoot = harnessBackupRoot(root); mkdirSync(backupRoot, { recursive: true, mode: 0o700 }); const pendingRoot = resolve( backupRoot, `.pending-${randomUUID()}`, ); - mkdirSync(pendingRoot, { recursive: true, mode: 0o700 }); - try { + // Reading the settled state out of the sandbox writes nothing + // durable, so a dropped sandbox connection can repeat the whole + // read. Without this, one reset loses the only copy of the + // provider session when the per-turn sandbox is released. + const captureSettledState = async () => { + rmSync(pendingRoot, { recursive: true, force: true }); + const verified = await measureNativeRunnerSpan(input.trace, "harness_state.inspect", () => inspectRemoteHarnessState()); + if ( + !verified.complete || + !verified.runnerState || + !verified.providerSessionIdentity + ) { + throw new Error("runner_harness_state_mismatch: checkpoint_identity_incomplete"); + } + mkdirSync(pendingRoot, { recursive: true, mode: 0o700 }); for (const directory of persistenceProfile.directories) { const sourcePath = remotePersistencePath(directory); if (!sourcePath) @@ -16372,6 +16434,16 @@ async function createRunnerdBackendWithinSessionClaim( throw new Error("runner_harness_state_mismatch: checkpoint_directory_missing"); } } + return verified.providerSessionIdentity; + }; + try { + const providerSessionIdentity = await retryTransientRemoteCheckpointRead( + captureSettledState, + (attempt, attempts) => input.onLog?.( + "stderr", + `[paperclip-runner] remote checkpoint read interrupted (attempt ${attempt} of ${attempts}); reading the settled state again\n`, + ), + ); const manifest = buildNativeHarnessBackupManifest({ backupRoot: pendingRoot, execution: input.execution, From 8c0dbffa704b4d0cb4fd7acee7be906ea11692ea Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:54:53 -0600 Subject: [PATCH 20/38] fix(heartbeat): retry a legacy run whose lease this process lost before dispatch (#20694) 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 > - The heartbeat orphan reaper settles legacy (non-native) runs that lost their controller lease > - #16355 taught the reaper to retry a legacy run that a restart stopped while setup was still `preparing`, because revocation fences the old controller and `preparing` proves no adapter dispatch > - That proof was applied only when the lapsed lease belonged to a different boot > - A stall can make the current process lose its own lease while setup is still `preparing`, and its executor can end without settling the row > - The reaper then wrote "retrying once" but recorded no bootstrap evidence, so the retry was refused and the task was blocked for reconciliation > - This pull request applies the same revocation proof to a lease from the current boot > - The benefit is that these tasks recover by themselves instead of waiting for a person to press Retry ## Linked Issues or Issue Description Refs #16355 **What happened?** On a hosted instance, one server process stalled for about 100 seconds (lease renewals were 42–46 s late). Several legacy `paperclip_runner` runs on a remote sandbox were still in setup (`executionStage: "preparing"`, no process id). Their controller leases expired. Some executors settled their own runs as `controller_lease_lost`. Two runs had no executor left, so the orphan reaper of the same process settled them 4 minutes later. Each run got `error: "Process lost -- server may have restarted; retrying once"` and `processLossDiagnostic.retryEligible: true`, but no `executionRecovery` evidence. `enqueueProcessLossRetry` then saw a run that needs reconciliation and scheduled nothing. The next sweep recorded `legacy_execution_requires_reconciliation` with `preserve_without_replay_v1`, and both tasks stayed `blocked` until a person pressed Retry. **Expected behavior** Revocation commits the stage. Renewal requires the old boot id, so no controller can move a revoked run to `dispatching`. A revoked run that is still `preparing` with no process identity did no provider work, whichever boot owned the lease. The reaper should record the bootstrap evidence and use the bounded retry. **Steps to reproduce** 1. Claim a legacy run in this process: `controllerBootId` is the current boot, `executionStage: "preparing"`, no process id. 2. Let its controller lease expire with no local executor (for example after an event-loop or database stall). 3. Run the orphan reaper. 4. Before this change: `process_lost; retrying once`, no `executionRecovery`, no retry, and a reconciliation hold. After this change: bootstrap evidence and a `scheduled_retry` successor. ## What Changed - `server/src/services/heartbeat/recovery.ts`: `restartInterruptedBeforeDispatch` no longer requires the lease to come from another boot. The other clauses stay: legacy runtime, a stamped controller boot id, and `preparing` with no process id or group in the state committed by the revocation. Locally tracked runs and runs with a live lease are still skipped before this point. - `server/src/__tests__/heartbeat-process-recovery.test.ts`: two cases in the hosted shape (assignment wake and due-monitor wake, `paperclip_runner`, prepared remote workspace, same-boot expired lease, `preparing`). They expect bootstrap evidence, a scheduled retry, no recovery hold after a second sweep, and no adapter call. A control case keeps a same-boot `dispatching` run held for reconciliation. ## Verification - Red on `origin/master` (source change reverted): both new cases fail. The monitor case shows the exact hosted shape: `retryEligible: true` with no `executionRecovery`. - Green with the change: `pnpm --filter @paperclipai/server exec vitest run src/__tests__/heartbeat-process-recovery.test.ts -t "lease this process lost|this process dispatched held|restart stopped before adapter dispatch|reached adapter dispatch held|lost monitor|older build without a controller stamp|failure budget"` (10 passed). - Related files, run together: `heartbeat-process-recovery`, `live-recovery-work`, `interrupted-preparation-hold-settle`, `resource-wait-stop`, `legacy-controller-lease`, `execution-recovery-dead-controller`, `legacy-process-settlement`, `run-failure-report` (876 passed; 2 timing failures under load in unrelated setup-failure tests, both pass when run alone). - `pnpm --filter @paperclipai/server exec tsc --noEmit` passes. ## Risks - Low risk. The proof is the one #16355 already relies on across boots: the revocation compare-and-set replaces the boot id, so the in-memory controller of this process also fails its next renewal and cannot dispatch. - A same-boot run reaches this code only when it is not in `activeRunExecutions` or `runningProcesses` and its lease expired. If an executor is stalled before it registers, it aborts at its first renewal. Setup work can run again in the retry; provider work cannot. - Upgrade safety: no persisted shape changes. The reaper reads the same fields (`executionStage`, `controllerBootId`, process ids) that older releases write. Runs that older code already parked keep their hold and their working Retry. - Runs that reached `dispatching`, recorded a process, or have no controller stamp keep the current behavior. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used through Claude Code with tool use, shell, and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes (the code comment carries the contract) - [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 --- .../heartbeat-process-recovery.test.ts | 64 +++++++++++++++++++ server/src/services/heartbeat/recovery.ts | 5 +- 2 files changed, 66 insertions(+), 3 deletions(-) diff --git a/server/src/__tests__/heartbeat-process-recovery.test.ts b/server/src/__tests__/heartbeat-process-recovery.test.ts index 74a0803bf67..559d9890075 100644 --- a/server/src/__tests__/heartbeat-process-recovery.test.ts +++ b/server/src/__tests__/heartbeat-process-recovery.test.ts @@ -3557,6 +3557,70 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => { expect(mockAdapterExecute).not.toHaveBeenCalled(); }); + it.each([ + ["an assignment", {}], + ["a due monitor", { wakeReason: "issue_monitor_due" }], + ] as const)("retries %s run whose lease this process lost before adapter dispatch", async (_label, contextSnapshot) => { + const { companyId, runId, issueId } = await seedRunFixture({ + adapterType: "paperclip_runner", agentStatus: "idle", runtimeMode: "legacy", contextSnapshot, + }); + await db.update(heartbeatRuns).set({ + controllerBootId: controllerLeases.legacyControllerBootId, + controllerProcess: currentControllerProcessStamp(), + controllerLeaseExpiresAt: sql`clock_timestamp() - interval '1 second'`, + executionStage: "preparing", + runnerProfileJson: { + adapterDispatch: { adapterType: "paperclip_runner" }, + remoteWorkspace: { schema: "paperclip.remote-workspace-run.v1", epoch: 6, state: "prepared", + leaseId: randomUUID(), providerLeaseId: randomUUID(), workspaceId: randomUUID(), + remoteCwd: "/home/daytona/paperclip-workspace", snapshotId: randomUUID() }, + }, + }).where(eq(heartbeatRuns.id, runId)); + + const heartbeat = heartbeatService(db); + expect(await heartbeat.reapOrphanedRuns()).toEqual({ reaped: 1, runIds: [runId] }); + + const [reaped] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(reaped).toMatchObject({ status: "failed", errorCode: "process_lost", + error: "Process lost -- server may have restarted; retrying once" }); + expect(reaped?.resultJson).toMatchObject({ + executionRecovery: { kind: "bootstrap", providerWorkStarted: false }, + processLossDiagnostic: { localCheck: "no_identifiers", retryEligible: true }, + }); + expect(await db.select().from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.retryOfRunId, runId), + ))).toEqual([expect.objectContaining({ status: "scheduled_retry" })]); + await heartbeat.reapOrphanedRuns(); + expect(await db.select().from(issueRecoveryActions) + .where(eq(issueRecoveryActions.sourceIssueId, issueId))).toEqual([]); + expect(mockAdapterExecute).not.toHaveBeenCalled(); + }); + + it("keeps a run this process dispatched held for reconciliation after its lease lapses", async () => { + const { companyId, runId, issueId } = await seedRunFixture({ + adapterType: "paperclip_runner", agentStatus: "idle", runtimeMode: "legacy", + }); + await db.update(heartbeatRuns).set({ + controllerBootId: controllerLeases.legacyControllerBootId, + controllerProcess: currentControllerProcessStamp(), + controllerLeaseExpiresAt: sql`clock_timestamp() - interval '1 second'`, + executionStage: "dispatching", + }).where(eq(heartbeatRuns.id, runId)); + + await heartbeatService(db).reapOrphanedRuns(); + + const [reaped] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(reaped).toMatchObject({ status: "failed", errorCode: "process_lost" }); + expect(reaped?.resultJson).not.toHaveProperty("executionRecovery"); + expect(await db.select().from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.retryOfRunId, runId), + ))).toEqual([]); + expect(await db.select().from(issueRecoveryActions) + .where(eq(issueRecoveryActions.sourceIssueId, issueId))).toEqual([ + expect.objectContaining({ cause: "legacy_execution_requires_reconciliation" }), + ]); + }); + it("keeps a lost preparation from an older build without a controller stamp in the charged lane", async () => { const { companyId, runId } = await seedRestartOrphanedLegacySetup("preparing"); await db.update(heartbeatRuns).set({ runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner" } } }) diff --git a/server/src/services/heartbeat/recovery.ts b/server/src/services/heartbeat/recovery.ts index b6482a6bc92..f6ea8aa8dae 100644 --- a/server/src/services/heartbeat/recovery.ts +++ b/server/src/services/heartbeat/recovery.ts @@ -2660,8 +2660,8 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD continue; } // A legacy controller persists "dispatching" in the same lease renewal - // that admits the adapter. An expired lease from another boot that is - // still "preparing" proves a restart stopped setup before provider work. + // that admits the adapter. An expired lease that is still "preparing" + // proves setup stopped before provider work. // Use the state committed with the revocation, not the earlier snapshot: // the old controller may have dispatched before its lease expired. // The revocation matched the snapshot's boot ID before replacing it. @@ -2669,7 +2669,6 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD run.runtimeMode === "legacy" && revokedState.executionStage === "preparing" && !!run.controllerBootId && - run.controllerBootId !== legacyControllerBootId && !revokedState.processPid && !revokedState.processGroupId; const shouldRetry = From a46b9ac7242b9ddcb8db8159be489742a725e9cb Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:57:03 -0600 Subject: [PATCH 21/38] fix(native): wait out an ACP usage limit's reported reset, then Retry the task (#20692) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Native runs (Paperclip Runner with an ACP harness, such as Claude) can stop because the provider account runs out of its usage allowance > - The ACP harness reports this as a "terminal limit failure". Paperclip blocked the task behind a board hold that called the session state ambiguous, and the only way forward was a manual Retry > - The provider also says when the limit resets, for example "resets Nov 12, 6pm (UTC)" for a weekly limit. Paperclip read only clock-only resets ("resets 2am"), so the agent-level wait fell back to one hour. Each later wake for the agent then hit the limit again and blocked another task > - This pull request reads calendar resets, says on the hold when the limit resets, and requests the task's Retry itself at that time when the reset is reported and bounded > - The benefit is that a usage limit no longer needs a person to click Retry, and the agent's other tasks wait instead of failing one by one ## Linked Issues or Issue Description **What happened?** A native ACP run failed with `native_provider_usage_limit` ("ACP agent reported a terminal limit failure. You've hit your weekly limit · resets Nov 12, 6pm (UTC)"). The task went to `blocked` with a board-owned hold. The hold said "Inspect the original provider failure and explicitly resolve the ambiguous session state". Nothing resumed the task after the reset. The agent-level `provider_limit_wait` recorded "no reset time was reported, so Paperclip waits one hour", so every hour another wake dispatched, hit the limit, and blocked another task. In one 48-hour window on a staging instance, this blocked 7 tasks for one agent. **What did you expect?** When the provider reports a bounded reset, the task waits and continues after the reset, like the existing `provider_limit_wait` path. When the reset is unknown, the task fails with a clear message and a working Retry. **Steps to reproduce** 1. Run a native ACP agent until its provider reports a weekly or session limit with a reset time. 2. Look at the task: it is blocked with an "ambiguous session state" hold. 3. Wait past the reported reset: the task stays blocked until a person clicks Retry. Refs #20666 (other recovery work in the same staging census; not changed here) ## What Changed - `provider-quota-reset.ts`: parse calendar resets such as "resets Nov 12, 6pm (UTC)", "resets Jul 17th at 4:30 PM (America/Chicago)" and "Resets on August 2, 9am (UTC)". A past date rolls into next year. An impossible date (Nov 31) is refused. Clock-only parsing is unchanged. This also fixes the agent-level `provider_limit_wait` reset and the legacy `provider_quota` reset for these messages. - New `native-runtime/provider-limit-resume.ts`: - `readNativeUsageLimitReset` reads the reset only from the run's own durable events. The last turn event must be a provider-observed `turn.failed` with a `rate_limit` or `quota_exhausted` provider failure, and the reset must be at most eight days out. - `requestProviderLimitResumeRetry` asks for the task's Retry (`requestTaskRetry`, `initiatedBy: "provider_limit_reset"`) on behalf of the user who requested the run, or the run's accountable user for automatic wakes. It is idempotent per run and records its outcome on the hold. At most three automatic Retries follow one another without a successful run. - `registerProviderLimitResumeWork` is a scoped deadline owner (shared work scheduler, no polling). Each active usage-limit hold is due at its reset. Startup rebuilds it from the holds, and the executor notifies it in the hold's transaction. - `native-session-executor.ts`: for a terminal usage limit, the hold and run failure detail say when the limit resets and whether Paperclip retries then, instead of "ambiguous session state". The evidence records `providerLimitResetAt`. - `task-retry.ts`: accept `initiatedBy: "provider_limit_reset"`. Its activity is recorded as system actor `provider-limit-reset` on behalf of the user, like `restart_recovery`. - `doc/execution-semantics.md`: document the wait and its limits. Previous-release story: holds saved by the previous release carry forward. At startup the owner reads each active `native_provider_usage_limit` hold. It rewrites the hold's message with the reset when the reset is known and still ahead, and it requests the Retry at the reset. Holds whose reset is unknown, more than a day in the past, or that have no accountable user keep their Retry and are recorded as not requested, so they are not read again. ## Verification - `npx vitest run server/src/services/provider-quota-reset.test.ts` — 4 tests. Three fail on `origin/master` code (calendar resets return `null`), all pass with this change. - `npx vitest run server/src/services/native-runtime/native-provider-capacity.integration.test.ts` — 5 tests on embedded Postgres: - the existing usage-terminal test (both replay modes) still blocks with a Retry, and no automatic Retry is requested without a reported reset; - "waits for a reported usage-limit reset and then requests the task's Retry once": the hold says when the limit resets, an old-release hold is rewritten, nothing starts before the reset, one Retry receipt is created for the accountable user at the reset, and a second pass does nothing. Fails on `origin/master` executor code; - "starts the Retry from the hold's own deadline": a real delivery coordinator rebuilds the deadline from the hold and calls Retry dispatch once, after the reset; - "leaves a visible Retry when no user is accountable for the run". Fails on `origin/master` executor code. - Focused regression suites pass (642 tests): `task-retry`, `quarantined-task-retry`, `heartbeat-native-restart-suspension`, `native-startup-retry.integration`, `provider-failure-classification`, `heartbeat-provider-limit-wait`, `deferred-execution-receipt-work`, `chat-run-publications`, `native-runner-restart-recovery.integration`, `native-remote-retry-admission`. - `pnpm --filter @paperclipai/server exec tsc --noEmit` passes. - `pnpm verify` selected a broad run (exit 2, because the docs file is a global CI input). CI supplies the broad coverage. ## Risks - The automatic Retry uses the accountable user's authority for automatic (system) wakes. It is the same Retry the hold already offered that user, and dispatch still checks Retry authority, stop proof, saved work and action reconciliation. It is never broader than a click. - A provider that keeps reporting resets that do not restore capacity gets at most three automatic Retries in a row; then the Retry stays visible. - The deadline owner reads all active usage-limit holds at startup (limit 500 rows). The number of such holds is small. - Not changed: the agent-level wait still holds new wakes for at most one day, as before. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits, read-only staging API reads). Extended reasoning enabled. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- doc/execution-semantics.md | 21 +- .../server-startup-feedback-export.test.ts | 8 + server/src/index.ts | 7 +- .../services/delivery-work-notifications.ts | 1 + server/src/services/heartbeat.ts | 8 + .../heartbeat/restart-interrupted-turn.ts | 6 +- ...tive-provider-capacity.integration.test.ts | 662 +++++++++++++----- .../native-runtime/native-session-executor.ts | 25 +- .../native-runtime/provider-limit-resume.ts | 284 ++++++++ .../src/services/provider-quota-reset.test.ts | 43 ++ server/src/services/provider-quota-reset.ts | 77 +- .../provider-failure-classification.test.ts | 11 + server/src/services/recovery/service.ts | 3 +- server/src/services/task-retry.ts | 28 +- 14 files changed, 945 insertions(+), 239 deletions(-) create mode 100644 server/src/services/native-runtime/provider-limit-resume.ts create mode 100644 server/src/services/provider-quota-reset.test.ts diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 4e604ccd82b..6c2c318e36b 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -3062,9 +3062,28 @@ account at once. ACP harnesses report an exhausted allowance as a generic terminal limit failure; Runner adds the provider's typed session-failure title, and only a rate-limit or quota title becomes `rate_limit` or `quota_exhausted`. Context, turn and configured budget limits stay ordinary terminal failures. A -reset clock in the provider's wording, such as "resets 2am (UTC)", is used as +reset clock in the provider's wording, such as "resets 2am (UTC)", or a +calendar reset such as a weekly limit's "resets Nov 12, 6pm (UTC)", is used as the reset time. +A native run whose provider ends a turn with an exhausted allowance +(`native_provider_usage_limit`) still blocks its task with a recovery action. +When the run's last turn event is a provider-observed `turn.failed` that reports +a reset within eight days, the action says when the limit resets, and at that +time Paperclip requests the task's Retry itself, on behalf of the user who +requested the run or, for automatic wakes, the run's accountable user. That is +the same Retry the user would click: admission keeps every gate (stop proof, +saved-work recovery and action reconciliation), so it never starts work a +user's Retry could not. The request is idempotent per run, and at most three +automatic Retries follow one another without a successful run between them. +A hold whose reset is more than eight days out (for example a monthly limit) +still names its reset but leaves the Retry to the user. A hold whose reset is +unknown, more than a day in the past, or that has no accountable user keeps its +visible Retry, and its message says why. A connected chat conversation's Retry +is prepared through the chat service, as a user's is. The +reset deadline is rebuilt from the active holds at startup, so holds saved by an +earlier release are covered too. + An ingress endpoint failure can use that same bounded retry only when the environment provider returns a structured HTTP 429 or 5xx failure and the complete, encrypted controller checkpoint proves that this exact run never diff --git a/server/src/__tests__/server-startup-feedback-export.test.ts b/server/src/__tests__/server-startup-feedback-export.test.ts index 944eb1dcc49..b7067d220fc 100644 --- a/server/src/__tests__/server-startup-feedback-export.test.ts +++ b/server/src/__tests__/server-startup-feedback-export.test.ts @@ -159,6 +159,7 @@ const { registerIssueStateRecoveryWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve(), watchdogs: { reconciliationSnapshot: () => ({ revision: "startup-watchdogs:1", reconciled: true }), stop: vi.fn(async () => {}) } })), registerDeferredReceiptWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve() })), + registerProviderLimitResumeWork: vi.fn((_coordinator: unknown, _canRun: () => boolean, _prepareChatRetry?: () => unknown) => ({ ready: Promise.resolve() })), registerRunDispatchWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve(), retries: { reconciliationSnapshot: () => ({ revision: "startup-retries:1", reconciled: true }), stop: vi.fn(async () => {}) } })), registerScheduledRetryCancellationWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve() })), @@ -1048,7 +1049,14 @@ describe("startServer feedback export wiring", () => { expect(heartbeatServiceMock.registerActiveRunSilenceWork).toHaveBeenCalledTimes(enabled ? 1 : 0); expect(heartbeatServiceMock.registerRunDispatchWork).toHaveBeenCalledTimes(enabled ? 1 : 0); expect(heartbeatServiceMock.registerDeferredReceiptWork).toHaveBeenCalledTimes(enabled ? 1 : 0); + expect(heartbeatServiceMock.registerProviderLimitResumeWork).toHaveBeenCalledTimes(enabled ? 1 : 0); expect(heartbeatServiceMock.resumeQueuedRuns).not.toHaveBeenCalled(); + if (enabled) { + const [limitCoordinator, limitAdmitted, chatRetry] = heartbeatServiceMock.registerProviderLimitResumeWork.mock.calls[0]; + expect(limitCoordinator).toBe((await createAppMock.mock.results.at(-1)!.value).locals.deliveryWork); + expect(limitAdmitted()).toBe(true); + expect(typeof chatRetry).toBe("function"); + } if (enabled) { const [coordinator, admitted] = heartbeatServiceMock.registerRunDispatchWork.mock.calls[0]; const app = await createAppMock.mock.results.at(-1)!.value; diff --git a/server/src/index.ts b/server/src/index.ts index 8e785370055..dfa92d5a9ad 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -951,7 +951,8 @@ async function startServerWithDatabaseTeardown( logger.warn({ scope: cloudQualification.scope, blockerCodes: cloudQualification.blockers.map((blocker) => blocker.code) }, "Cloud configuration and package qualification has blockers"); } const idleDeadlineOwners: IdleDeadlineOwners = {}; - // createApp fills the chat Retry callback; the continuation worker reads it. + // createApp fills the chat Retry callback; the continuation and + // provider-limit Retry workers read it. const budgetResumeDelivery: BudgetResumeDelivery = {}; const app = await createApp(db as any, { idleDeadlineOwners, @@ -1771,6 +1772,10 @@ async function startServerWithDatabaseTeardown( } if (config.heartbeatSchedulerEnabled) await heartbeat.registerDeferredReceiptWork(deliveryWork, () => !isIdleTaskDrainActive() && !isWarmStandby() && !heartbeatSchedulerStopped).ready; + // A connected conversation's Retry needs the chat callback createApp registered. + if (config.heartbeatSchedulerEnabled) await heartbeat.registerProviderLimitResumeWork(deliveryWork, + () => !isIdleTaskDrainActive() && !isWarmStandby() && !heartbeatSchedulerStopped, + () => budgetResumeDelivery.prepareChatRetry).ready; if (config.heartbeatSchedulerEnabled) { const work = heartbeat.registerRunDispatchWork(deliveryWork, () => !isIdleTaskDrainActive() && !isWarmStandby() && !heartbeatSchedulerStopped); diff --git a/server/src/services/delivery-work-notifications.ts b/server/src/services/delivery-work-notifications.ts index c8ecc5a9ba6..cd0da16ca72 100644 --- a/server/src/services/delivery-work-notifications.ts +++ b/server/src/services/delivery-work-notifications.ts @@ -58,6 +58,7 @@ export const DELIVERY_QUEUES = { scheduledRetryCancellation: "scheduled-retry-cancellation", executionFinalization: "execution-finalization", workspaceRecovery: "workspace-recovery", + providerLimitResume: "provider-limit-resume", executionReplacement: "execution-replacement", executionContinuation: "execution-continuation", executionStatus: "execution-status", diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 7724e412126..baaaace2ea1 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -9,6 +9,7 @@ import { isContextCompactionRun } from "./context-compaction.js"; import { isUnstartedTaskQuestionAnswer } from "./unstarted-task-question-answer.js"; import { isVerifiedDependencyInteractionResponse } from "./queued-interaction-response.js"; import { registerDeferredReceiptWork } from "./heartbeat/deferred-receipt-work.js"; +import { registerProviderLimitResumeWork, type PrepareChatRetry } from "./native-runtime/provider-limit-resume.js"; import { reconcileTaskChatRetryReceipts } from "./task-retry.js"; import { registerIssueRecoveryWork } from "./recovery/work.js"; import { registerRunDispatchWork } from "./heartbeat/dispatch-work.js"; @@ -4522,6 +4523,13 @@ export function heartbeatService( }, }, () => canRun() && readTaskDrain(new Date()) === null), readIdleWatchdogSchedule: taskWatchdogs.readIdleSchedule, + registerProviderLimitResumeWork: (coordinator: Parameters[1], canRun: () => boolean, + prepareChatRetry?: () => PrepareChatRetry | undefined) => + registerProviderLimitResumeWork(db, coordinator, { + resume: (companyId, requestId) => runControl.resumeTaskRetry(companyId, requestId), + schedulingSuppressed: async () => (await getSchedulingSuppression(true)).suppressed, + prepareChatRetry, + }, () => canRun() && readTaskDrain(new Date()) === null), registerIssueStateRecoveryWork: (coordinator: Parameters[1], canRun: () => boolean) => registerIssueRecoveryWork(db, coordinator, { stranded: scope => reconcileStrandedAssignedIssues({ ...scope, skipExternalConversationSettlement: true, skipRelatedRecovery: true }), diff --git a/server/src/services/heartbeat/restart-interrupted-turn.ts b/server/src/services/heartbeat/restart-interrupted-turn.ts index df89505a90e..a1458a27826 100644 --- a/server/src/services/heartbeat/restart-interrupted-turn.ts +++ b/server/src/services/heartbeat/restart-interrupted-turn.ts @@ -19,8 +19,8 @@ function isReattachmentLoss(error: string | null): boolean { return error !== null && REATTACHMENT_LOST_ERRORS.some(code => error === code || error.startsWith(`${code}: `)); } -const TURN_STARTED_EVENTS = ["turn.submitted", "turn.started", "turn.accepted"]; -const TURN_SETTLED_EVENTS = ["turn.completed", "turn.failed", "turn.cancelled", "turn.interrupted"]; +export const TURN_STARTED_EVENTS = ["turn.submitted", "turn.started", "turn.accepted"]; +export const TURN_SETTLED_EVENTS = ["turn.completed", "turn.failed", "turn.cancelled", "turn.interrupted"]; const asRecord = (value: unknown): Record => value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; @@ -29,7 +29,7 @@ const asRecord = (value: unknown): Record => * A driver that lost its event stream records `providerTerminalObserved: false` * (on the event or its stored PRP source): the real outcome is unknown, and * another turn could repeat work that already happened. */ -function isProvenTurnSettlement(event: { eventType: string; payload: unknown }) { +export function isProvenTurnSettlement(event: { eventType: string; payload: unknown }) { if (!TURN_SETTLED_EVENTS.includes(event.eventType)) return false; const payload = asRecord(event.payload); return payload.providerTerminalObserved !== false && diff --git a/server/src/services/native-runtime/native-provider-capacity.integration.test.ts b/server/src/services/native-runtime/native-provider-capacity.integration.test.ts index ee32b33e81a..d3a9a3b4167 100644 --- a/server/src/services/native-runtime/native-provider-capacity.integration.test.ts +++ b/server/src/services/native-runtime/native-provider-capacity.integration.test.ts @@ -1,8 +1,11 @@ import { randomUUID } from "node:crypto"; -import { eq } from "drizzle-orm"; +import { and, eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { agents, + agentWakeupRequests, + chatConversations, + chatEndpoints, companies, completionContracts, createDb, @@ -11,6 +14,8 @@ import { issueRecoveryActions, issues, nativeRunFinalizations, + toolApplications, + toolConnections, } from "@paperclipai/db"; import type { ControlPlanePort, @@ -31,6 +36,8 @@ import { executePaperclipNativeSession } from "./native-session-executor.js"; import { buildNativeCompletionContract } from "./completion-contracts.js"; import { PaperclipControlPlanePort } from "./paperclip-control-plane-port.js"; import { prepareNativeHeartbeatRun } from "./prepare-native-run.js"; +import { PROVIDER_LIMIT_RESUME_KEY_PREFIX, registerProviderLimitResumeWork, requestProviderLimitResumeRetry } from "./provider-limit-resume.js"; +import { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js"; describe("native provider capacity failure persistence", () => { let temporary: Awaited>; @@ -62,125 +69,211 @@ describe("native provider capacity failure persistence", () => { await temporary?.cleanup(); }); + /** Runs one native session whose provider ends its turn with `payload`. */ + async function failTurn(options: { + payload: Record; + replayed?: boolean; + responsibleUserId?: string | null; + }) { + const issueId = randomUUID(); + const runId = randomUUID(); + const [issue] = await db + .insert(issues) + .values({ + id: issueId, + companyId, + title: "Reply after a capacity failure", + status: "in_progress", + workMode: "standard", + assigneeAgentId: agentId, + }) + .returning(); + const [run] = await db + .insert(heartbeatRuns) + .values({ + id: runId, + companyId, + agentId, + status: "running", + runtimeMode: "native", + nativeIssueId: issueId, + invocationSource: "assignment", + triggerDetail: "system", + contextSnapshot: { issueId }, + responsibleUserId: options.responsibleUserId ?? null, + }) + .returning(); + await db + .update(issues) + .set({ executionRunId: runId }) + .where(eq(issues.id, issueId)); + const native = await prepareNativeHeartbeatRun({ + db, + run, + issue, + environmentLeaseId: randomUUID(), + }); + const [contract] = await db + .select() + .from(completionContracts) + .where(eq(completionContracts.issueId, issueId)); + const completionInput = buildNativeCompletionContract(issue, { + revision: contract.revision, + }); + expect(completionInput).toEqual(contract.contractJson); + await db.insert(nativeRunFinalizations).values({ + runId, + companyId, + issueId, + phase: "observed", + }); + // A real terminal follows provider session establishment. Keep the + // recovery evidence explicit; this must not be a bootstrap retry. + await db + .update(heartbeatRuns) + .set({ + runnerProfileJson: { + sessionCheckpoint: { + providerSessionId: "capacity-test-provider-session", + providerIdentity: { threadId: "capacity-test-thread" }, + }, + }, + }) + .where(eq(heartbeatRuns.id, runId)); + + const execution: NativeExecutionInputV1 = { + schema: "paperclip.native-execution-input.v1", + binding: { + companyId, + runId, + issueId, + agentId, + executionWorkspaceId: runId, + }, + provider: { kind: "codex", model: "gpt-5.6-luna" }, + task: { + identifier: issueId, + title: issue.title, + description: null, + prompt: "Reply to the current message.", + workMode: "standard", + }, + workspace: { + cwd: "/tmp", + repoUrl: null, + repoRef: null, + branchName: null, + }, + session: { + normalizedSessionId: native.normalizedSessionId, + driverKind: "codex_app_server", + protocolVersion: 1, + lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null }, + }, + completionContract: { + id: contract.id, + sha256: contract.canonicalSha256, + schemaVersion: "paperclip.completion-contract.v1", + contract: completionInput, + }, + interactionResponses: [], + credentialBindings: [], + }; + const event: PrpEvent = { + schema: "paperclip.prp.event.v1", + runId, + normalizedSessionId: native.normalizedSessionId, + turnId: native.turnId, + sourceInstanceId: native.runnerInstanceId, + sourceEventId: "capacity-terminal", + sourceSeq: 1, + sourceKind: "runner", + eventType: "turn.failed", + schemaVersion: 1, + priority: 0, + emittedAt: new Date().toISOString(), + payload: options.payload, + }; + const openInput = { + identity: { + companyId, + issueId, + runId, + agentId, + sessionId: native.normalizedSessionId, + }, + backendKind: "mock" as const, + sourceInstanceId: native.runnerInstanceId, + }; + if (options.replayed) { + // Model a controller crash after the event commit but before its + // observational callback or failure coordinator could run. + const priorPort = new PaperclipControlPlanePort(db, { + companyId, + issueId, + runId, + agentId, + sessionId: native.normalizedSessionId, + sourceInstanceId: native.runnerInstanceId, + controlPlaneSourceInstanceId: "prior-controller", + completionContractId: contract.id, + completionContractSha256: contract.canonicalSha256, + }); + await priorPort.openRun(openInput); + expect((await priorPort.appendEvent(event)).disposition).toBe( + "committed", + ); + } + provider.execute + .mockReset() + .mockImplementation( + async (executeOptions: { controlPlane: ControlPlanePort }) => { + await executeOptions.controlPlane.openRun(openInput); + const appended = await executeOptions.controlPlane.appendEvent(event); + expect(appended.disposition).toBe( + options.replayed ? "duplicate" : "committed", + ); + // Production reports the provider terminal through the event, not by + // pattern-matching this exception's arbitrary message. + throw new Error("provider turn stopped"); + }, + ); + await expect( + executePaperclipNativeSession({ + db, + execution, + runnerInstanceId: native.runnerInstanceId, + backend: { + descriptor: async () => { + throw new Error( + "Unexpected provider descriptor call in capacity test", + ); + }, + openSession: async () => { + throw new Error( + "Unexpected provider session call in capacity test", + ); + }, + }, + }), + ).rejects.toThrow("provider turn stopped"); + expect(provider.execute).toHaveBeenCalledTimes(1); + return { runId, issueId, sourceEventId: event.sourceEventId }; + } + + async function holdFor(issueId: string) { + const [recovery] = await db + .select() + .from(issueRecoveryActions) + .where(eq(issueRecoveryActions.sourceIssueId, issueId)); + return recovery; + } + it.each([false, true])( "stops automatic retries for a durable usage terminal (replayed=%s)", async (replayed) => { - const issueId = randomUUID(); - const runId = randomUUID(); - const [issue] = await db - .insert(issues) - .values({ - id: issueId, - companyId, - title: "Reply after a capacity failure", - status: "in_progress", - workMode: "standard", - assigneeAgentId: agentId, - }) - .returning(); - const [run] = await db - .insert(heartbeatRuns) - .values({ - id: runId, - companyId, - agentId, - status: "running", - runtimeMode: "native", - nativeIssueId: issueId, - invocationSource: "assignment", - triggerDetail: "system", - contextSnapshot: { issueId }, - }) - .returning(); - await db - .update(issues) - .set({ executionRunId: runId }) - .where(eq(issues.id, issueId)); - const native = await prepareNativeHeartbeatRun({ - db, - run, - issue, - environmentLeaseId: randomUUID(), - }); - const [contract] = await db - .select() - .from(completionContracts) - .where(eq(completionContracts.issueId, issueId)); - const completionInput = buildNativeCompletionContract(issue, { - revision: contract.revision, - }); - expect(completionInput).toEqual(contract.contractJson); - await db.insert(nativeRunFinalizations).values({ - runId, - companyId, - issueId, - phase: "observed", - }); - // A real terminal follows provider session establishment. Keep the - // recovery evidence explicit; this must not be a bootstrap retry. - await db - .update(heartbeatRuns) - .set({ - runnerProfileJson: { - sessionCheckpoint: { - providerSessionId: "capacity-test-provider-session", - providerIdentity: { threadId: "capacity-test-thread" }, - }, - }, - }) - .where(eq(heartbeatRuns.id, runId)); - - const execution: NativeExecutionInputV1 = { - schema: "paperclip.native-execution-input.v1", - binding: { - companyId, - runId, - issueId, - agentId, - executionWorkspaceId: runId, - }, - provider: { kind: "codex", model: "gpt-5.6-luna" }, - task: { - identifier: issueId, - title: issue.title, - description: null, - prompt: "Reply to the current message.", - workMode: "standard", - }, - workspace: { - cwd: "/tmp", - repoUrl: null, - repoRef: null, - branchName: null, - }, - session: { - normalizedSessionId: native.normalizedSessionId, - driverKind: "codex_app_server", - protocolVersion: 1, - lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null }, - }, - completionContract: { - id: contract.id, - sha256: contract.canonicalSha256, - schemaVersion: "paperclip.completion-contract.v1", - contract: completionInput, - }, - interactionResponses: [], - credentialBindings: [], - }; - const event: PrpEvent = { - schema: "paperclip.prp.event.v1", - runId, - normalizedSessionId: native.normalizedSessionId, - turnId: native.turnId, - sourceInstanceId: native.runnerInstanceId, - sourceEventId: "capacity-terminal", - sourceSeq: 1, - sourceKind: "runner", - eventType: "turn.failed", - schemaVersion: 1, - priority: 0, - emittedAt: new Date().toISOString(), + const { runId, issueId, sourceEventId } = await failTurn({ + replayed, payload: { status: "failed", error: { @@ -188,72 +281,7 @@ describe("native provider capacity failure persistence", () => { message: "Private account metadata", }, }, - }; - const openInput = { - identity: { - companyId, - issueId, - runId, - agentId, - sessionId: native.normalizedSessionId, - }, - backendKind: "mock" as const, - sourceInstanceId: native.runnerInstanceId, - }; - if (replayed) { - // Model a controller crash after the event commit but before its - // observational callback or failure coordinator could run. - const priorPort = new PaperclipControlPlanePort(db, { - companyId, - issueId, - runId, - agentId, - sessionId: native.normalizedSessionId, - sourceInstanceId: native.runnerInstanceId, - controlPlaneSourceInstanceId: "prior-controller", - completionContractId: contract.id, - completionContractSha256: contract.canonicalSha256, - }); - await priorPort.openRun(openInput); - expect((await priorPort.appendEvent(event)).disposition).toBe( - "committed", - ); - } - provider.execute - .mockReset() - .mockImplementation( - async (options: { controlPlane: ControlPlanePort }) => { - await options.controlPlane.openRun(openInput); - const appended = await options.controlPlane.appendEvent(event); - expect(appended.disposition).toBe( - replayed ? "duplicate" : "committed", - ); - // Production reports the provider terminal through the event, not by - // pattern-matching this exception's arbitrary message. - throw new Error("provider turn stopped"); - }, - ); - await expect( - executePaperclipNativeSession({ - db, - execution, - runnerInstanceId: native.runnerInstanceId, - backend: { - descriptor: async () => { - throw new Error( - "Unexpected provider descriptor call in capacity test", - ); - }, - openSession: async () => { - throw new Error( - "Unexpected provider session call in capacity test", - ); - }, - }, - }), - ).rejects.toThrow("provider turn stopped"); - - expect(provider.execute).toHaveBeenCalledTimes(1); + }); const [coordinator] = await db .select() .from(nativeRunFinalizations) @@ -271,10 +299,7 @@ describe("native provider capacity failure persistence", () => { .from(heartbeatRuns) .where(eq(heartbeatRuns.id, runId)); expect(failedRun.errorCode).toBe("native_provider_usage_limit"); - const [recovery] = await db - .select() - .from(issueRecoveryActions) - .where(eq(issueRecoveryActions.sourceIssueId, issueId)); + const recovery = await holdFor(issueId); expect(recovery).toMatchObject({ ownerType: "board", cause: "native_provider_usage_limit", @@ -294,8 +319,269 @@ describe("native provider capacity failure persistence", () => { .from(heartbeatRunEvents) .where(eq(heartbeatRunEvents.runId, runId)); expect( - events.filter((row) => row.sourceEventId === event.sourceEventId), + events.filter((row) => row.sourceEventId === sourceEventId), ).toHaveLength(1); + // No reset was reported, so nothing retries the task by itself. + await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: recovery.id })) + .resolves.toEqual({ requested: false, reason: "reset_unknown" }); }, ); + + /** The ACP harness's weekly-limit terminal, as staging recorded it (PAP-1057). */ + function weeklyLimit(resetAt: Date) { + const month = resetAt.toLocaleString("en-US", { month: "short", timeZone: "UTC" }); + const hour = resetAt.getUTCHours(); + const clock = `${hour % 12 || 12}${hour < 12 ? "am" : "pm"}`; + return { + status: "failed", + error: { + code: "RUNTIME", + message: "ACP agent reported a terminal limit failure.", + providerFailure: { + schema: "paperclip.provider-failure.v1", + provider: "anthropic", + phase: "turn", + category: "quota_exhausted", + retryability: "requires_action", + message: `ACP agent reported a terminal limit failure.\nYou've hit your weekly limit · resets ${month} ${resetAt.getUTCDate()}, ${clock} (UTC)`, + }, + }, + }; + } + + it("waits for a reported usage-limit reset and then requests the task's Retry once", async () => { + const resetAt = new Date(Date.now() + 2 * 24 * 60 * 60_000); + resetAt.setUTCMinutes(0, 0, 0); + const userId = `user-${randomUUID()}`; + const { runId, issueId } = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: userId }); + + const hold = await holdFor(issueId); + expect(hold).toMatchObject({ cause: "native_provider_usage_limit", + evidence: expect.objectContaining({ providerLimitResetAt: resetAt.toISOString() }) }); + // The hold says when work resumes, not that its session state is ambiguous. + expect(hold.nextAction).toBe(`The provider usage limit resets at ${resetAt.toISOString()}. ` + + "Paperclip will retry this task then; Retry starts it sooner if usage capacity is already restored."); + + // A hold saved by the previous release names no reset and calls the state ambiguous. + const { providerLimitResetAt: _reset, ...oldEvidence } = hold.evidence; + await db.update(issueRecoveryActions).set({ evidence: oldEvidence, nextAction: "Inspect the original provider failure " + + "and explicitly resolve the ambiguous session state; do not open a replacement provider session." }) + .where(eq(issueRecoveryActions.id, hold.id)); + + // Before the reset nothing starts; the owner keeps the reset as its deadline + // and tells the reader when work resumes. + await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id })) + .resolves.toEqual({ requested: false, waitUntil: resetAt }); + expect(await holdFor(issueId)).toMatchObject({ nextAction: hold.nextAction, + evidence: expect.objectContaining({ providerLimitResetAt: resetAt.toISOString() }) }); + + // At the reset Paperclip asks for the same Retry the accountable user would. + const afterReset = new Date(resetAt.getTime() + 1000); + const outcome = await requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id }, afterReset); + expect(outcome).toMatchObject({ requested: true }); + const [receipt] = await db.select().from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, companyId), + eq(agentWakeupRequests.idempotencyKey, `task-retry:provider-limit-reset:${runId}`))); + expect(receipt).toMatchObject({ reason: "task_retry", requestedByActorType: "user", requestedByActorId: userId, + status: "deferred_issue_execution", payload: expect.objectContaining({ issueId, + taskRetry: expect.objectContaining({ sourceRunId: runId, actorId: userId }) }) }); + expect((await holdFor(issueId)).evidence.providerLimitResume).toMatchObject({ state: "requested", + requestId: receipt.id, resetAt: resetAt.toISOString() }); + + // A second pass never requests another Retry for the same hold. + await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id }, afterReset)) + .resolves.toEqual({ requested: false, reason: "not_waiting" }); + const receipts = await db.select().from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.reason, "task_retry"), + eq(agentWakeupRequests.agentId, agentId))); + expect(receipts.filter(row => (row.payload as Record).issueId === issueId)).toHaveLength(1); + }); + + it("starts the Retry from the hold's own deadline after a restart rebuilds it", async () => { + // A typed reset a few seconds out; the owner learns it only from durable rows. + const resetAt = new Date(Date.now() + 3000); + const payload = weeklyLimit(resetAt); + (payload.error.providerFailure as Record).retryAt = resetAt.toISOString(); + const userId = `user-${randomUUID()}`; + const { issueId } = await failTurn({ payload, responsibleUserId: userId }); + const hold = await holdFor(issueId); + const errors: unknown[] = []; + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, + onError: error => { errors.push(error); } }); + const resume = vi.fn(async () => undefined); + try { + const worker = registerProviderLimitResumeWork(db, coordinator, + { resume, schedulingSuppressed: async () => false }, () => true); + await worker.ready; + // Nothing starts before the reset. + expect(resume).not.toHaveBeenCalled(); + await vi.waitFor(() => expect(resume).toHaveBeenCalledTimes(1), { timeout: 20_000, interval: 200 }); + const [receipt] = await db.select().from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.reason, "task_retry"), + eq(agentWakeupRequests.requestedByActorId, userId))); + expect(resume).toHaveBeenCalledWith(companyId, receipt.id); + expect(Date.now()).toBeGreaterThanOrEqual(resetAt.getTime()); + expect((await holdFor(issueId)).evidence.providerLimitResume).toMatchObject({ state: "requested", requestId: receipt.id }); + expect(hold.id).toBe((await holdFor(issueId)).id); + } finally { + await coordinator.stop(); + } + expect(errors).toEqual([]); + }, 30_000); + + it("leaves a visible Retry when no user is accountable for the run", async () => { + const resetAt = new Date(Date.now() + 3 * 60 * 60_000); + resetAt.setUTCMinutes(0, 0, 0); + const { issueId } = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: null }); + const hold = await holdFor(issueId); + expect(hold.nextAction).toBe(`The provider usage limit resets at ${resetAt.toISOString()}. ` + + "Retry the task after that time, or sooner if usage capacity is restored."); + const outcome = await requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id }, + new Date(resetAt.getTime() + 1000)); + expect(outcome).toEqual({ requested: false, reason: "no_accountable_user" }); + expect((await holdFor(issueId)).nextAction).toBe("Paperclip did not retry this task after the provider usage limit " + + "reset because no user is accountable for the run. Retry the task when usage capacity is available."); + }); + + it("prepares a connected chat conversation's Retry through the chat service", async () => { + const resetAt = new Date(Date.now() + 2 * 60 * 60_000); + resetAt.setUTCMinutes(0, 0, 0); + const userId = `user-${randomUUID()}`; + const { runId, issueId } = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: userId }); + // The task belongs to a restricted external chat conversation. + const [application] = await db.insert(toolApplications).values({ companyId, name: "Slack", type: "chat" }).returning(); + const connectionId = randomUUID(); + await db.insert(toolConnections).values({ id: connectionId, companyId, applicationId: application!.id, uid: connectionId, + name: "Slack", transport: "chat_sdk", connectionPurpose: "channel" }); + const endpointId = randomUUID(); + await db.insert(chatEndpoints).values({ id: endpointId, companyId, connectionId, provider: "slack", publicId: endpointId, + assignedAgentId: agentId, status: "active", externalExecutionPolicy: "restricted" }); + await db.insert(chatConversations).values({ companyId, endpointId, issueId, externalConversationId: "channel", + externalThreadId: issueId, externalLabel: "#limits", state: "waiting" }); + const hold = await holdFor(issueId); + const chatActionId = randomUUID(); + const prepareChatRetry = vi.fn(async () => ({ actionId: chatActionId })); + const outcome = await requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id, prepareChatRetry }, + new Date(resetAt.getTime() + 1000)); + expect(outcome).toMatchObject({ requested: true }); + expect(prepareChatRetry).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ + companyId, issueId, agentId, failedRunId: runId, initiatedByUserId: userId })); + const [receipt] = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, companyId), + eq(agentWakeupRequests.idempotencyKey, `task-retry:${PROVIDER_LIMIT_RESUME_KEY_PREFIX}${runId}`))); + expect(receipt.payload).toMatchObject({ taskRetry: expect.objectContaining({ chatActionId }) }); + }); + + it("replaces the retry promise on every give-up path", async () => { + const resetAt = new Date(Date.now() + 2 * 60 * 60_000); + resetAt.setUTCMinutes(0, 0, 0); + const afterReset = new Date(resetAt.getTime() + 1000); + // The failed run's terminal can no longer be read as a provider-observed reset. + const unreadable = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: `user-${randomUUID()}` }); + await db.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, unreadable.runId)); + const unreadableHold = await holdFor(unreadable.issueId); + expect(unreadableHold.nextAction).toContain("Paperclip will retry this task then"); + await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: unreadableHold.id }, afterReset)) + .resolves.toEqual({ requested: false, reason: "reset_unknown" }); + expect((await holdFor(unreadable.issueId)).nextAction).toBe("Paperclip did not retry this task after the provider " + + "usage limit reset because the provider's reset could no longer be read. Retry the task when usage capacity is available."); + // The hold's run no longer failed for the usage limit. + const changed = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: `user-${randomUUID()}` }); + await db.update(heartbeatRuns).set({ errorCode: "adapter_failed" }).where(eq(heartbeatRuns.id, changed.runId)); + const changedHold = await holdFor(changed.issueId); + await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: changedHold.id }, afterReset)) + .resolves.toEqual({ requested: false, reason: "source_run_mismatch" }); + expect((await holdFor(changed.issueId)).nextAction).toBe("Paperclip did not retry this task after the provider " + + "usage limit reset because the failed run no longer matches this hold. Retry the task when usage capacity is available."); + }); + + it("stops after three automatic Retries in a row and counts again after a successful run", async () => { + const resetAt = new Date(Date.now() + 2 * 60 * 60_000); + resetAt.setUTCMinutes(0, 0, 0); + const afterReset = new Date(resetAt.getTime() + 1000); + const userId = `user-${randomUUID()}`; + const { issueId } = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: userId }); + const hold = await holdFor(issueId); + // Earlier usage-limit Retries on this task, none followed by a success. + const earlierRetry = (task: string) => ({ companyId, agentId, source: "on_demand", triggerDetail: "manual", + reason: "task_retry", status: "completed", idempotencyKey: `task-retry:${PROVIDER_LIMIT_RESUME_KEY_PREFIX}${randomUUID()}`, + requestedByActorType: "user", requestedByActorId: userId, payload: { issueId: task }, + requestedAt: new Date(Date.now() - 60_000) }); + // Two in a row still leave this one. + await db.insert(agentWakeupRequests).values([earlierRetry(issueId), earlierRetry(issueId)]); + const [third] = await db.insert(agentWakeupRequests).values(earlierRetry(issueId)).returning(); + await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id }, afterReset)) + .resolves.toEqual({ requested: false, reason: "automatic_retry_budget_used" }); + expect((await holdFor(issueId)).nextAction).toBe("Paperclip did not retry this task after the provider usage limit " + + "reset because three automatic Retries in a row did not restore usage. Retry the task when usage capacity is available."); + expect(third.id).toBeTruthy(); + + // A successful run on the task after earlier Retries restores the budget. + const second = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: userId }); + await db.insert(agentWakeupRequests).values([earlierRetry(second.issueId), earlierRetry(second.issueId), + earlierRetry(second.issueId)]); + await db.insert(heartbeatRuns).values({ companyId, agentId, status: "succeeded", runtimeMode: "native", + nativeIssueId: second.issueId, invocationSource: "assignment", triggerDetail: "system", + contextSnapshot: { issueId: second.issueId }, finishedAt: new Date(Date.now() - 1000), + createdAt: new Date(Date.now() - 10 * 60_000) }); + const secondHold = await holdFor(second.issueId); + await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: secondHold.id }, afterReset)) + .resolves.toMatchObject({ requested: true }); + }); + + it("rebuilds every waiting hold after a restart, past one page", async () => { + const resetAt = new Date(Date.now() + 2 * 60 * 60_000); + resetAt.setUTCMinutes(0, 0, 0); + const { issueId } = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: `user-${randomUUID()}` }); + const hold = await holdFor(issueId); + // A hold saved before holds named their reset; it sorts after 600 others. + const { providerLimitResetAt: _reset, ...oldEvidence } = hold.evidence; + await db.delete(issueRecoveryActions).where(eq(issueRecoveryActions.id, hold.id)); + const otherCompanyId = randomUUID(); + await db.insert(companies).values({ id: otherCompanyId, name: "Other holds", issuePrefix: "OTH" }); + const otherIssues = Array.from({ length: 600 }, () => randomUUID()); + await db.insert(issues).values(otherIssues.map(id => ({ id, companyId: otherCompanyId, title: "Other", status: "in_progress" }))); + const { id: _id, companyId: _company, sourceIssueId: _issue, createdAt: _c, updatedAt: _u, ...template } = hold; + for (let page = 0; page < 6; page++) { + await db.insert(issueRecoveryActions).values(Array.from({ length: 100 }, (_, index) => ({ ...template, + companyId: otherCompanyId, sourceIssueId: otherIssues[page * 100 + index]!, + id: `00000000-0000-4000-8000-${String(page * 100 + index).padStart(12, "0")}`, + evidence: { ...oldEvidence, runId: randomUUID() } }))); + } + await db.insert(issueRecoveryActions).values({ ...hold, id: `ffffffff-ffff-4fff-bfff-${randomUUID().slice(-12)}`, + evidence: oldEvidence }); + const errors: unknown[] = []; + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, + onError: error => { errors.push(error); } }); + try { + const worker = registerProviderLimitResumeWork(db, coordinator, + { resume: vi.fn(async () => undefined), schedulingSuppressed: async () => false }, () => true); + await worker.ready; + // The hold past the first page reads its reset and records it. + await vi.waitFor(async () => expect((await holdFor(issueId)).evidence.providerLimitResetAt).toBe(resetAt.toISOString()), + { timeout: 25_000, interval: 250 }); + } finally { + await coordinator.stop(); + } + expect(errors).toEqual([]); + }, 40_000); + + it("reports a reset beyond the automatic wait without retrying by itself", async () => { + // A monthly limit, typed by the provider, three weeks out. + const resetAt = new Date(Date.now() + 21 * 24 * 60 * 60_000); + resetAt.setUTCMinutes(0, 0, 0); + const payload = weeklyLimit(resetAt); + (payload.error.providerFailure as Record).retryAt = resetAt.toISOString(); + const userId = `user-${randomUUID()}`; + const { issueId } = await failTurn({ payload, responsibleUserId: userId }); + const hold = await holdFor(issueId); + expect(hold.nextAction).toBe(`The provider usage limit resets at ${resetAt.toISOString()}. ` + + "Retry the task after that time, or sooner if usage capacity is restored."); + expect(hold.evidence).toMatchObject({ providerLimitResetAt: resetAt.toISOString() }); + await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id }, + new Date(resetAt.getTime() + 1000))).resolves.toEqual({ requested: false, reason: "reset_beyond_wait" }); + expect((await holdFor(issueId)).nextAction).toBe(hold.nextAction); + const receipts = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, companyId), + eq(agentWakeupRequests.requestedByActorId, userId))); + expect(receipts).toEqual([]); + }); }); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index cc2d29953b0..7ed7a9692c6 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -12155,6 +12155,18 @@ async function executePaperclipNativeSessionAttempt( .from(heartbeatRuns).where(eq(heartbeatRuns.id, input.execution.binding.runId)) .then(rows => rows.some(row => nativeCheckpointRecordsCompletedTurn(row.runnerProfileJson, input.execution.binding.runId))) .catch(() => false); + // An exhausted provider allowance is not ambiguous session state: the + // provider ended its turn. Say when it resets and whether Paperclip will + // retry then. A failed read only loses that detail. + const providerLimit = sourceFailureCode === "native_provider_usage_limit" && phase === "terminal_failure" + ? await import("./provider-limit-resume.js").then(async ({ planProviderLimitResume, providerLimitNextAction }) => { + const plan = await planProviderLimitResume(input.db, input.execution.binding.runId); + return { plan, nextAction: providerLimitNextAction(plan) }; + }).catch((failure: unknown) => { + logger.warn({ err: failure, runId: input.execution.binding.runId }, "provider limit reset unavailable"); + return null; + }) + : null; const recoveryProjection = nativeSessionRecoveryProjection({ phase, failureCode, @@ -12222,9 +12234,12 @@ async function executePaperclipNativeSessionAttempt( providerEventsExist: recoveryEvidence.providerEventsExist, checkpointExists: recoveryEvidence.checkpointExists, ...(providerCooldownAt ? { providerCooldownAt: providerCooldownAt.toISOString() } : {}), + ...(providerLimit?.plan.resetAt ? { providerLimitResetAt: providerLimit.plan.resetAt.toISOString() } : {}), recoveryOwner: recoveryProjection.recoveryOwner, nextAction: - sourceFailureCode === "native_permission_declined" + providerLimit + ? providerLimit.nextAction + : sourceFailureCode === "native_permission_declined" ? "Provider permission was declined. Inspect the task and give explicit direction before starting further provider work. Automatic recovery is stopped." : sourceFailureCode === "native_provider_approval_required" ? "Approval required. Review the operation and update the agent's permission setting before retrying. This runner has no interactive approval handler." @@ -12458,6 +12473,9 @@ async function executePaperclipNativeSessionAttempt( .where(eq(issues.id, input.execution.binding.issueId)); } if (!stillOwnsTask) return; + // The hold's reset deadline belongs to the provider-limit owner. + if (providerLimit?.plan.automatic) await notifyDeliveryWork(tx, DELIVERY_QUEUES.providerLimitResume, + JSON.stringify({ companyId: input.execution.binding.companyId })); await issueRecoveryActionService( tx as unknown as Db, ).upsertSourceScoped({ @@ -12485,9 +12503,12 @@ async function executePaperclipNativeSessionAttempt( providerSessionEstablished: recoveryEvidence.providerSessionEstablished, ...(providerCooldownAt ? { providerCooldownAt: providerCooldownAt.toISOString() } : {}), + ...(providerLimit?.plan.resetAt ? { providerLimitResetAt: providerLimit.plan.resetAt.toISOString() } : {}), }, nextAction: - sourceFailureCode === "native_permission_declined" + providerLimit + ? providerLimit.nextAction + : sourceFailureCode === "native_permission_declined" ? "Provider permission was declined. Inspect the task and give explicit direction before starting further provider work. Automatic recovery is stopped." : sourceFailureCode === "native_provider_approval_required" ? "Approval required. Review the operation and update the agent's permission setting before retrying. This runner has no interactive approval handler." diff --git a/server/src/services/native-runtime/provider-limit-resume.ts b/server/src/services/native-runtime/provider-limit-resume.ts new file mode 100644 index 00000000000..82497b620ba --- /dev/null +++ b/server/src/services/native-runtime/provider-limit-resume.ts @@ -0,0 +1,284 @@ +import { and, asc, desc, eq, gt, inArray, isNull, like, sql } from "drizzle-orm"; +import { + agentWakeupRequests, + heartbeatRunEvents, + heartbeatRuns, + issueRecoveryActions, + issues, + type Db, +} from "@paperclipai/db"; +import { readProviderFailure } from "@paperclipai/shared"; +import { HttpError } from "../../errors.js"; +import { logger } from "../../middleware/logger.js"; +import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js"; +import { DELIVERY_QUEUES } from "../delivery-work-notifications.js"; +import { isProvenTurnSettlement, TURN_SETTLED_EVENTS, TURN_STARTED_EVENTS } from "../heartbeat/restart-interrupted-turn.js"; +import { parseProviderQuotaClockReset } from "../provider-quota-reset.js"; +import { registerScopedDeadlineWork } from "../scoped-deadline-work.js"; +import { requestTaskRetry } from "../task-retry.js"; + +/** The chat service's Retry callback, which a connected conversation's Retry needs. */ +export type PrepareChatRetry = NonNullable[0]["prepareChatRetry"]>; + +/** + * A native run whose provider ended its turn because the account's usage limit + * ran out. When the provider reported when the limit resets, Paperclip asks for + * the task's Retry itself at that time, as the accountable user would. Retry + * admission keeps every gate (stop proof, saved work, action reconciliation), + * so this never starts work a user's own Retry could not. + */ +export const NATIVE_PROVIDER_USAGE_LIMIT = "native_provider_usage_limit"; +/** Longer than a weekly limit's reset, so the reset is the only wait. */ +export const PROVIDER_LIMIT_RESUME_MAX_WAIT_MS = 8 * 24 * 60 * 60_000; +/** A reset older than this belongs to an incident nobody is waiting on. */ +const STALE_RESET_MS = 24 * 60 * 60_000; +/** Automatic Retries in a row without a successful run between them. */ +const MAX_AUTOMATIC_RESUMES = 3; +export const PROVIDER_LIMIT_RESUME_KEY_PREFIX = "provider-limit-reset:"; +const LIMIT_CATEGORIES = ["rate_limit", "quota_exhausted"]; + +const asRecord = (value: unknown): Record => + value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; + +/** The provider-reported failure on a settled turn event, raw or PRP-wrapped. */ +function providerFailureOf(payload: unknown) { + const direct = asRecord(asRecord(payload).error).providerFailure; + const wrapped = asRecord(asRecord(asRecord(asRecord(payload).prpEvent).payload).error).providerFailure; + return readProviderFailure(direct) ?? readProviderFailure(wrapped); +} + +export type ProviderLimitReset = { + resetAt: Date; observedAt: Date; + /** False for a reset further out than Paperclip waits by itself (a monthly limit). */ + withinAutomaticWait: boolean; +}; + +/** + * When the provider said the usage limit resets, from the run's own durable + * events. Null unless the last turn event is a provider-observed settlement + * reporting an exhausted allowance with a reset after it. + */ +export async function readNativeUsageLimitReset( + db: Pick, + run: { id: string; companyId: string }, +): Promise { + const [lastTurn] = await db.select({ eventType: heartbeatRunEvents.eventType, payload: heartbeatRunEvents.payload, + createdAt: heartbeatRunEvents.createdAt }) + .from(heartbeatRunEvents).where(and( + eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id), + inArray(heartbeatRunEvents.eventType, [...TURN_STARTED_EVENTS, ...TURN_SETTLED_EVENTS]), + )).orderBy(desc(heartbeatRunEvents.seq)).limit(1); + // An unsettled or unobserved turn may still be working: its outcome is unknown. + if (!lastTurn || lastTurn.eventType !== "turn.failed" || !isProvenTurnSettlement(lastTurn)) return null; + const failure = providerFailureOf(lastTurn.payload); + if (!failure || !LIMIT_CATEGORIES.includes(failure.category)) return null; + const observedAt = lastTurn.createdAt; + const typed = failure.retryAt ? new Date(failure.retryAt) : null; + const resetAt = typed && Number.isFinite(typed.getTime()) ? typed : parseProviderQuotaClockReset(failure.message, observedAt); + if (!resetAt || resetAt.getTime() <= observedAt.getTime()) return null; + return { resetAt, observedAt, + withinAutomaticWait: resetAt.getTime() - observedAt.getTime() <= PROVIDER_LIMIT_RESUME_MAX_WAIT_MS }; +} + +/** The user whose authority Retry uses: the requester, else the run's accountable user. */ +async function accountableUser(db: Pick, run: typeof heartbeatRuns.$inferSelect) { + const [wake] = run.wakeupRequestId ? await db.select({ type: agentWakeupRequests.requestedByActorType, + id: agentWakeupRequests.requestedByActorId }).from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, run.companyId), eq(agentWakeupRequests.id, run.wakeupRequestId))) : []; + if (wake?.type === "user" && wake.id) return wake.id; + return run.responsibleUserId ?? null; +} + +export type ProviderLimitResumePlan = + | { automatic: true; resetAt: Date; actorId: string } + | { automatic: false; resetAt: Date | null }; + +/** Whether this failed run's task continues by itself once the limit resets. */ +export async function planProviderLimitResume(db: Pick, runId: string): Promise { + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + if (!run) return { automatic: false, resetAt: null }; + const reset = await readNativeUsageLimitReset(db, run); + if (!reset) return { automatic: false, resetAt: null }; + // A reset beyond the bounded wait is still reported; only the automatic Retry is bounded. + const actorId = reset.withinAutomaticWait ? await accountableUser(db, run) : null; + return actorId ? { automatic: true, resetAt: reset.resetAt, actorId } : { automatic: false, resetAt: reset.resetAt }; +} + +export function providerLimitNextAction(plan: ProviderLimitResumePlan) { + if (plan.automatic) { + return `The provider usage limit resets at ${plan.resetAt.toISOString()}. Paperclip will retry this task then; Retry starts it sooner if usage capacity is already restored.`; + } + return plan.resetAt + ? `The provider usage limit resets at ${plan.resetAt.toISOString()}. Retry the task after that time, or sooner if usage capacity is restored.` + : "Restore model provider usage capacity, then retry the task. The provider did not report when its usage limit resets."; +} + +type Outcome = + | { requested: true; requestId: string } + | { requested: false; waitUntil: Date } + | { requested: false; reason: string }; + +async function settle(db: Db, actionId: string, state: Record, nextAction?: string) { + await db.update(issueRecoveryActions).set({ + evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResume', ${JSON.stringify(state)}::jsonb)`, + ...(nextAction ? { nextAction } : {}), + updatedAt: new Date(), + }).where(and(eq(issueRecoveryActions.id, actionId), sql`${issueRecoveryActions.evidence}->'providerLimitResume' is null`)); +} + +/** Why Paperclip did not retry after a reset it announced; the Retry stays. + * Every give-up reason is listed, so no give-up leaves the promise standing. */ +const NOT_RETRIED = { + source_run_mismatch: "the failed run no longer matches this hold", + reset_unknown: "the provider's reset could no longer be read", + task_changed: "the task changed", + no_accountable_user: "no user is accountable for the run", + automatic_retry_budget_used: "three automatic Retries in a row did not restore usage", + retry_stale: "a newer run exists", + retry_refused: "Retry was not allowed for the accountable user", + reset_stale: "the reset passed more than a day ago", +} as const; +type NotRetriedReason = keyof typeof NOT_RETRIED; + +/** + * Requests the task's Retry for one usage-limit hold once its reset has + * passed. Idempotent per run: the Retry key and the recorded outcome both + * prevent a second request. + */ +export async function requestProviderLimitResumeRetry(db: Db, input: { + companyId: string; actionId: string; prepareChatRetry?: PrepareChatRetry; +}, now = new Date()): Promise { + const [action] = await db.select().from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.id, input.actionId))); + if (!action || action.status !== "active" || action.kind !== "active_run_watchdog" || action.cause !== NATIVE_PROVIDER_USAGE_LIMIT + || action.evidence?.providerLimitResume) return { requested: false, reason: "not_waiting" }; + const runId = typeof action.evidence?.runId === "string" ? action.evidence.runId : null; + const [run] = runId ? await db.select().from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, action.companyId), sql`${heartbeatRuns.id}::text = ${runId}`)) : []; + const done = async (reason: NotRetriedReason, extra: Record = {}) => { + // Replace a promise to retry with what the user can do now. + const nextAction = action.evidence?.providerLimitResetAt + ? `Paperclip did not retry this task after the provider usage limit reset because ${NOT_RETRIED[reason]}. Retry the task when usage capacity is available.` + : undefined; + await settle(db, action.id, { state: "not_requested", reason, decidedAt: now.toISOString(), ...extra }, nextAction); + return { requested: false as const, reason }; + }; + // The failure that created the hold may still be settling its run. + if (run && ["queued", "running"].includes(run.status)) return { requested: false, waitUntil: new Date(now.getTime() + 60_000) }; + if (!run || run.runtimeMode !== "native" || run.status !== "failed" || run.errorCode !== NATIVE_PROVIDER_USAGE_LIMIT) + return done("source_run_mismatch"); + const reset = await readNativeUsageLimitReset(db, run); + if (!reset) return done("reset_unknown"); + if (!reset.withinAutomaticWait) { + // Too far out to wait by itself: the hold names the reset and leaves the + // Retry to the user; it never promised an automatic one. + await db.update(issueRecoveryActions).set({ + nextAction: providerLimitNextAction({ automatic: false, resetAt: reset.resetAt }), + evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResetAt', ${reset.resetAt.toISOString()}::text)`, + updatedAt: now, + }).where(and(eq(issueRecoveryActions.id, action.id), eq(issueRecoveryActions.status, "active"))); + await settle(db, action.id, { state: "not_requested", reason: "reset_beyond_wait", resetAt: reset.resetAt.toISOString(), + decidedAt: now.toISOString() }); + return { requested: false, reason: "reset_beyond_wait" }; + } + if (reset.resetAt.getTime() > now.getTime()) { + // A hold saved by an earlier release names no reset; tell its reader when work resumes. + if (!action.evidence?.providerLimitResetAt) { + const actorId = await accountableUser(db, run); + await db.update(issueRecoveryActions).set({ + nextAction: providerLimitNextAction(actorId + ? { automatic: true, resetAt: reset.resetAt, actorId } : { automatic: false, resetAt: reset.resetAt }), + evidence: sql`coalesce(${issueRecoveryActions.evidence}, '{}'::jsonb) || jsonb_build_object('providerLimitResetAt', ${reset.resetAt.toISOString()}::text)`, + updatedAt: now, + }).where(and(eq(issueRecoveryActions.id, action.id), eq(issueRecoveryActions.status, "active"))); + } + return { requested: false, waitUntil: reset.resetAt }; + } + if (now.getTime() - reset.resetAt.getTime() > STALE_RESET_MS) return done("reset_stale", { resetAt: reset.resetAt.toISOString() }); + const issueId = action.sourceIssueId; + const [issue] = await db.select({ status: issues.status, assigneeAgentId: issues.assigneeAgentId }).from(issues) + .where(and(eq(issues.companyId, run.companyId), eq(issues.id, issueId))); + if (!issue || issue.assigneeAgentId !== run.agentId || ["done", "cancelled"].includes(issue.status)) return done("task_changed"); + const actorId = await accountableUser(db, run); + if (!actorId) return done("no_accountable_user"); + // Bound a provider that keeps reporting resets that do not restore capacity. + const [lastSuccess] = await db.select({ finishedAt: heartbeatRuns.finishedAt }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, run.companyId), eq(heartbeatRuns.agentId, run.agentId), eq(heartbeatRuns.status, "succeeded"), + sql`coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.issueId}::text, ${heartbeatRuns.contextSnapshot}->>'issueId') = ${issueId}`, + )).orderBy(desc(heartbeatRuns.finishedAt)).limit(1); + const earlier = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, run.companyId), eq(agentWakeupRequests.agentId, run.agentId), + like(agentWakeupRequests.idempotencyKey, `task-retry:${PROVIDER_LIMIT_RESUME_KEY_PREFIX}%`), + sql`${agentWakeupRequests.payload}->>'issueId' = ${issueId}`, + lastSuccess?.finishedAt ? gt(agentWakeupRequests.requestedAt, lastSuccess.finishedAt) : undefined, + )).limit(MAX_AUTOMATIC_RESUMES); + if (earlier.length >= MAX_AUTOMATIC_RESUMES) return done("automatic_retry_budget_used"); + try { + const receipt = await requestTaskRetry({ db, companyId: run.companyId, issueId, actorId, + actorSource: actorId === "local-board" ? "local_implicit" : "session", + idempotencyKey: `${PROVIDER_LIMIT_RESUME_KEY_PREFIX}${run.id}`, observedRunId: run.id, + initiatedBy: "provider_limit_reset", prepareChatRetry: input.prepareChatRetry }); + if (!receipt.accepted || !receipt.requestId) return done("retry_stale"); + await settle(db, action.id, { state: "requested", requestId: receipt.requestId, resetAt: reset.resetAt.toISOString(), + requestedAt: now.toISOString() }); + return { requested: true, requestId: receipt.requestId }; + } catch (error) { + // Authority or conversation checks refused it; the visible Retry remains. + if (!(error instanceof HttpError)) throw error; + logger.info({ runId: run.id, status: error.status }, "provider limit reset left for an explicit Retry"); + return done("retry_refused", { status: error.status }); + } +} + +type Scope = { companyId: string }; +const LOAD_PAGE_SIZE = 500; +type Entry = { id: string; companyId: string; dueAt: number }; + +/** + * Deadline owner for usage-limit holds: one entry per hold, due at its + * provider-reported reset. Holds are the durable truth; a new hold notifies + * this queue, and startup reconstructs every waiting hold. + */ +export function registerProviderLimitResumeWork( + db: Db, + coordinator: ReturnType, + owner: { resume(companyId: string, requestId: string): Promise; schedulingSuppressed(): Promise; + /** Read when a Retry is requested: the chat service registers it after startup. */ + prepareChatRetry?: () => PrepareChatRetry | undefined }, + canRun: () => boolean, +) { + const cursors = new Map(); + return registerScopedDeadlineWork(coordinator, { + queue: DELIVERY_QUEUES.providerLimitResume, + decodeScope: hint => hint === "*" ? undefined : JSON.parse(hint) as Scope, + matches: (entry, scope) => !scope || entry.companyId === scope.companyId, + load: async scope => { + // One bounded page per pass, resumed from a stable cursor until every + // waiting hold is loaded: a hold left out would never retry. + const key = scope ? JSON.stringify(scope) : "*"; + const cursor = cursors.get(key); + const rows = await db.select({ id: issueRecoveryActions.id, companyId: issueRecoveryActions.companyId }) + .from(issueRecoveryActions).where(and( + scope ? eq(issueRecoveryActions.companyId, scope.companyId) : undefined, + eq(issueRecoveryActions.status, "active"), eq(issueRecoveryActions.kind, "active_run_watchdog"), + eq(issueRecoveryActions.cause, NATIVE_PROVIDER_USAGE_LIMIT), + sql`${issueRecoveryActions.evidence}->'providerLimitResume' is null`, + isNull(issueRecoveryActions.resolvedAt), + cursor ? gt(issueRecoveryActions.id, cursor) : undefined, + )).orderBy(asc(issueRecoveryActions.id)).limit(LOAD_PAGE_SIZE); + const complete = rows.length < LOAD_PAGE_SIZE; + if (complete) cursors.delete(key); else cursors.set(key, rows.at(-1)!.id); + // check() reads each hold's reset and returns its real deadline. + return { rows: rows.map(row => ({ ...row, dueAt: 0 })), complete }; + }, + check: async entry => { + if (await owner.schedulingSuppressed()) return { ...entry, dueAt: Date.now() + 5 * 60_000 }; + const outcome = await requestProviderLimitResumeRetry(db, { companyId: entry.companyId, actionId: entry.id, + prepareChatRetry: owner.prepareChatRetry?.() }); + if ("waitUntil" in outcome) return { ...entry, dueAt: outcome.waitUntil.getTime() }; + if (outcome.requested) await owner.resume(entry.companyId, outcome.requestId).catch((error: unknown) => + logger.warn({ err: error, actionId: entry.id }, "provider limit Retry remains queued")); + return null; + }, + }, canRun); +} diff --git a/server/src/services/provider-quota-reset.test.ts b/server/src/services/provider-quota-reset.test.ts new file mode 100644 index 00000000000..f3ba512145b --- /dev/null +++ b/server/src/services/provider-quota-reset.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from "vitest"; +import { parseProviderQuotaClockReset } from "./provider-quota-reset.js"; + +describe("parseProviderQuotaClockReset", () => { + it("reads a weekly limit's calendar reset, as Claude's ACP agent reports it", () => { + // Staging run c086fa26 (PAP-1057), 2026-11-10: the reset is two days out. + const now = new Date("2026-11-10T20:06:33.000Z"); + const message = "ACP agent reported a terminal limit failure.\nYou've hit your weekly limit · resets Nov 12, 6pm (UTC)"; + expect(parseProviderQuotaClockReset(message, now)).toEqual(new Date("2026-11-12T18:00:00.000Z")); + }); + + it("reads a calendar reset in a named time zone, with minutes and an ordinal", () => { + const now = new Date("2026-07-15T20:00:00.000Z"); + expect(parseProviderQuotaClockReset("resets Jul 17th at 4:30 PM (America/Chicago)", now)) + .toEqual(new Date("2026-07-17T21:30:00.000Z")); + expect(parseProviderQuotaClockReset("Resets on August 2, 9am (UTC)", now)) + .toEqual(new Date("2026-08-02T09:00:00.000Z")); + }); + + it("rolls a calendar reset that already passed into next year, and rejects impossible dates", () => { + expect(parseProviderQuotaClockReset("resets Jan 2, 6pm (UTC)", new Date("2026-12-30T10:00:00.000Z"))) + .toEqual(new Date("2027-01-02T18:00:00.000Z")); + expect(parseProviderQuotaClockReset("resets Nov 31, 6pm (UTC)", new Date("2026-11-10T10:00:00.000Z"))).toBeNull(); + }); + + it("reads a calendar reset that already passed as expired, never as a year away", () => { + // Recovery rereads an unchanged failure days after its reset. + expect(parseProviderQuotaClockReset("resets Nov 12, 6pm (UTC)", new Date("2026-11-14T10:00:00.000Z"))) + .toEqual(new Date("2026-11-12T18:00:00.000Z")); + expect(parseProviderQuotaClockReset("resets Dec 30, 6pm (UTC)", new Date("2027-01-03T10:00:00.000Z"))) + .toEqual(new Date("2026-12-30T18:00:00.000Z")); + }); + + it("keeps reading a clock-only reset as the next matching time", () => { + const now = new Date("2026-07-15T20:00:00.000Z"); + expect(parseProviderQuotaClockReset("You've hit your session limit · resets 2am (UTC)", now)) + .toEqual(new Date("2026-07-16T02:00:00.000Z")); + expect(parseProviderQuotaClockReset("Try again at 4:30 PM (America/Chicago).", now)) + .toEqual(new Date("2026-07-15T21:30:00.000Z")); + expect(parseProviderQuotaClockReset("resets 9pm", now)).toEqual(new Date("2026-07-15T21:00:00.000Z")); + expect(parseProviderQuotaClockReset("Provider quota exceeded for this model.", now)).toBeNull(); + }); +}); diff --git a/server/src/services/provider-quota-reset.ts b/server/src/services/provider-quota-reset.ts index b2d62613b93..25e275ce9e0 100644 --- a/server/src/services/provider-quota-reset.ts +++ b/server/src/services/provider-quota-reset.ts @@ -1,17 +1,29 @@ +const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]; +const RESET_PATTERN = new RegExp( + "(?:try again at|resets?(?:\\s+(?:at|on))?)\\s+" + + // Optional calendar date, as in "resets Nov 12, 6pm (UTC)" for a weekly limit. + `(?:(${MONTHS.join("|")})[a-z]*\\.?\\s+(\\d{1,2})(?:st|nd|rd|th)?,?\\s+(?:at\\s+)?)?` + + "(\\d{1,2})(?::(\\d{2}))?\\s*(?:([ap])\\.?\\s*m\\.?)?(?:\\s*\\(([^)]+)\\)|\\s+([A-Z]{2,5}))?", + "i", +); + /** - * Reads a provider's "try again at 4:30 PM (America/Chicago)" or - * "resets 2am (UTC)" wording as the next matching wall-clock instant after - * `now`. A clock without a time zone is read as UTC. + * Reads a provider's "try again at 4:30 PM (America/Chicago)", "resets 2am + * (UTC)" or "resets Nov 12, 6pm (UTC)" wording. A clock alone is the next + * matching wall-clock instant after `now`; a calendar date is its occurrence + * nearest `now`, which is in the past when the reset already passed. A clock + * without a time zone is read as UTC. */ export function parseProviderQuotaClockReset(error: string, now: Date) { - const match = error.match( - /(?:try again at|resets?(?:\s+at)?)\s+(\d{1,2})(?::(\d{2}))?\s*(?:([ap])\.?\s*m\.?)?(?:\s*\(([^)]+)\)|\s+([A-Z]{2,5}))?/i, - ); + const match = error.match(RESET_PATTERN); if (!match) return null; - const hourValue = Number.parseInt(match[1] ?? "", 10); - const minute = Number.parseInt(match[2] ?? "0", 10); - const meridiem = (match[3] ?? "").toLowerCase(); + const monthIndex = match[1] ? MONTHS.indexOf(match[1].slice(0, 3).toLowerCase()) : null; + const dayOfMonth = match[2] ? Number.parseInt(match[2], 10) : null; + if (monthIndex !== null && (monthIndex < 0 || !dayOfMonth || dayOfMonth < 1 || dayOfMonth > 31)) return null; + const hourValue = Number.parseInt(match[3] ?? "", 10); + const minute = Number.parseInt(match[4] ?? "0", 10); + const meridiem = (match[5] ?? "").toLowerCase(); if (!Number.isInteger(hourValue)) return null; if ( meridiem ? hourValue < 1 || hourValue > 12 : hourValue < 0 || hourValue > 23 @@ -21,14 +33,7 @@ export function parseProviderQuotaClockReset(error: string, now: Date) { let hour = meridiem ? hourValue % 12 : hourValue; if (meridiem === "p") hour += 12; - const timeZone = (match[4] ?? match[5])?.trim(); - if (!timeZone) { - const retryAt = new Date(now); - retryAt.setUTCHours(hour, minute, 0, 0); - if (retryAt.getTime() <= now.getTime()) - retryAt.setUTCDate(retryAt.getUTCDate() + 1); - return retryAt; - } + const timeZone = (match[6] ?? match[7])?.trim() || "UTC"; try { const wallClock = (date: Date) => @@ -46,18 +51,13 @@ export function parseProviderQuotaClockReset(error: string, now: Date) { .map((part) => [part.type, part.value]), ); const nowParts = wallClock(now); - const buildRetryAt = (dayOffset: number) => { - const targetDay = new Date( - Date.UTC( - Number(nowParts.year), - Number(nowParts.month) - 1, - Number(nowParts.day) + dayOffset, - hour, - minute, - ), - ); - let candidate = targetDay; - const targetMs = targetDay.getTime(); + // The instant whose wall clock in `timeZone` reads this date and time. + const instant = (year: number, month: number, day: number) => { + const target = new Date(Date.UTC(year, month, day, hour, minute)); + // Reject dates that overflow, such as Nov 31. + if (monthIndex !== null && target.getUTCDate() !== day) return null; + let candidate = target; + const targetMs = target.getTime(); for (let attempt = 0; attempt < 4; attempt += 1) { const actual = wallClock(candidate); const actualMs = Date.UTC( @@ -73,8 +73,23 @@ export function parseProviderQuotaClockReset(error: string, now: Date) { } return candidate; }; - const sameDay = buildRetryAt(0); - return sameDay.getTime() > now.getTime() ? sameDay : buildRetryAt(1); + const year = Number(nowParts.year); + if (monthIndex !== null && dayOfMonth !== null) { + // The occurrence of that date nearest `now`: "resets Jan 2" read on + // Dec 30 is next year's. A date read after it passed stays in the past, + // so a caller reading an old message sees an expired reset rather than + // one a year away. + const candidates = [year - 1, year, year + 1] + .map((candidateYear) => instant(candidateYear, monthIndex, dayOfMonth)) + .filter((candidate): candidate is Date => candidate !== null); + if (!candidates.length) return null; + return candidates.reduce((nearest, candidate) => + Math.abs(candidate.getTime() - now.getTime()) < Math.abs(nearest.getTime() - now.getTime()) ? candidate : nearest); + } + const month = Number(nowParts.month) - 1; + const day = Number(nowParts.day); + const sameDay = instant(year, month, day)!; + return sameDay.getTime() > now.getTime() ? sameDay : instant(year, month, day + 1); } catch { return null; } diff --git a/server/src/services/recovery/provider-failure-classification.test.ts b/server/src/services/recovery/provider-failure-classification.test.ts index ce7da72da9f..d072b3d93a5 100644 --- a/server/src/services/recovery/provider-failure-classification.test.ts +++ b/server/src/services/recovery/provider-failure-classification.test.ts @@ -111,6 +111,17 @@ describe("classifyAdapterFailureForRecovery", () => { }); }); + it("releases the wait when an unchanged weekly-limit failure is reread after its calendar reset", () => { + // Read two days after "resets Nov 12": the wait is over, not a year away. + const now = new Date("2026-11-14T10:00:00.000Z"); + const classification = classifyAdapterFailureForRecovery({ + errorCode: "adapter_failed", + error: "You've hit your weekly limit · resets Nov 12, 6pm (UTC)", + resultJson: null, + }, now); + expect(classification).toEqual({ kind: "provider_quota", retryAt: now, parsedResetTime: true }); + }); + it("uses the default recovery backoff when quota reset time is absent", () => { const now = new Date("2026-07-15T20:00:00.000Z"); const classification = classifyAdapterFailureForRecovery({ diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 4cadaea1b47..4456079b96f 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -676,7 +676,8 @@ export function classifyAdapterFailureForRecovery( if (parsedClockReset) { return { kind: "provider_quota", - retryAt: parsedClockReset, + // A calendar reset read after it passed has released the wait. + retryAt: parsedClockReset > now ? parsedClockReset : now, parsedResetTime: true, }; } diff --git a/server/src/services/task-retry.ts b/server/src/services/task-retry.ts index 72050465f52..4525c5986c7 100644 --- a/server/src/services/task-retry.ts +++ b/server/src/services/task-retry.ts @@ -224,12 +224,20 @@ export async function retireSupersededTaskRetry(db: Db, input: { type TaskRetryRequest = { db: Db; companyId: string; issueId: string; actorId: string; idempotencyKey: string; observedRunId: string | null; actorSource?: string; - /** Paperclip requests the user's Retry itself after a restart lost an unstarted turn. */ - initiatedBy?: "restart_recovery"; + /** Paperclip requests the user's Retry itself: after a restart lost an + * unstarted turn, or once a provider usage limit it waited on has reset. */ + initiatedBy?: "restart_recovery" | "provider_limit_reset"; prepareChatRetry?: (tx: Db, scope: { companyId: string; issueId: string; agentId: string; failedRunId: string; initiatedByUserId: string; retryIntentId?: string }) => Promise<{ actionId: string }>; }; +/** Activity actor for a Retry: the user, or the Paperclip hook acting for them. */ +function automaticRetryActor(input: Pick) { + if (!input.initiatedBy) return { actorType: "user" as const, actorId: input.actorId }; + return { actorType: "system" as const, + actorId: input.initiatedBy === "restart_recovery" ? "restart-recovery" : "provider-limit-reset" }; +} + const TASK_RETRY_CONTENTION_ATTEMPTS = 10; const TASK_RETRY_CONTENTION_DELAY_MS = 100; @@ -324,13 +332,11 @@ function admitTaskRetry(input: TaskRetryRequest) { source: "on_demand", triggerDetail: "manual", reason: "task_retry", idempotencyKey: key, requestedByActorType: "user", requestedByActorId: input.actorId, ...settled, payload: { issueId: issue.id, taskRetry: finalizeIntent } }); - const restartRecovery = input.initiatedBy === "restart_recovery"; - await persistActivity(db, { companyId: issue.companyId, actorType: restartRecovery ? "system" : "user", - actorId: restartRecovery ? "restart-recovery" : input.actorId, + await persistActivity(db, { companyId: issue.companyId, ...automaticRetryActor(input), action: "issue.retry_requested", entityType: "issue", entityId: issue.id, runId: latest.id, details: { requestId: canonicalId ?? finalizeId, sourceRunId: latest.id, attachedToExistingWork: Boolean(canonicalId), strategy: "finalize_result", - ...(restartRecovery ? { initiatedBy: "restart_recovery", onBehalfOfUserId: input.actorId } : {}) } }); + ...(input.initiatedBy ? { initiatedBy: input.initiatedBy, onBehalfOfUserId: input.actorId } : {}) } }); const finalizing = savedResult.kind === "rearmed" || savedResult.finalizing; return { requestId: canonicalId ?? finalizeId, accepted: true, stale: false, observedRunId: latest.id, chatActionId: undefined, ...(finalizing ? { finalizeRunId: latest.id } : {}) }; @@ -371,10 +377,10 @@ function admitTaskRetry(input: TaskRetryRequest) { // A new deliberate click (new key) replaces it with a fresh attempt under the // clicker's current authority instead of joining it. Waits on shared state // (cleanup, recovery, an active run) keep coalescing: that intent starts by - // itself once the gate clears. The restart hook never replaces a user's click. + // itself once the gate clears. An automatic hook never replaces a user's click. let replacedRequestId: string | undefined; if (active && !busy && !active.runId && active.status === "deferred_issue_execution" && - input.initiatedBy !== "restart_recovery" && activeIntent && !activeIntent.chatActionId && + !input.initiatedBy && activeIntent && !activeIntent.chatActionId && !activeIntent.queuedChatRequestId && isDeclinedTaskRetry(active.payload)) { await tx.update(agentWakeupRequests).set({ status: "skipped", error: "task_retry_replaced", finishedAt: new Date(), updatedAt: new Date() }).where(and(eq(agentWakeupRequests.id, active.id), @@ -462,13 +468,11 @@ function admitTaskRetry(input: TaskRetryRequest) { actionId: action.id }, previous, next); } } - const restartRecovery = input.initiatedBy === "restart_recovery"; - await persistActivity(db, { companyId: issue.companyId, actorType: restartRecovery ? "system" : "user", - actorId: restartRecovery ? "restart-recovery" : input.actorId, + await persistActivity(db, { companyId: issue.companyId, ...automaticRetryActor(input), action: "issue.retry_requested", entityType: "issue", entityId: issue.id, runId: latest.id, details: { requestId: active?.id ?? id, sourceRunId: latest.id, attachedToExistingWork: Boolean(active || busy), ...(replacedRequestId ? { replacedRequestId } : {}), - ...(restartRecovery ? { initiatedBy: "restart_recovery", onBehalfOfUserId: input.actorId } : {}) } }); + ...(input.initiatedBy ? { initiatedBy: input.initiatedBy, onBehalfOfUserId: input.actorId } : {}) } }); return { requestId: active?.id ?? id, accepted: true, stale: false, observedRunId: latest.id, chatActionId: intent.chatActionId, ...(!active && latest.status === "scheduled_retry" ? { scheduledRetryRunId: latest.id } : {}) }; From ce3881f1b3f20337ddfc698380552f11e49ac579 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:59:49 -0600 Subject: [PATCH 22/38] fix(skills): release a skill cache lock whose holder's deployment was replaced (#20688) 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 > - Run preparation publishes skill revisions into a shared runtime skill cache. A file lock serializes each publication. A lock whose holder provably exited is released at once. > - That check used `controllerProcessExited`, a PID proof. It fails closed whenever the recorded process space (host, kernel boot, PID namespace) differs from this server's. > - Every Railway deploy starts the server in a new process space. A lock left by a server that a deploy stopped mid-publish can never be released. Each later preparation of that skill waits 60 s and fails with "Runtime skill cache publisher is busy … remove it", until an operator deletes the file. > - The rest of recovery already uses one shared prover (`proveOwnerGone`). Across process spaces it accepts a replaced platform deployment on the same exclusive volume, or a stopped or fenced server boot. > - This pull request makes the skill cache lock use that prover. It was the last caller of the separate PID-only proof. > - The benefit is one rule for "the controller from a previous deployment is provably gone", and no manual file removal after a deploy. ## Linked Issues or Issue Description **What happened?** A census of staging failures after deploys showed that `controllerProcessExited` always fails closed after a deploy, because the process-space hash changes. On `master`, the only remaining caller is the runtime skill cache lock check. The restart chaos harness restarts in the same process space, so the PID proof succeeded there and hid the gap. I did not find this failure in the staging run census. It is a latent dead end with the same cause as the census class. **Expected behavior** A lock whose holder ran in a deployment that the platform replaced on the same exclusive volume, or whose server boot stopped or was fenced, is released at once. Any other holder is still waited for. **Steps to reproduce** 1. Run the server on Railway with a volume. 2. Redeploy while a skill revision is being published (the lock file exists). 3. Prepare a run that needs the same skill revision on the new deployment. 4. Observe a 60 s wait and `Runtime skill cache publisher is busy; retry preparation.` on every attempt. **Paperclip version or commit** `master` at `c444da7d05` (the new test fails there). ## What Changed - `server/src/services/runtime-skill-cache.ts`: `runtimeSkillCacheLockHolderExited` builds a local owner stamp from the recorded controller (boot ID, PID, process space, start time, and the Railway deployment and volume when recorded). It returns true only for the `gone` verdict of `proveOwnerGone`. - Same-space PID rules do not change. A dead PID is gone, a live PID with no start time is unprovable, and this server's own boot is alive. - `server/src/__tests__/runtime-skill-cache.test.ts`: a new test for a holder in another process space whose deployment the platform replaced. - The proof is bounded by the lock wait (5 s, never past the deadline). A timed-out or failed proof keeps the lock held. A proof still running is joined by later waits on the same holder, so a stalled read adds at most one database query per holder. - `server/src/services/controller-process-identity.ts`: removes `controllerProcessExited`, which has no caller left; its test assertions now check `sameProcessSpace`. ## Verification - `npx vitest run src/__tests__/runtime-skill-cache.test.ts src/services/controller-process-space-identity.test.ts` (from `server/`): 31 passed. - New: "releases a lock whose holder ran in a deployment the platform replaced". It fails on `master` (`expected false to be true`) and passes with this change. - The same test keeps the lock held for: the same deployment ID, another volume, a non-exclusive volume, another service, and no recorded deployment. - The existing test "never treats age, another host, or a legacy holder as proof that a lock holder exited" still passes. Without a deployment or controller lease proof, another host stays held. - `npx tsc --noEmit -p server/tsconfig.json` passes. - `pnpm verify` selected 2504 of 3294 test files (the change reaches `owner-proof.ts` importers) and hit my 30 min local limit with no failure seen. Required CI supplies the broad coverage. - Live proof: not done (tests only). ## Risks - Across process spaces, a held lock can now trigger a read of `controller_instances` for the holder's boot. This happens at most once per second, and only while a lock is held. Uncontended preparation does no extra work. - The prover may fence a boot row whose lease lapsed past its grace, as it already does for every other recorded owner. - No persisted shape changes. Older lock files without a `controller` field stay held, as before. > 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, used through Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- .../src/__tests__/runtime-skill-cache.test.ts | 56 +++++++++++++++++++ .../services/controller-process-identity.ts | 14 ----- .../controller-process-space-identity.test.ts | 11 +--- server/src/services/runtime-skill-cache.ts | 54 +++++++++++++++--- 4 files changed, 105 insertions(+), 30 deletions(-) diff --git a/server/src/__tests__/runtime-skill-cache.test.ts b/server/src/__tests__/runtime-skill-cache.test.ts index ab63e868ac4..d03475037a5 100644 --- a/server/src/__tests__/runtime-skill-cache.test.ts +++ b/server/src/__tests__/runtime-skill-cache.test.ts @@ -187,6 +187,62 @@ describe("runtime skill revision cache", () => { expect(await runtimeSkillCacheLockHolderExited(Buffer.from("not json"))).toBe(false); }); + it("releases a lock whose holder ran in a deployment the platform replaced", async () => { + // A Railway redeploy starts the server in a new process space, so a PID + // proof never applies. The platform stopped the earlier deployment, which + // held the same exclusive volume, before it started this one. + const railway = { RAILWAY_PROJECT_ID: "project", RAILWAY_ENVIRONMENT_ID: "environment", RAILWAY_SERVICE_ID: "service", + RAILWAY_DEPLOYMENT_ID: "deployment-new", RAILWAY_VOLUME_ID: "volume", RAILWAY_VOLUME_MOUNT_PATH: "/data" }; + for (const [key, value] of Object.entries(railway)) vi.stubEnv(key, value); + try { + const worker = { provider: "railway", projectId: "project", environmentId: "environment", serviceId: "service" }; + const holder = { bootId: randomUUID(), pid: 3, hostHash: "f".repeat(32), processStartedAt: null, + deployment: { worker: { ...worker, deploymentId: "deployment-old" }, exclusiveVolume: true, volumeId: "volume" } }; + expect(await runtimeSkillCacheLockHolderExited(lockStamp(holder))).toBe(true); + // Only a replaced deployment on the same exclusive volume is proof. + const deployment = holder.deployment; + for (const changed of [{ ...deployment, worker: { ...worker, deploymentId: "deployment-new" } }, + { ...deployment, volumeId: "another-volume" }, { ...deployment, exclusiveVolume: false }, + { ...deployment, worker: { ...worker, serviceId: "another-service", deploymentId: "deployment-old" } }]) { + expect(await runtimeSkillCacheLockHolderExited(lockStamp({ ...holder, deployment: changed }))).toBe(false); + } + const { deployment: _omitted, ...withoutDeployment } = holder; + expect(await runtimeSkillCacheLockHolderExited(lockStamp(withoutDeployment))).toBe(false); + } finally { + vi.unstubAllEnvs(); + } + }); + + it("keeps a lock held when the holder proof stalls or fails", async () => { + // A distinct holder per case: a still-pending proof is joined by later waits on the same holder. + const holder = () => ({ bootId: randomUUID(), pid: 3, hostHash: "f".repeat(32), processStartedAt: null }); + const startedAt = Date.now(); + expect(await runtimeSkillCacheLockHolderExited(lockStamp(holder()), + { timeoutMs: 50, prove: () => new Promise(() => {}) })).toBe(false); + expect(Date.now() - startedAt).toBeLessThan(2_000); + expect(await runtimeSkillCacheLockHolderExited(lockStamp(holder()), + { prove: async () => { throw new Error("database unavailable"); } })).toBe(false); + expect(await runtimeSkillCacheLockHolderExited(lockStamp(holder()), + { prove: async () => ({ verdict: "gone", reason: "controller_stopped" }) })).toBe(true); + }); + + it("joins a stalled holder proof instead of starting another read on every timeout", async () => { + const holder = { bootId: randomUUID(), pid: 3, hostHash: "f".repeat(32), processStartedAt: null }; + let settle!: (proof: { verdict: "gone"; reason: "controller_stopped" }) => void; + const prove = vi.fn(() => new Promise<{ verdict: "gone"; reason: "controller_stopped" }>(resolve => { settle = resolve; })); + for (let attempt = 0; attempt < 5; attempt++) { + expect(await runtimeSkillCacheLockHolderExited(lockStamp(holder), { timeoutMs: 10, prove })).toBe(false); + } + expect(prove).toHaveBeenCalledTimes(1); + settle({ verdict: "gone", reason: "controller_stopped" }); + expect(await runtimeSkillCacheLockHolderExited(lockStamp(holder), { timeoutMs: 1_000, prove })).toBe(true); + // A settled proof is not reused: the next wait asks again. + await new Promise(resolve => setImmediate(resolve)); + const fresh = vi.fn(async () => ({ verdict: "alive" as const, reason: "controller_lease_held" as const })); + expect(await runtimeSkillCacheLockHolderExited(lockStamp(holder), { prove: fresh })).toBe(false); + expect(fresh).toHaveBeenCalledTimes(1); + }); + it("fingerprints installed content and ownership, excluding cosmetic metadata", async () => { const spec = runtimeSkillCacheSpec(root, skill)!; expect(runtimeSkillCacheSpec(root, { ...skill, name: "Renamed", updatedAt: new Date(), metadata: { ...skill.metadata, starred: true, ref: "new-branch" } })!.fingerprint).toBe(spec.fingerprint); diff --git a/server/src/services/controller-process-identity.ts b/server/src/services/controller-process-identity.ts index 338c7485b60..a5649a2f51a 100644 --- a/server/src/services/controller-process-identity.ts +++ b/server/src/services/controller-process-identity.ts @@ -200,20 +200,6 @@ export function processStartsDefinitelyDiffer( return Number.isFinite(left) && Number.isFinite(right) && Math.abs(left - right) >= PROCESS_START_PRECISION_MS; } -/** True only with proof, in this process's own PID space, that the recorded - * server process has exited. Another space, an unreadable space, this server, - * or an ambiguous live PID returns false. */ -export async function controllerProcessExited(controller: ControllerProcess): Promise { - if (controller.bootId === bootId || hostHash === UNKNOWN_PROCESS_SPACE || controller.hostHash !== hostHash) return false; - if (!processExists(controller.pid)) return true; - // Without a recorded start time a live PID can never prove exit; skip the probe. - if (!Number.isFinite(Date.parse(controller.processStartedAt ?? ""))) return false; - // The PID now belongs to a live process, possibly this restarted server. - // Only a definitely different start time proves the recorded process is gone. - const observed = await observedProcessStartedAt(controller.pid); - return observed !== null && processStartsDefinitelyDiffer(controller.processStartedAt, new Date(observed)); -} - /** This process's PID-space hash. An unreadable space is stored as * "unknown", which `sameProcessSpace` never accepts. */ export function currentProcessSpaceHash(): string { diff --git a/server/src/services/controller-process-space-identity.test.ts b/server/src/services/controller-process-space-identity.test.ts index bbf3b9046f4..858e7bef487 100644 --- a/server/src/services/controller-process-space-identity.test.ts +++ b/server/src/services/controller-process-space-identity.test.ts @@ -50,10 +50,8 @@ describe("controller process-space identity", () => { expect(state.sysctl).toHaveBeenCalledTimes(2); expect(JSON.stringify(first)).not.toContain(firstBoot); // Old weak/foreign receipts retain their original deadline: no local probe. - const kill = vi.spyOn(process, "kill"); - expect(await owner.controllerProcessExited({ bootId: "old", pid: 2_000_000_001, - hostHash: "old-rounded-clock-hash", processStartedAt: null })).toBe(false); - expect(kill).not.toHaveBeenCalled(); + expect(owner.sameProcessSpace("old-rounded-clock-hash")).toBe(false); + expect(owner.sameProcessSpace(first.hostHash)).toBe(true); }); it.each(["unreadable", "malformed", "unsupported"] as const)("fails closed without an owner PID probe for %s identity", async mode => { @@ -62,10 +60,7 @@ describe("controller process-space identity", () => { if (mode === "malformed") state.sysctl.mockReturnValue("not-a-kernel-uuid"); const owner = await fresh(); expect((await owner.currentControllerProcess()).hostHash).toBe("unknown"); - const kill = vi.spyOn(process, "kill"); - expect(await owner.controllerProcessExited({ bootId: "old", pid: 2_000_000_001, - hostHash: "unknown", processStartedAt: null })).toBe(false); - expect(kill).not.toHaveBeenCalled(); + expect(owner.sameProcessSpace("unknown")).toBe(false); if (mode === "unsupported") expect(state.sysctl).not.toHaveBeenCalled(); }); }); diff --git a/server/src/services/runtime-skill-cache.ts b/server/src/services/runtime-skill-cache.ts index 7c9cef9d7b3..0366a774c37 100644 --- a/server/src/services/runtime-skill-cache.ts +++ b/server/src/services/runtime-skill-cache.ts @@ -3,7 +3,11 @@ import { constants, promises as fs } from "node:fs"; import os from "node:os"; import path from "node:path"; import type { CompanySkill } from "@paperclipai/shared"; -import { controllerProcessExited, currentControllerProcessStamp, readControllerProcess } from "./controller-process-identity.js"; +import { currentControllerProcessStamp, readControllerProcess } from "./controller-process-identity.js"; +import { proveOwnerGone, type LocalOwnerStamp, type OwnerProof } from "./owner-proof.js"; + +/** Bounds one lock-holder proof, which can read the database across process spaces. */ +const LOCK_PROOF_TIMEOUT_MS = 5_000; const FORMAT = 1; const inFlight = new Map>(); @@ -114,18 +118,51 @@ async function matches(spec: CacheSpec, entry = spec.entry): Promise { } /** - * True only when a lock holder's recorded server process has provably exited - * in this PID space. Lock age is never proof. A holder on another host or PID - * namespace, an unreadable space, or a lock written before holders recorded - * their process identity stays held. + * True only when the shared owner prover shows that a lock holder's recorded + * server process is gone. Lock age is never proof. In this PID space the PID + * decides. A holder in another process space (for example before a redeploy) + * is gone only when the platform replaced its deployment on the same exclusive + * volume, or when its server boot stopped or was fenced. A lock written before + * holders recorded their process identity stays held. */ -export async function runtimeSkillCacheLockHolderExited(lockContent: Buffer): Promise { +export async function runtimeSkillCacheLockHolderExited(lockContent: Buffer, options: { + /** This wait gives up (the lock stays held) after this long. A stalled read keeps running; later waits on the same holder join it. */ + timeoutMs?: number; + prove?: (stamp: LocalOwnerStamp) => Promise; +} = {}): Promise { let holder: unknown; try { holder = JSON.parse(lockContent.toString("utf8")); } catch { return false; } const controller = readControllerProcess((holder as { controller?: unknown } | null)?.controller); - return controller !== null && await controllerProcessExited(controller); + if (!controller) return false; + const stamp: LocalOwnerStamp = { + kind: "local", scope: "runtime_skill_cache_lock", generation: null, host: null, processSpace: controller.hostHash, + bootId: controller.bootId, pid: controller.pid, processStartedAt: controller.processStartedAt, processGroupId: null, + ...(controller.deployment ? { worker: controller.deployment.worker, exclusiveVolume: controller.deployment.exclusiveVolume, + volumeId: controller.deployment.volumeId } : {}), + }; + // A proof that outlives its timeout keeps running (its database read cannot + // be cancelled), so later waits on the same holder join it instead of adding + // another read to the shared pool. + const key = JSON.stringify(stamp); + let proved = pendingLockProofs.get(key); + if (!proved) { + proved = (options.prove ?? (value => proveOwnerGone(value)))(stamp) + .then(proof => proof.verdict === "gone", () => false) + .finally(() => { if (pendingLockProofs.get(key) === proved) pendingLockProofs.delete(key); }); + pendingLockProofs.set(key, proved); + } + let timer: NodeJS.Timeout | undefined; + const timedOut = new Promise(resolve => { timer = setTimeout(() => resolve(false), options.timeoutMs ?? LOCK_PROOF_TIMEOUT_MS); }); + try { + return await Promise.race([proved, timedOut]); + } finally { + clearTimeout(timer); + } } +/** Lock-holder proofs still running, by holder stamp; at most one per holder. */ +const pendingLockProofs = new Map>(); + const OWNER_TOKEN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; function lockHolderToken(lockContent: Buffer): string | null { @@ -221,7 +258,8 @@ async function publishLocked(root: string, fingerprint: string, action: () => const due = judged === null || judged.inode !== held.inode || Date.now() - judged.at >= 1_000; if (holderToken && due) { judged = { inode: held.inode, at: Date.now() }; - if (await runtimeSkillCacheLockHolderExited(held.content)) { + if (await runtimeSkillCacheLockHolderExited(held.content, + { timeoutMs: Math.max(1, Math.min(LOCK_PROOF_TIMEOUT_MS, deadline - Date.now())) })) { await releaseExitedRuntimeSkillCacheLock(root, lock, { inode: held.inode, token: holderToken }); continue; } From d79b7f29f2695651004b3755c5fc44d6970f46bd Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 21:10:28 -0600 Subject: [PATCH 23/38] fix(heartbeat): bind queued card-answer interrupts to the delivered answer (#20698) 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 > - A person can queue direction while a task's run is active, then use Interrupt to stop the run and start a successor that receives the direction > - The queued direction can be an answer to a card, for example an accepted confirmation of a saved plan > - `explicitOperatorRunIdentity` verifies the click from the coalesced queue receipt before the successor run can start > - That check required comment ids in the receipt, but a card answer carries its interaction and no comment ids > - So every claim of the successor failed with 403, and the direction never reached a run > - This pull request binds a card-answer receipt to the answer that the successor run delivers, and to the user who gave it > - The benefit is that Interrupt works for queued card answers, and the operator identity stays verified ## Linked Issues or Issue Description Refs #14043, #14510 **What happened** A person accepted a `request_confirmation` card on a task while its run was active, and then clicked Interrupt. The active run stopped ("Interrupted to send queued messages"). The successor run was then cancelled with "Cancelled because the queued run cannot be claimed: Queued-message interrupt authority is unavailable". The coalesced receipt had the interaction id and no `queuedCommentIds`. The successor run's context had the same `interactionId` and the receipt id in `queuedCommentSourceWakeIds`. The chat eval `steering.interrupt-with-direction` recorded this. **Expected behavior** The successor run starts, receives the accepted direction once, and runs with the clicking user as its responsible user. A receipt that the run does not deliver, or an answer that another user gave, still fails closed. **Steps to reproduce** 1. Start a run on a task. 2. While the run is active, accept a confirmation card on that task. The answer goes into the deferred queue. 3. Click Interrupt for the queued messages. 4. Before this change, the successor run is cancelled with `queued_run_claim_rejected`. ## What Changed - `server/src/services/run-identity.ts`: the shared receipt binding (consumed `coalesced` receipt for the same company, agent and run; same task; `user` request from the marker's actor) runs first, as before. Then: - A receipt with comment ids keeps the existing rule: all ids must be delivered to the run. - A receipt without comment ids must be a queued card answer (`queuedInteractionId`). The run context must deliver the same `interactionId`. The interaction must be on the same company and task, with the receipt's status, and `resolvedByUserId` must be the clicking user. Then the run gets the operator identity (`queued_comment_interrupt`). Otherwise the claim still fails with 403. - `server/src/__tests__/heartbeat-queued-run-claim-isolation.test.ts`: a successor of a card-answer interrupt is claimed, runs, and has the clicking user as responsible user. Two negative cases: the run delivers a different answer, and another user resolved the answer. Both stay rejected. Relation to #14510: that open PR fixes the same claim failure (#14043) by returning `null` for card-answer receipts, so the run starts without the operator identity. Its Risks section notes that keeping the operator identity needs a check that the actor resolved the interaction. This PR adds that check instead, so the successor keeps the identity that enqueue time records. If maintainers prefer #14510's approach, this PR's regression test still applies to it. ## Verification - `cd server && npx vitest run src/__tests__/heartbeat-queued-run-claim-isolation.test.ts`: the new positive test fails before the change (successor cancelled) and passes after it. The negative tests and the existing tests pass. - Suites that cover interrupt identity, each run separately: `run-identity` (37), `heartbeat-responsible-user-invariant` (18), `issue-queued-comments-routes` (129), `deferred-execution-receipt-work` (50), `task-interruption-query` (31), `explicit-native-continuation` (436), `run-cancellation` (8), `workspace-recovery-admission` (147), `wake-queue/adapters/postgres` (113): all pass. In `heartbeat-process-recovery`, the interrupt-named tests pass except `dispatches interrupted CLI input and cleans up early fixture exits`, which fails before any interrupt (the CLI child does not start: `controller_lease_lost`). It fails the same way on unchanged master on this loaded host (3 of 3 attempts failed at least one case), so it is not caused by this change. CI covers it. - `server` `tsc --noEmit`: no errors in the changed files. - Live chat eval `chat-features.runner-opencode.local.steering.interrupt-with-direction` at this branch (run 42938970466): passed. The old run stopped with "Interrupted to send queued messages". Exactly one successor run started, delivered the accepted card answer, ran with the clicking user as responsible user, and saved the approved single page and its delivery document. Before this change, the same case failed with the successor cancelled as `queued_run_claim_rejected`. ## Risks - Low risk. The change adds a verified path only for receipts that previously always failed. Comment receipts keep their checks. - If a different user answered the card than the user who clicked Interrupt, the claim still fails. The person who answered can click Interrupt. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] 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 --- ...artbeat-queued-run-claim-isolation.test.ts | 57 +++++++++++++++++++ server/src/services/run-identity.ts | 28 +++++++-- 2 files changed, 80 insertions(+), 5 deletions(-) diff --git a/server/src/__tests__/heartbeat-queued-run-claim-isolation.test.ts b/server/src/__tests__/heartbeat-queued-run-claim-isolation.test.ts index ab100717603..b5fc8e27060 100644 --- a/server/src/__tests__/heartbeat-queued-run-claim-isolation.test.ts +++ b/server/src/__tests__/heartbeat-queued-run-claim-isolation.test.ts @@ -11,6 +11,7 @@ import { heartbeatRuns, externalAgentHolds, issues, + issueThreadInteractions, } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, @@ -294,6 +295,62 @@ describeEmbeddedPostgres("heartbeat queued-run claim isolation", () => { expect(mockAdapterExecute).toHaveBeenCalledOnce(); }); + async function insertCardAnswerInterruptRun(fault?: "other-answer" | "other-resolver") { + const { companyId, agentId } = await insertAgent(); + const userId = `card-owner-${randomUUID()}`; + await db.insert(authUsers).values({ id: userId, name: "Card owner", email: `${userId}@paperclip.test`, + createdAt: new Date(), updatedAt: new Date() }); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: userId, + status: "active", membershipRole: "owner" }); + const issueId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Website", status: "in_progress", + assigneeAgentId: agentId, responsibleUserId: userId }); + const [interaction] = await db.insert(issueThreadInteractions).values({ companyId, issueId, + kind: "request_confirmation", status: "accepted", payload: { version: 1, prompt: "Use the simpler layout?" }, + result: { version: 1, outcome: "accepted" }, createdByUserId: userId, + resolvedByUserId: fault === "other-resolver" ? "another-user" : userId, resolvedAt: new Date() }).returning(); + const queueId = randomUUID(); + const { runId, wakeupRequestId } = await insertQueuedRun(companyId, agentId, { + reason: "issue_commented", + idempotencyKey: `queued-comment-interrupt:${queueId}`, + requestedByActorType: "user", + requestedByActorId: userId, + payload: { issueId, interactionId: interaction!.id, explicitUserContinuation: { queuedCommentInterruptId: queueId } }, + }, new Date(Date.now() - 60_000)); + await db.insert(agentWakeupRequests).values({ id: queueId, companyId, agentId, source: "automation", + triggerDetail: "system", reason: "issue_commented", status: "coalesced", runId, + requestedByActorType: "user", requestedByActorId: userId, + payload: { issueId, mutation: "interaction", interactionId: interaction!.id, interactionKind: "request_confirmation", + interactionStatus: "accepted", queuedCommentInterrupt: { actorId: userId, requestedAt: new Date().toISOString() } } }); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId, taskId: issueId, + interactionId: fault === "other-answer" ? randomUUID() : interaction!.id, interactionKind: "request_confirmation", + interactionStatus: "accepted", queuedCommentSourceWakeIds: [queueId] } }).where(sql`${heartbeatRuns.id} = ${runId}`); + return { runId, wakeupRequestId, userId }; + } + + it("claims the successor of an interrupt that delivers a queued card answer", async () => { + const { runId, userId } = await insertCardAnswerInterruptRun(); + + await expect(heartbeat.resumeQueuedRuns()).resolves.toBeUndefined(); + await heartbeat.drainActiveRunExecutions(); + + expect(await runStatus(runId)).toMatchObject({ status: "succeeded", errorCode: null }); + const [run] = await db.select({ responsibleUserId: heartbeatRuns.responsibleUserId }).from(heartbeatRuns) + .where(sql`${heartbeatRuns.id} = ${runId}`); + expect(run).toMatchObject({ responsibleUserId: userId }); + }); + + it.each(["other-answer", "other-resolver"] as const)( + "rejects a card-answer interrupt whose %s does not match the receipt", async (fault) => { + const { runId } = await insertCardAnswerInterruptRun(fault); + + await expect(heartbeat.resumeQueuedRuns()).resolves.toBeUndefined(); + + expect(await runStatus(runId)).toMatchObject({ status: "cancelled", errorCode: "queued_run_claim_rejected" }); + expect(mockAdapterExecute).not.toHaveBeenCalled(); + }, + ); + it("keeps processing other agents' queued runs after one agent's run is rejected", async () => { const first = await insertAgent(); const second = await insertAgent(); diff --git a/server/src/services/run-identity.ts b/server/src/services/run-identity.ts index 9b8d845c098..e9ebc3219ed 100644 --- a/server/src/services/run-identity.ts +++ b/server/src/services/run-identity.ts @@ -15,6 +15,7 @@ import { notifyChatRunMilestones } from "./chat-run-milestone-notifications.js"; import { boundRunIssueId, boundRunIssueIdSql, runTaskContextColumn } from "./run-task-binding.js"; import { isUuidLike } from "@paperclipai/shared"; import { queuedCommentIdsFromRunContext, queuedCommentIdsFromWakePayload } from "./issue-queued-comment-queue.js"; +import { queuedInteractionId } from "./queued-interaction-response.js"; /** Resolve an explicit click from persisted receipts, never caller context or message authors. */ export async function explicitOperatorRunIdentity( @@ -46,14 +47,31 @@ export async function explicitOperatorRunIdentity( )); const marker = receipt?.payload?.queuedCommentInterrupt; const actorId = marker && typeof marker === "object" && "actorId" in marker ? marker.actorId : null; - const ids = queuedCommentIdsFromWakePayload(receipt?.payload); - const deliveredIds = queuedCommentIdsFromRunContext(run.contextSnapshot); - if (typeof actorId !== "string" || !actorId || !ids.length || - receipt?.payload?.issueId !== run.contextSnapshot?.issueId || - !ids.every(id => deliveredIds.includes(id)) || + if (typeof actorId !== "string" || !actorId || !receipt || + receipt.payload?.issueId !== run.contextSnapshot?.issueId || request.requestedByActorType !== "user" || request.requestedByActorId !== actorId) { throw forbidden("Queued-message interrupt authority is unavailable"); } + const ids = queuedCommentIdsFromWakePayload(receipt.payload); + if (!ids.length) { + const interactionId = queuedInteractionId(receipt.payload); + const [interaction] = interactionId && run.contextSnapshot?.interactionId === interactionId + ? await executor.select({ resolvedByUserId: issueThreadInteractions.resolvedByUserId }) + .from(issueThreadInteractions).where(and( + eq(issueThreadInteractions.id, interactionId), eq(issueThreadInteractions.companyId, run.companyId), + eq(issueThreadInteractions.issueId, String(run.contextSnapshot.issueId)), + eq(issueThreadInteractions.status, String(receipt.payload?.interactionStatus)), + )) + : []; + if (!interaction || interaction.resolvedByUserId !== actorId) { + throw forbidden("Queued-message interrupt authority is unavailable"); + } + return { actorId, cause: "queued_comment_interrupt" }; + } + const deliveredIds = queuedCommentIdsFromRunContext(run.contextSnapshot); + if (!ids.every(id => deliveredIds.includes(id))) { + throw forbidden("Queued-message interrupt authority is unavailable"); + } return { actorId, cause: "queued_comment_interrupt" }; } From 4baff8322538cd4c7b465b4915b233c85531c3fc Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 21:15:40 -0600 Subject: [PATCH 24/38] fix(chat): never batch messages of two chat conversations into one wake (#20697) 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. > - Chat channels let a linked user talk to an agent from GitHub, Slack and other platforms. Each external thread is a chat conversation. Many conversations can share one task. > - A reviewed chat run attests exactly one conversation. #17054 keeps each conversation in its own wake batch, but it compares only the conversation that a wake records. > - The work-intent outbox saves unanswered user messages as a plain comment wake. That wake records no conversation, even when its messages are chat messages. A wake with no recorded conversation matched every conversation, so a message from another conversation merged into it. > - The promoted run held messages of two conversations. The binding check correctly refused it (`reviewed_chat_execution_binding_not_authorized`, `binding_denied`), and the task needed Retry. > - This pull request compares the conversations of the queued messages themselves. Wakes of different conversations never merge. Each conversation gets its own run, in order. > - The benefit is that replies in several threads of one task each get an attested run, without a failed run or a Retry. ## Linked Issues or Issue Description Refs #17054 (the earlier per-conversation batching fix). Refs #20689 (a different shape of the same error). **What happened?** On staging, a GitHub pull-request review task had two runs fail with `setup_failed` / `reviewed_chat_execution_binding_not_authorized` (`reviewedChatBinding.denialReason: binding_denied`). Each failed run held the same two older saved messages plus one new message. The two runs recorded two different `chatConversationId` values. The work-intent outbox had saved the older messages as plain deferred wakes with no conversation. A new message from each conversation then merged into one of these saved wakes. **Steps to reproduce** 1. Bind two chat conversations to one `in_review` task. 2. Let the outbox save an unanswered message of conversation B as a deferred wake while a run is active. 3. As the linked user, send a message in conversation A while the run is still active. 4. See that the message of A merges into the saved wake of B. The promoted run fails the binding check. **Expected behavior** The saved message of B runs as its own wake. The message of A runs after it, in its own attested run. ## What Changed - New `server/src/modules/wake-queue/adapters/chat-conversation-batch.ts`: reads the inbound chat links (`chat_message_links`, direction `inbound`) of queued messages and finds messages of a conversation other than the expected one. - Deferred-wake lookup (`findExistingDeferredWake`): when the incoming wake has a conversation, a saved wake qualifies only if none of its queued messages is an inbound message of another conversation. This is one more predicate in the same query (no new round trip). It uses the existing `chat_message_links_company_comment_idx` index. - Coalescing into the active run (`coalesceIntoActiveExecutionRun`): returns no merge when the merged batch would hold messages of a conversation other than the one it records. The wake is then saved behind the run, which is the existing fallback. - Release drain (`findNextDeferredWake`), upgrade repair: a saved chat wake that older code already merged across two conversations is split. The other conversation's messages move to a plain saved wake (the outbox shape), ordered just before it. The original wake keeps its conversation and its own messages. The drain then reads the queue again. - `doc/execution-semantics.md`: describe the comparison and the upgrade repair. - New test `chat-wake-conversation-batch.test.ts` (embedded Postgres, real admission and release code, real `authorizeChatConversationForBoundRun`). ## Verification - Red on `origin/master` (test file only): `pnpm --dir server exec vitest run src/modules/wake-queue/adapters/chat-wake-conversation-batch.test.ts` gives 4 failed, 6 passed. The 4 failures are the bug: the new message merges into the other conversation's saved wake (`[[earlier, reply]]`), two conversations cross-merge, a message coalesces into a queued run of another conversation, and the old merged shape stays merged. The 6 passing cases pin unchanged batching. - Green with the fix: 10 of 10 pass. Each separated wake passes `authorizeChatConversationForBoundRun` for its own conversation. The old merged shape fails it with `paperclip_runner_chat_attachment_binding_denied` before the split. - Batching that stays the same (pinned, pass before and after): comment wakes with no conversation merge; messages of one conversation merge; an outbox-saved wake of the same conversation still absorbs the reply; a chat message and plain comments merge in both orders; same-conversation messages still coalesce into a queued run; two recorded conversations stay apart. - Related suites pass locally: `src/modules/wake-queue`, `src/modules/run-dispatch`, `chat-run-milestone-work`, `durable-chat-wakeup`, `heartbeat-comment-wake-batching`, `heartbeat-reviewed-chat-binding.integration`, `slack-conversation-lifecycle`, `queued-comment-consumption`, `issue-queued-comments-routes` (23 files, 1037 tests). `heartbeat-process-recovery`: see the comment below. - `tsc --noEmit -p server/tsconfig.json` passes. ## Risks - Low risk. No schema change and no migration. - Behavior change only for chat messages: a message no longer joins a saved wake or a run that holds another conversation's inbound messages. It gets its own wake behind them, and it runs after them. Before this change, that batch always failed the binding check. - Board comments have no inbound chat link, so they belong to no conversation. Wakes without a conversation, wakes of one conversation, and mixed board-comment and chat wakes batch exactly as before. - Ordering: the deferred queue still promotes one wake per release, oldest first. The second conversation waits for the issue execution lock. Single-assignee and atomic checkout are unchanged. - Upgrade: a saved wake that older code merged across conversations is split at promotion. No message is dropped or delivered twice: each message id moves to exactly one wake. A run that older code already promoted in the merged shape is not changed; it fails the binding check as before and keeps its existing Retry path. - No wait is added before a turn starts. Admission adds one predicate to an existing query. Coalescing adds one indexed read only when the merged batch has a chat conversation. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), in Claude Code with tool use (shell, file edits, GitHub CLI). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] 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 --- doc/execution-semantics.md | 9 + .../adapters/chat-conversation-batch.ts | 113 ++++++ .../chat-wake-conversation-batch.test.ts | 335 ++++++++++++++++++ .../modules/wake-queue/adapters/postgres.ts | 18 +- 4 files changed, 474 insertions(+), 1 deletion(-) create mode 100644 server/src/modules/wake-queue/adapters/chat-conversation-batch.ts create mode 100644 server/src/modules/wake-queue/adapters/chat-wake-conversation-batch.test.ts diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 6c2c318e36b..d58586a675b 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -328,6 +328,15 @@ Messages from the same conversation still coalesce into one run. Messages from different conversations queue separately and run one after the other. Wakes without a conversation keep their normal coalescing. +The comparison uses the conversations of the messages themselves, not only the +conversation a wake records. A wake that the work-intent outbox saved for +unanswered chat messages records no conversation, so a message from another +conversation does not join it, and is not folded into a run promoted from it. +Board comments have no conversation and still join any batch. A saved chat wake +that older code already merged across two conversations is split when it is +promoted: the other conversation's messages run first as saved messages, then +the recorded conversation runs with its own messages. + If reviewed chat attestation exhausts its short lock or delivery wait before provider dispatch, the run records `reviewed_chat_execution_binding_not_ready`. The existing durable retry scheduler permits at most two further attempts. Each diff --git a/server/src/modules/wake-queue/adapters/chat-conversation-batch.ts b/server/src/modules/wake-queue/adapters/chat-conversation-batch.ts new file mode 100644 index 00000000000..d0109cf4f19 --- /dev/null +++ b/server/src/modules/wake-queue/adapters/chat-conversation-batch.ts @@ -0,0 +1,113 @@ +import { and, eq, inArray, ne, sql, type SQL } from "drizzle-orm"; +import { agentWakeupRequests, chatMessageLinks, type Db } from "@paperclipai/db"; +import { isUuidLike } from "@paperclipai/shared"; +import { withQueuedCommentIdsInWakePayload } from "../../../services/issue-queued-comment-queue.js"; + +// A reviewed chat run attests exactly one conversation. A wake records its +// conversation in `chatConversationId`, but a wake can also hold messages of +// a conversation it does not record: the work-intent outbox saves unanswered +// chat messages as a plain comment wake. These checks compare the +// conversations of the messages themselves, so a batch never holds messages +// of two conversations. Comments with no inbound chat link (board comments) +// belong to no conversation and batch as before. + +const DEFERRED_WAKE_CONTEXT_KEY = "_paperclipWakeContext"; +const CHAT_CONVERSATION_ID_KEY = "chatConversationId"; + +function record(value: unknown): Record { + return typeof value === "object" && value !== null && !Array.isArray(value) ? value as Record : {}; +} +const UUID_PATTERN = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"; + +/** + * SQL predicate on a deferred `agent_wakeup_requests` row: none of its queued + * messages is an inbound chat message of a conversation other than + * `conversationId`. + */ +export function deferredWakeHoldsNoOtherConversation(companyId: string, conversationId: string): SQL { + const ids = sql`${agentWakeupRequests.payload} -> ${DEFERRED_WAKE_CONTEXT_KEY}::text -> 'wakeCommentIds'`; + return sql`not exists ( + select 1 from ${chatMessageLinks} + where ${chatMessageLinks.companyId} = ${companyId} + and ${chatMessageLinks.direction} = 'inbound' + and ${chatMessageLinks.conversationId}::text <> ${conversationId} + and ${chatMessageLinks.commentId} = any(array( + select queued.id::uuid + from jsonb_array_elements_text(case when jsonb_typeof(${ids}) = 'array' then ${ids} else '[]'::jsonb end) as queued(id) + where queued.id ~ ${UUID_PATTERN} + )) + )`; +} + +/** The ids among `commentIds` that are inbound chat messages of a conversation other than `conversationId`. */ +export async function otherConversationCommentIds( + tx: Db, + input: { companyId: string; conversationId: string; commentIds: string[] }, +): Promise { + const queryable = input.commentIds.filter((id) => isUuidLike(id)); + if (queryable.length === 0) return []; + const rows = await tx + .selectDistinct({ commentId: chatMessageLinks.commentId }) + .from(chatMessageLinks) + .where(and( + eq(chatMessageLinks.companyId, input.companyId), + eq(chatMessageLinks.direction, "inbound"), + inArray(chatMessageLinks.commentId, queryable), + ne(sql`${chatMessageLinks.conversationId}::text`, input.conversationId), + )); + const other = new Set(rows.map((row) => row.commentId)); + return input.commentIds.filter((id) => other.has(id)); +} + +/** + * Upgrade repair for a deferred chat wake that older code merged across two + * conversations. The messages of other conversations move to their own plain + * saved wake (the shape the work-intent outbox writes), ordered just before + * this wake so they keep their place. This wake keeps its id, its recorded + * conversation and the rest of its messages. When no message of its own + * conversation is left, the wake keeps its id and becomes a plain saved wake. + * No message is dropped. + * Returns true when the wake changed and must be read again. + */ +export async function splitOtherConversationMessages( + tx: Db, + row: typeof agentWakeupRequests.$inferSelect, + input: { companyId: string; issueId: string; conversationId: string; queuedCommentIds: string[]; payload: Record }, +): Promise { + const moved = await otherConversationCommentIds(tx, { + companyId: input.companyId, conversationId: input.conversationId, commentIds: input.queuedCommentIds, + }); + if (moved.length === 0) return false; + const kept = input.queuedCommentIds.filter((id) => !moved.includes(id)); + const now = new Date(); + const deferred = and(eq(agentWakeupRequests.companyId, input.companyId), eq(agentWakeupRequests.id, row.id), + eq(agentWakeupRequests.status, "deferred_issue_execution")); + if (kept.length === 0) { + // Every message belongs to another conversation. Keep the wake and its id + // (an interrupt names the wake by id) and drop only its chat binding, so + // it runs as plain saved messages. + const { [CHAT_CONVERSATION_ID_KEY]: _dropped, ...context } = record(input.payload[DEFERRED_WAKE_CONTEXT_KEY]); + await tx.update(agentWakeupRequests).set({ updatedAt: now, + payload: withQueuedCommentIdsInWakePayload({ ...input.payload, mutation: "comment", + [DEFERRED_WAKE_CONTEXT_KEY]: { ...context, source: "issue.comment", wakeReason: "issue_commented" } }, moved) }) + .where(deferred); + return true; + } + const updated = await tx.update(agentWakeupRequests) + .set({ payload: withQueuedCommentIdsInWakePayload(input.payload, kept), updatedAt: now }) + .where(deferred) + .returning({ id: agentWakeupRequests.id }); + // Another writer already moved the wake on; its messages stay where they are. + if (updated.length === 0) return true; + const latest = moved.at(-1)!; + await tx.insert(agentWakeupRequests).values({ + companyId: input.companyId, agentId: row.agentId, source: "automation", triggerDetail: "system", + reason: "issue_commented", status: "deferred_issue_execution", + requestedByActorType: row.requestedByActorType, requestedByActorId: row.requestedByActorId, + requestedAt: new Date(row.requestedAt.getTime() - 1), updatedAt: now, + payload: withQueuedCommentIdsInWakePayload({ issueId: input.issueId, mutation: "comment", commentId: latest, + [DEFERRED_WAKE_CONTEXT_KEY]: { issueId: input.issueId, taskId: input.issueId, wakeReason: "issue_commented", + source: "issue.comment", wakeCommentIds: moved, wakeCommentId: latest } }, moved), + }); + return true; +} diff --git a/server/src/modules/wake-queue/adapters/chat-wake-conversation-batch.test.ts b/server/src/modules/wake-queue/adapters/chat-wake-conversation-batch.test.ts new file mode 100644 index 00000000000..760708c4549 --- /dev/null +++ b/server/src/modules/wake-queue/adapters/chat-wake-conversation-batch.test.ts @@ -0,0 +1,335 @@ +import { randomUUID } from "node:crypto"; +import { and, asc, eq, sql } from "drizzle-orm"; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { agentWakeupRequests, chatConversations, chatDeliveries, chatMessageLinks, createDb, heartbeatRuns, + issueComments, issues, type Db } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js"; +import { seedBoundChatAuthorization } from "../../../__tests__/helpers/bound-chat-authorization.js"; +import { authorizeChatConversationForBoundRun } from "../../../services/native-runtime/chat-attachment-reuse.js"; +import { mergeCoalescedContextSnapshot } from "../../../services/heartbeat/run-preparation.js"; +import { saveUndeliveredUserComments } from "../../../services/work-intent-outbox.js"; +import { queuedCommentIdsFromWakePayload } from "../../../services/issue-queued-comment-queue.js"; +import { createAdmitWakeBehindIssueExecution, createReleaseIssueExecution } from "../application/use-cases.js"; +import type { WakeAdmissionActiveExecutionRun } from "../application/ports.js"; +import { createAdmissionTransactionScope, createPostgresWakeQueueAdapter, createWakeAdmissionReader, + createWakeAdmissionWriter } from "./postgres.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const CONTEXT_KEY = "_paperclipWakeContext"; + +// PAP-4244 on staging. The work-intent outbox saved two unanswered GitHub +// messages as a plain deferred wake: it records no chat conversation. A new +// message from another conversation then merged into that saved wake, because +// a wake with no recorded conversation matched every conversation. The +// promoted run held messages of two conversations, and the reviewed chat +// binding refused it: `reviewed_chat_execution_binding_not_authorized` +// (`binding_denied`). Each conversation must get its own run, in order. +describe.skipIf(!support.supported)("chat wake batches stay within one conversation", () => { + let database: Awaited>; + let db: ReturnType; + let f: Awaited>; + let otherConversationId: string; + let deferOnly = true; + + const admit = createAdmitWakeBehindIssueExecution({ + reader: createWakeAdmissionReader(), + writer: createWakeAdmissionWriter(), + helpers: { + filterZombieCoalesceTarget: (target) => target, + mergeCoalescedContextSnapshot, + shouldDeferFollowupWakeForSameIssue: () => deferOnly, + shouldQueueFollowupForRunningIssueWake: () => false, + }, + }); + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("wake-chat-conversation-batch-"); + db = createDb(database.connectionString); + }, 60_000); + + afterAll(async () => { + await db?.$client.end(); + await database?.cleanup(); + }); + + beforeEach(async () => { + deferOnly = true; + // The fixture uses fixed identifiers; move earlier cases' rows aside. + await db.execute(sql`update companies set issue_prefix = 'X' || upper(left(replace(id::text, '-', ''), 6))`); + await db.execute(sql`update issues set identifier = id::text`); + f = await seedBoundChatAuthorization(db); + otherConversationId = randomUUID(); + await db.insert(chatConversations).values({ id: otherConversationId, companyId: f.companyId, endpointId: f.endpointId, + resourceId: f.resourceId, issueId: f.issueId, externalConversationId: "channel-1", externalThreadId: "thread-2", + externalLabel: "Second review thread", state: "active" }); + // The fixture's own message is not part of these cases. + await db.delete(chatMessageLinks).where(eq(chatMessageLinks.commentId, f.commentId)); + await db.delete(issueComments).where(eq(issueComments.id, f.commentId)); + await db.insert(heartbeatRuns).values({ id: f.runId, companyId: f.companyId, agentId: f.agentId, status: "running", + invocationSource: "assignment", triggerDetail: "system", startedAt: new Date(), + contextSnapshot: { issueId: f.issueId, taskId: f.issueId } }); + await db.update(issues).set({ executionRunId: f.runId, executionLockedAt: new Date() }).where(eq(issues.id, f.issueId)); + }); + + let messageClock = Date.now() - 600_000; + async function message(conversationId: string | null): Promise { + messageClock += 1_000; + const at = new Date(messageClock); + const [comment] = await db.insert(issueComments).values({ companyId: f.companyId, issueId: f.issueId, + authorType: "user", authorUserId: f.userId, body: `Message ${messageClock}`, createdAt: at, updatedAt: at }).returning(); + if (conversationId) { + const deliveryId = randomUUID(); + await db.insert(chatDeliveries).values({ id: deliveryId, companyId: f.companyId, endpointId: f.endpointId, + conversationId, principalId: f.principalId, providerEventId: deliveryId, deduplicationKey: deliveryId, + eventKind: "message", normalizedEvent: {}, state: "processed", attempts: 1, processedAt: at }); + await db.insert(chatMessageLinks).values({ companyId: f.companyId, endpointId: f.endpointId, conversationId, + deliveryId, commentId: comment!.id, providerMessageId: deliveryId, direction: "inbound" }); + } + return comment!.id; + } + + function chatContext(conversationId: string, commentId: string) { + return { issueId: f.issueId, taskId: f.issueId, source: "chat:slack", wakeReason: "External chat message received", + wakeSource: "assignment", chatConversationId: conversationId, commentId, wakeCommentId: commentId, + wakeCommentIds: [commentId] }; + } + + function commentContext(commentId: string) { + return { issueId: f.issueId, taskId: f.issueId, source: "issue.comment", wakeReason: "issue_commented", + commentId, wakeCommentId: commentId, wakeCommentIds: [commentId] }; + } + + async function admitWake(contextSnapshot: Record, activeExecutionRun?: WakeAdmissionActiveExecutionRun) { + const commentId = contextSnapshot.wakeCommentId as string; + const chat = contextSnapshot.source === "chat:slack"; + return db.transaction(async (tx) => admit(createAdmissionTransactionScope(f.companyId, tx as unknown as Db), { + companyId: f.companyId, issueId: f.issueId, agentId: f.agentId, agentNameKey: "chat runner", + issueExecutionAgentNameKey: null, + activeExecutionRun: activeExecutionRun ?? { id: f.runId, agentId: f.agentId, status: "running", + contextSnapshot: { issueId: f.issueId, taskId: f.issueId }, wakeupRequestId: null }, + allowRunCoalescing: true, liveRunExecutions: new Set([f.runId]), wakeCommentId: commentId, + forceFreshSession: false, contextSnapshot, source: "assignment", triggerDetail: "system", + reason: chat ? "External chat message received" : "issue_commented", + payload: { issueId: f.issueId, mutation: chat ? "chat_message_received" : "comment", wakeCommentId: commentId }, + requestedByActorType: "user", requestedByActorId: f.userId, idempotencyKey: null, + })); + } + + async function deferredWakes() { + const rows = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, f.companyId), + eq(agentWakeupRequests.status, "deferred_issue_execution"))).orderBy(asc(agentWakeupRequests.requestedAt)); + return rows.map(row => ({ id: row.id, commentIds: queuedCommentIdsFromWakePayload(row.payload), + context: (row.payload as Record>)[CONTEXT_KEY]! })); + } + + async function attest(context: Record) { + return authorizeChatConversationForBoundRun(db, { companyId: f.companyId, issueId: f.issueId, agentId: f.agentId, + runId: f.runId }, { ...context, paperclipHarnessCheckedOut: true }, "read"); + } + + async function saveUndelivered(commentIds: string[]) { + const saved = await saveUndeliveredUserComments(db, { companyId: f.companyId, issueId: f.issueId, agentId: f.agentId, + commentIds, allowedStatuses: ["in_review"] }); + expect(saved).toBeTruthy(); + return saved!; + } + + it("keeps a message out of a saved wake that holds another conversation's messages", async () => { + const earlier = await message(otherConversationId); + const saved = await saveUndelivered([earlier]); + const reply = await message(f.conversationId); + + expect(await admitWake(chatContext(f.conversationId, reply))).toEqual({ kind: "deferred" }); + + const wakes = await deferredWakes(); + // The saved messages run first, then the new conversation, each on its own. + expect(wakes.map(wake => wake.commentIds)).toEqual([[earlier], [reply]]); + expect(wakes[0]!.id).toBe(saved); + expect(wakes[0]!.context.chatConversationId).toBeUndefined(); + expect(wakes[0]!.context.source).toBe("issue.comment"); + await expect(attest(wakes[1]!.context)).resolves.toMatchObject({ conversationId: f.conversationId }); + }); + + it("keeps two conversations apart when both arrive behind saved wakes", async () => { + const first = await message(f.conversationId); + const second = await message(otherConversationId); + await saveUndelivered([first]); + await saveUndelivered([second]); + const replyToFirst = await message(f.conversationId); + const replyToSecond = await message(otherConversationId); + + await admitWake(chatContext(otherConversationId, replyToSecond)); + await admitWake(chatContext(f.conversationId, replyToFirst)); + + const wakes = await deferredWakes(); + expect(wakes.map(wake => wake.commentIds)).toEqual([[first, replyToFirst], [second, replyToSecond]]); + expect(wakes.map(wake => wake.context.chatConversationId)).toEqual([f.conversationId, otherConversationId]); + await expect(attest(wakes[0]!.context)).resolves.toMatchObject({ conversationId: f.conversationId }); + await expect(attest(wakes[1]!.context)).resolves.toMatchObject({ conversationId: otherConversationId }); + }); + + describe("batching that stays the same", () => { + it("merges comment wakes that have no conversation", async () => { + const one = await message(null); + const two = await message(null); + await admitWake(commentContext(one)); + await admitWake(commentContext(two)); + expect((await deferredWakes()).map(wake => wake.commentIds)).toEqual([[one, two]]); + }); + + it("merges messages of one conversation", async () => { + const one = await message(f.conversationId); + const two = await message(f.conversationId); + await admitWake(chatContext(f.conversationId, one)); + await admitWake(chatContext(f.conversationId, two)); + const wakes = await deferredWakes(); + expect(wakes.map(wake => wake.commentIds)).toEqual([[one, two]]); + await expect(attest(wakes[0]!.context)).resolves.toMatchObject({ conversationId: f.conversationId }); + }); + + it("merges a saved wake of the same conversation's messages", async () => { + const earlier = await message(f.conversationId); + await saveUndelivered([earlier]); + const reply = await message(f.conversationId); + await admitWake(chatContext(f.conversationId, reply)); + const wakes = await deferredWakes(); + expect(wakes.map(wake => wake.commentIds)).toEqual([[earlier, reply]]); + await expect(attest(wakes[0]!.context)).resolves.toMatchObject({ conversationId: f.conversationId }); + }); + + it("merges a chat message into a wake of plain comments, and a plain comment into a chat wake", async () => { + const plain = await message(null); + const chat = await message(f.conversationId); + const laterPlain = await message(null); + await admitWake(commentContext(plain)); + await admitWake(chatContext(f.conversationId, chat)); + await admitWake(commentContext(laterPlain)); + const wakes = await deferredWakes(); + expect(wakes.map(wake => wake.commentIds)).toEqual([[plain, chat, laterPlain]]); + expect(wakes[0]!.context.chatConversationId).toBe(f.conversationId); + }); + + it("keeps messages of two recorded conversations apart", async () => { + const one = await message(f.conversationId); + const two = await message(otherConversationId); + await admitWake(chatContext(f.conversationId, one)); + await admitWake(chatContext(otherConversationId, two)); + expect((await deferredWakes()).map(wake => wake.commentIds)).toEqual([[one], [two]]); + }); + }); + + it("does not fold a message into a queued run that holds another conversation's messages", async () => { + deferOnly = false; + const earlier = await message(otherConversationId); + const savedId = await saveUndelivered([earlier]); + // The saved wake was promoted: a queued run that the finished run left behind. + const queuedRunId = randomUUID(); + const [savedWake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, savedId)); + const runContext = (savedWake!.payload as Record>)[CONTEXT_KEY]!; + await db.insert(heartbeatRuns).values({ id: queuedRunId, companyId: f.companyId, agentId: f.agentId, status: "queued", + invocationSource: "automation", triggerDetail: "system", wakeupRequestId: savedId, contextSnapshot: runContext }); + await db.update(agentWakeupRequests).set({ status: "queued", runId: queuedRunId }).where(eq(agentWakeupRequests.id, savedId)); + await db.update(issues).set({ executionRunId: queuedRunId }).where(eq(issues.id, f.issueId)); + const reply = await message(f.conversationId); + + const result = await admitWake(chatContext(f.conversationId, reply), { id: queuedRunId, agentId: f.agentId, + status: "queued", contextSnapshot: runContext, wakeupRequestId: savedId }); + + expect(result).toEqual({ kind: "deferred" }); + const [queuedRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, queuedRunId)); + expect(queuedRun!.contextSnapshot).toMatchObject({ wakeCommentIds: [earlier], source: "issue.comment" }); + expect((await deferredWakes()).map(wake => wake.commentIds)).toEqual([[reply]]); + }); + + it("still folds a same-conversation message into a queued run", async () => { + deferOnly = false; + const earlier = await message(f.conversationId); + const savedId = await saveUndelivered([earlier]); + const queuedRunId = randomUUID(); + const [savedWake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, savedId)); + const runContext = (savedWake!.payload as Record>)[CONTEXT_KEY]!; + await db.insert(heartbeatRuns).values({ id: queuedRunId, companyId: f.companyId, agentId: f.agentId, status: "queued", + invocationSource: "automation", triggerDetail: "system", wakeupRequestId: savedId, contextSnapshot: runContext }); + await db.update(agentWakeupRequests).set({ status: "queued", runId: queuedRunId }).where(eq(agentWakeupRequests.id, savedId)); + await db.update(issues).set({ executionRunId: queuedRunId }).where(eq(issues.id, f.issueId)); + const reply = await message(f.conversationId); + + const result = await admitWake(chatContext(f.conversationId, reply), { id: queuedRunId, agentId: f.agentId, + status: "queued", contextSnapshot: runContext, wakeupRequestId: savedId }); + + expect(result.kind).toBe("coalesced"); + const [queuedRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, queuedRunId)); + expect(queuedRun!.contextSnapshot).toMatchObject({ wakeCommentIds: [earlier, reply], chatConversationId: f.conversationId }); + }); + + function releaseIssue() { + return createReleaseIssueExecution({ + issueLock: createPostgresWakeQueueAdapter(db, { + resolveResponsibleUserId: async () => f.userId, + getRoutineEnv: async () => ({ routineId: null, env: null, responsibleUserId: null }), + resolveSessionBeforeForWakeup: async () => null, + } as never), + recovery: { escalateStrandedAssignedIssue: async () => {}, escalateStrandedRecoveryIssueInPlace: async () => {} } as never, + }); + } + + // An older merged wake can be left with only the other conversation's + // messages (its own message was discarded). An interrupt names the wake by + // id, so the wake keeps its id and runs as plain saved messages. + it("keeps an interrupted wake's id when all of its messages belong to another conversation", async () => { + const earlier = await message(otherConversationId); + const savedId = await saveUndelivered([earlier]); + const [savedWake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, savedId)); + const payload = savedWake!.payload as Record; + await db.update(agentWakeupRequests).set({ payload: { ...payload, mutation: "chat_message_received", + [CONTEXT_KEY]: { ...(payload[CONTEXT_KEY] as Record), source: "chat:slack", + wakeReason: "External chat message received", chatConversationId: f.conversationId } } }) + .where(eq(agentWakeupRequests.id, savedId)); + await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(), + resultJson: { queuedCommentInterruptQueueId: savedId, executionCancellation: { state: "acknowledged" }, + conversationContinuation: "continue_conversation_v1" } }) + .where(eq(heartbeatRuns.id, f.runId)); + + const result = await releaseIssue()({ companyId: f.companyId, runId: f.runId, now: new Date() }); + + expect(result.outcome.kind).toBe("promoted"); + const promoted = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId), + eq(heartbeatRuns.status, "queued"))); + expect(promoted).toHaveLength(1); + expect(promoted[0]!.wakeupRequestId).toBe(savedId); + expect(promoted[0]!.contextSnapshot).toMatchObject({ wakeCommentIds: [earlier], source: "issue.comment" }); + expect(promoted[0]!.contextSnapshot?.chatConversationId).toBeUndefined(); + expect(await deferredWakes()).toEqual([]); + }); + + // A wake that older code already merged across two conversations. Release + // splits it: the other conversation's messages run first as plain saved + // messages, then the recorded conversation runs with its own messages. + it("splits a saved wake that older code merged across two conversations", async () => { + const earlier = await message(otherConversationId); + const savedId = await saveUndelivered([earlier]); + const reply = await message(f.conversationId); + const [savedWake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, savedId)); + const payload = savedWake!.payload as Record; + const merged = mergeCoalescedContextSnapshot(payload[CONTEXT_KEY], chatContext(f.conversationId, reply)); + await db.update(agentWakeupRequests).set({ payload: { ...payload, mutation: "chat_message_received", + commentId: reply, wakeCommentId: reply, [CONTEXT_KEY]: merged } }).where(eq(agentWakeupRequests.id, savedId)); + expect(merged).toMatchObject({ wakeCommentIds: [earlier, reply], chatConversationId: f.conversationId }); + // This is the shape that failed on staging. + await expect(attest(merged)).rejects.toThrow("paperclip_runner_chat_attachment_binding_denied"); + + const release = releaseIssue(); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, f.runId)); + const first = await release({ companyId: f.companyId, runId: f.runId, now: new Date() }); + expect(first.outcome.kind).toBe("promoted"); + + const promoted = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId), + eq(heartbeatRuns.status, "queued"))); + expect(promoted).toHaveLength(1); + expect(promoted[0]!.contextSnapshot).toMatchObject({ wakeCommentIds: [earlier], source: "issue.comment" }); + expect(promoted[0]!.contextSnapshot?.chatConversationId).toBeUndefined(); + const waiting = await deferredWakes(); + expect(waiting).toEqual([expect.objectContaining({ id: savedId, commentIds: [reply] })]); + await expect(attest(waiting[0]!.context)).resolves.toMatchObject({ conversationId: f.conversationId }); + }); +}); diff --git a/server/src/modules/wake-queue/adapters/postgres.ts b/server/src/modules/wake-queue/adapters/postgres.ts index 93689a48dd1..07c2bb718c2 100644 --- a/server/src/modules/wake-queue/adapters/postgres.ts +++ b/server/src/modules/wake-queue/adapters/postgres.ts @@ -55,7 +55,8 @@ import { queuedCommentIdsFromRunContext, withQueuedCommentIdsInWakePayload, } from "../../../services/issue-queued-comment-queue.js"; -import { CHAT_CONVERSATION_ID_KEY, extractWakeCommentIds } from "../../run-dispatch/index.js"; +import { CHAT_CONVERSATION_ID_KEY, extractWakeCommentIds, readWakeChatConversationId } from "../../run-dispatch/index.js"; +import { deferredWakeHoldsNoOtherConversation, otherConversationCommentIds, splitOtherConversationMessages } from "./chat-conversation-batch.js"; import { hasInteractionContinuationWakeContext } from "../domain/context.js"; import { decidePreDrain, type PreDrainFacts } from "../domain/policy.js"; import { @@ -259,6 +260,12 @@ function buildTransaction(tx: Db, deps: WakeQueuePostgresAdapterDeps, db: Db, ru .then((rows) => rows[0] ?? null); if (!row) return null; const candidate = toDeferredWakeCandidate(row); + // Upgrade repair: older code could merge two conversations into one + // saved chat wake. Split it and read the queue again. + const conversationId = readWakeChatConversationId(candidate.deferredContextSeed); + if (conversationId && candidate.queuedCommentIds.length > 0 && await splitOtherConversationMessages(tx, row, { + companyId, issueId, conversationId, queuedCommentIds: candidate.queuedCommentIds, payload: candidate.payload, + })) continue; try { const authorizedFailedChatRetry = await authorizeFailedChatRunRetryWake( db, @@ -960,6 +967,9 @@ export function createWakeAdmissionReader(): WakeAdmissionReader { ...(chatConversationId ? [ sql`coalesce(${agentWakeupRequests.payload} -> ${DEFERRED_WAKE_CONTEXT_KEY}::text ->> ${CHAT_CONVERSATION_ID_KEY}::text, ${chatConversationId}) = ${chatConversationId}`, + // A wake with no recorded conversation can still hold + // another conversation's messages (an outbox-saved wake). + deferredWakeHoldsNoOtherConversation(companyId, chatConversationId), ] : []), ...(durableActor @@ -1016,6 +1026,12 @@ export function createWakeAdmissionWriter(): WakeAdmissionWriter { )).for("update").limit(1); if (!current || current.status !== input.activeExecutionRunStatus || current.wakeupRequestId !== candidate.wakeupRequestId) return null; const commentIds = queuedCommentIdsFromRunContext(input.mergedContextSnapshot); + // A reviewed chat run attests one conversation. Never fold a message + // into a run that already holds another conversation's messages; the + // wake is saved behind the run instead. + const mergedConversationId = readWakeChatConversationId(input.mergedContextSnapshot); + if (mergedConversationId && commentIds.length > 0 && (await otherConversationCommentIds(tx, { + companyId: input.companyId, conversationId: mergedConversationId, commentIds })).length > 0) return null; const synchronizeBatch = current.status === "queued" && commentIds.length > 0 && primary?.status === "queued" && queuedCommentIdsFromWakePayload(primary.payload).length > 0; if (current.status === "queued" && commentIds.length && current.wakeupRequestId && From 200c6e40e2cba5d9419f688b8f8d38dbc22e1a16 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 21:35:38 -0600 Subject: [PATCH 25/38] fix(native): restart a bootstrap whose Runner suspended before the provider opened (#20691) 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. > - When a native run's first provider start fails before any session opens, Paperclip retries the bootstrap on the same run. Durable controller evidence proves that no provider session or provider event exists. > - A remote sandbox keeps the Runner state inside the workspace. A replacement sandbox gets that state back when the saved workspace is restored. > - When the provider refused `session.open` (for example an Anthropic 429), the Runner still suspended cleanly. Its state says `suspended`, but the provider state has no session identity. > - The same-run restart handled a Runner that never suspended. It did not handle a Runner that suspended before the provider opened a session. It failed with `runner_harness_state_mismatch: provider_identity_incomplete (provider_not_suspended)`, and the task showed "Recovery needed" without Retry. > - This pull request lets that proven restart set the unopened session aside and start the provider again. > - The benefit is that a rate-limited provider start continues by itself after the limit resets. ## Linked Issues or Issue Description Refs #20627 and #20683 (other restore paths). This PR changes only the same-run bootstrap restart. **What happened?** Two ACPX Claude tasks on remote Daytona sandboxes, on staging: 1. The first attempt sent `session.open`. ACPX rejected it with `classification=provider_rate_limit` (Anthropic 429). The Runner exited with `lifecycle=suspended`. 2. Paperclip recorded `recoveryMode: bootstrap_retry`, `providerSessionEstablished: false`, `providerEventsExist: false`, and a retry after the limit reset. 3. One hour later the retry ran as `bootstrap_incomplete` on the same run, in a new sandbox with the saved workspace restored. 4. Host preparation inspected the restored Runner state. The Runner was `suspended`, but the provider had no session identity. The inspection threw `provider_identity_incomplete (provider_not_suspended)` before the bootstrap restart branch ran. 5. The run failed. The task stopped at "Recovery needed" with only inspect actions. **Expected behavior** The restart sets the unopened session aside and opens a new provider session, as it already does for a Runner that never suspended. **Steps to reproduce** 1. Restart a remote run as `bootstrap_incomplete` with a proven bootstrap restart. 2. Give the sandbox a Runner state for this run with `lifecycle: suspended` and a provider state with no session identity. 3. Prepare the host. On `master` it throws `runner_harness_state_mismatch: provider_identity_incomplete`. The new `interrupted_bootstrap_unopened` cases of `bootstraps only an untouched provider session in a $outcome workspace lease` run these steps for a created and a resumed lease. **Paperclip version or commit** `master` at `7435abcc63`. ## What Changed - During host preparation, a Runner state that is suspended with no provider session identity returns the new incomplete reason `provider_unopened`, but only when all of these hold: - the run is restarting as `bootstrap_incomplete`; - the state belongs to this same run; - the controller already recorded the bootstrap restart proof (its durable journal shows no provider turn, and the old Runner is stopped or absent). - the provider state is the one saved before any session opened (`remoteProviderStateNeverOpened`): `prepared`, no session or identity, no turn in progress, no unconfirmed exit. Only ACPX and Codex-family states qualify. - The created-lease and resumed-lease restart branches share one check (`restartableBootstrapState`) and accept `provider_unopened` exactly like `not_suspended`. They move the old session aside and claim a new, untouched session root. - Every other case still throws `provider_identity_incomplete`: another run's state, a restart without the proof, a normal resume, and close checkpointing. ## Verification - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-session-executor.test.ts -t "bootstraps only an untouched provider session"`: 47 passed. - Red on `master`: the `created` and `resumed` `interrupted_bootstrap_unopened` cases fail with `runner_harness_state_mismatch: provider_identity_incomplete (identity_binding)`. Green with this change. - Fail-closed cases stay red-proof: `interrupted_bootstrap_unopened_unproven` (no restart proof) and `interrupted_bootstrap_unopened_other_run` (another run's state) still throw. - Full `native-session-executor.test.ts` and `pnpm --filter @paperclipai/server typecheck` pass. ## Risks - Low risk. The new branch needs the same proof that already authorizes a fresh bootstrap for a Runner that never suspended. The proof comes from the controller's durable journal, not from the sandbox. - The normal path is unchanged and has no added wait. - Not proven live: I did not confirm on staging that the controller recorded the restart proof for these runs. If it did not, the run still fails closed as before. > 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, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- .../native-session-executor.test.ts | 49 +++++++++++++++++-- .../native-runtime/native-session-executor.ts | 49 +++++++++++++++---- 2 files changed, 83 insertions(+), 15 deletions(-) diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index dd961a60dc2..29669b434ca 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -474,6 +474,7 @@ import { retryTransientRemoteCheckpointRead, verifyNativeHarnessBackup, shouldRestoreNativeHarnessBackupIntoSandbox, + remoteProviderStateNeverOpened, } from "./native-session-executor.js"; import { onNativeRunnerEvidence } from "./native-runner-evidence-signal.js"; @@ -20274,10 +20275,15 @@ describe("runnerd provider runtime wiring", () => { ["fresh", "external_checkpoint", "external_pending_turn", "external_wrong_identity", "external_unregistered", "existing_state", "symlink_parent", "wrong_identity", "wrong_runner", "wrong_lease", "missing_control_plane", "connected", "committed_event", "committed_command", "pending_turn", "remote_probe_failed", "backup_present"] .map((scenario) => ({ outcome, scenario, homeMode: "isolated" }))), ...["resumed", "replacement"].map(outcome => ({ outcome, scenario: "fresh", homeMode: "preconfigured" })), - ...["interrupted_bootstrap", "interrupted_bootstrap_other_run", "interrupted_bootstrap_unproven", "interrupted_bootstrap_symlink_parent"] + ...["interrupted_bootstrap", "interrupted_bootstrap_other_run", "interrupted_bootstrap_unproven", "interrupted_bootstrap_symlink_parent", + "interrupted_bootstrap_unopened", "interrupted_bootstrap_unopened_unproven", "interrupted_bootstrap_unopened_other_run", + "interrupted_bootstrap_unopened_active_turn"] .map(scenario => ({ outcome: "resumed", scenario, homeMode: "isolated" })), { outcome: "created", scenario: "interrupted_bootstrap", homeMode: "isolated" }, { outcome: "created", scenario: "interrupted_bootstrap_symlink_parent", homeMode: "isolated" }, + { outcome: "created", scenario: "interrupted_bootstrap_unopened", homeMode: "isolated" }, + { outcome: "created", scenario: "interrupted_bootstrap_unopened_active_turn", homeMode: "isolated" }, + { outcome: "created", scenario: "interrupted_bootstrap_unopened_unproven", homeMode: "isolated" }, ])( "bootstraps only an untouched provider session in a $outcome workspace lease: $scenario ($homeMode)", async ({ outcome, scenario, homeMode }) => { const remoteCwd = join(isolatedStateDirectory, "remote"); @@ -20321,11 +20327,19 @@ describe("runnerd provider runtime wiring", () => { try { execFileSync("sh", command.args, { stdio: "pipe" }); return { exitCode: 0, timedOut: false, stdout: "", stderr: "" }; } catch { return { exitCode: 1, timedOut: false, stdout: "", stderr: "" }; } } + if (command.args?.[1]?.includes("base64") && scenario.startsWith("interrupted_bootstrap_unopened") + && command.args[1].includes("codex-provider-state.json") && !command.args[1].includes("runner-state.json")) return { + exitCode: 0, timedOut: false, stderr: "", stdout: Buffer.from(JSON.stringify({ + schema: "paperclip.runner.codex-provider-state.v1", lifecycle: "prepared", threadId: null, providerSessionId: null, + activeProviderTurnId: scenario.endsWith("_active_turn") ? "turn-in-progress" : null, ambiguousTurnStartPending: false, + config: { provider: "codex", driver: "codex_app_server" } })).toString("base64"), + }; if (command.args?.[1]?.includes("base64") && scenario.startsWith("interrupted_bootstrap")) return { exitCode: 0, timedOut: false, stderr: "", stdout: Buffer.from(JSON.stringify({ runnerInstanceId: "runner-new-in-retained-workspace", normalizedSessionId: execution.session.normalizedSessionId, - runId: scenario === "interrupted_bootstrap_other_run" ? "previous-warm-run" : execution.binding.runId, - lifecycle: "ready", outbox: [], pendingTerminalDelivery: null })).toString("base64"), + runId: scenario.endsWith("_other_run") ? "previous-warm-run" : execution.binding.runId, + lifecycle: scenario.startsWith("interrupted_bootstrap_unopened") ? "suspended" : "ready", + outbox: [], pendingTerminalDelivery: null })).toString("base64"), }; if (command.args?.[1]?.includes("base64")) return { exitCode: 1, timedOut: false, stdout: "", stderr: "", @@ -20416,10 +20430,11 @@ describe("runnerd provider runtime wiring", () => { await mkdir(join(options.stateDirectory!, "failover-backups", "current"), { recursive: true }); await writeFile(join(options.stateDirectory!, "failover-backups", "current", "manifest.json"), "{}"); } - if (["interrupted_bootstrap", "interrupted_bootstrap_other_run", "interrupted_bootstrap_symlink_parent"].includes(scenario)) { + if (["interrupted_bootstrap", "interrupted_bootstrap_other_run", "interrupted_bootstrap_symlink_parent", + "interrupted_bootstrap_unopened", "interrupted_bootstrap_unopened_other_run", "interrupted_bootstrap_unopened_active_turn"].includes(scenario)) { noteRemoteBootstrapRestartProven(execution.binding.runId, "stopped"); } - if (scenario === "interrupted_bootstrap") { + if (scenario === "interrupted_bootstrap" || scenario === "interrupted_bootstrap_unopened") { await expect(options.prepareExternalRunnerState()).resolves.toBeUndefined(); const siblings = await readdir(dirname(sessionRoot)); expect(siblings.filter(name => name.startsWith(`${basename(sessionRoot)}.bootstrap-restart-`))).toHaveLength(1); @@ -21248,6 +21263,30 @@ describe("HTTP Stop during remote runner staging", () => { }, 120000); }); +describe("remoteProviderStateNeverOpened", () => { + const acpx = { provider: { kind: "acpx" } } as unknown as Parameters[0]; + const prepared = { + schema: "paperclip.runner.acpx-provider-state.v3", launchProfileDigest: `sha256:${"c".repeat(64)}`, lifecycle: "prepared", + descriptor: { kind: "acpx", provider: "acpx", driver: "acpx_runtime", agent: "claude", model: "explicit-model" }, + toolSet: { schema: "paperclip.runner.authorized-tools.v1", schemaVersion: 1, catalogDigest: `sha256:${"d".repeat(64)}`, operations: [] }, + identity: null, activeTurnId: null, attemptedTurnControls: [], providerExitUnconfirmed: false, + semanticResult: null, goalProjection: null, turnControls: { steering: false, queuedFollowUp: false }, + goalRevision: 0, goalSourceRevision: null, pendingEvents: [], pendingRuntimeRequests: {}, nextEventSequence: 1, + openSemanticCalls: [], retiredSemanticCalls: [], + }; + it("accepts the ACPX state a rejected session.open leaves, and nothing that may hold a turn", () => { + expect(remoteProviderStateNeverOpened(acpx, prepared)).toBe(true); + const { providerExitUnconfirmed: _exit, activeTurnId: _turn, identity: _identity, ...beforeDefaults } = prepared; + expect(remoteProviderStateNeverOpened(acpx, beforeDefaults)).toBe(true); + for (const changed of [{ lifecycle: "session_open" }, { lifecycle: "turn_active", activeTurnId: "turn" }, { activeTurnId: "turn" }, + { providerExitUnconfirmed: true }, { lifecycle: "closed", providerExitUnconfirmed: true }, { schema: "paperclip.runner.acpx-provider-state.v2" }, + { identity: { kind: "acpx", acpxRecordId: "record" } }]) { + expect(remoteProviderStateNeverOpened(acpx, { ...prepared, ...changed })).toBe(false); + } + expect(remoteProviderStateNeverOpened({ provider: { kind: "claude_managed" } } as never, { lifecycle: "prepared" })).toBe(false); + }); +}); + describe("isTransientRemoteCheckpointReadFailure", () => { it("repeats only a dropped sandbox connection, never a state or safety refusal", () => { expect(isTransientRemoteCheckpointReadFailure(Object.assign(new Error("write ECONNRESET"), { code: "ECONNRESET" }))).toBe(true); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 7ed7a9692c6..ac9a832446a 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -7607,6 +7607,24 @@ function providerSessionIdentityIsPresent(value: unknown): boolean { ); } +export function remoteProviderStateNeverOpened(execution: NativeExecutionInput, providerState: unknown): boolean { + const state = record(providerState); + if (state.lifecycle !== "prepared") return false; + switch (execution.provider.kind) { + case "acpx": + return state.schema === ACPX_PROVIDER_STATE_SCHEMA && (state.identity ?? null) === null + && (state.activeTurnId ?? null) === null && (state.providerExitUnconfirmed ?? false) === false; + case "cursor_cloud": + case "codex": + case "opencode": + return state.schema === CODEX_PROVIDER_STATE_SCHEMA && (state.threadId ?? null) === null + && (state.providerSessionId ?? null) === null && (state.activeProviderTurnId ?? null) === null + && state.ambiguousTurnStartPending !== true; + default: + return false; + } +} + /** Closed diagnostic categories; durable state may contain private provider data. */ export function durableProviderCheckpointFailureReason(execution: NativeExecutionInput, providerState: unknown): string { if (execution.provider.kind !== "acpx") return "identity_binding"; @@ -14671,7 +14689,7 @@ export { resolveRemoteRunnerTransportMode } from "./native-runner-execution-driv export function remoteCheckpointIncompleteFailure( settlement: "settled" | "unsettled", - incompleteReason: "unavailable" | "not_suspended" | null, + incompleteReason: "unavailable" | "not_suspended" | "provider_unopened" | null, ): Error | null { // A transport that never completed provider bootstrap has no provider state // to preserve; its original launch failure remains authoritative. Once @@ -15740,13 +15758,20 @@ async function createRunnerdBackendWithinSessionClaim( * this invocation's archived rotation snapshot; every other caller, * including close checkpointing, must inspect the live Runner state. */ + const provenOwnBootstrapRestart = (runId: string | null | undefined) => + input.restartRecovery?.kind === "bootstrap_incomplete" + && runId === input.execution.binding.runId + && hasRemoteBootstrapRestartProof(input.execution.binding.runId); + const restartableBootstrapState = (state: { incompleteReason: string | null; notSuspendedRunId?: string | null }) => + (state.incompleteReason === "not_suspended" || state.incompleteReason === "provider_unopened") + && provenOwnBootstrapRestart(state.notSuspendedRunId); const inspectRemoteHarnessState = async ( source: "live" | "host_preparation" = "live", ): Promise<{ complete: boolean; runnerState: Record | null; providerSessionIdentity: Record | null; - incompleteReason: "unavailable" | "not_suspended" | null; + incompleteReason: "unavailable" | "not_suspended" | "provider_unopened" | null; notSuspendedRunId?: string | null; }> => { if (!remoteCommandRunner || !remoteStateDirectory) { @@ -15834,6 +15859,16 @@ async function createRunnerdBackendWithinSessionClaim( providerState, }); if (!providerSessionIdentityIsPresent(providerSessionIdentity)) { + if (source === "host_preparation" && remoteProviderStateNeverOpened(input.execution, providerState) + && provenOwnBootstrapRestart(typeof runnerState.runId === "string" ? runnerState.runId : null)) { + return { + complete: false, + runnerState: null, + providerSessionIdentity: null, + incompleteReason: "provider_unopened", + notSuspendedRunId: input.execution.binding.runId, + }; + } throw new Error(`runner_harness_state_mismatch: provider_identity_incomplete (${durableProviderCheckpointFailureReason(input.execution, providerState)})`); } const previousManifest = compatibleNativeHarnessBackupManifests({ @@ -16173,10 +16208,7 @@ async function createRunnerdBackendWithinSessionClaim( !state.runnerState || !state.providerSessionIdentity ) { - const provenRestart = state.incompleteReason === "not_suspended" && !backupAvailable - && input.restartRecovery?.kind === "bootstrap_incomplete" - && state.notSuspendedRunId === input.execution.binding.runId - && hasRemoteBootstrapRestartProof(input.execution.binding.runId) + const provenRestart = restartableBootstrapState(state) && !backupAvailable && await moveInterruptedBootstrapSessionAside() && takeRemoteBootstrapRestartProof(input.execution.binding.runId); // A resumed allocation that never held this session (for example @@ -16255,10 +16287,7 @@ async function createRunnerdBackendWithinSessionClaim( // lease was not provider-confirmed lost. Never silently create a new // provider session from that ambiguous state. throw new Error("runner_harness_state_mismatch: backup_without_reusable_lease"); - } else if (state.incompleteReason === "not_suspended" - && input.restartRecovery?.kind === "bootstrap_incomplete" - && state.notSuspendedRunId === input.execution.binding.runId - && hasRemoteBootstrapRestartProof(input.execution.binding.runId)) { + } else if (restartableBootstrapState(state)) { if (!(await moveInterruptedBootstrapSessionAside() && takeRemoteBootstrapRestartProof(input.execution.binding.runId) && await claimUntouchedRemoteSession())) { From 6d1eae73c0fd8f42884e7910b4a835d3215c8f31 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:16:27 -0600 Subject: [PATCH 26/38] fix(runner): do not count time the control plane was stopped against a Runner command wait (#20704) 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 > - The native runtime resumes a run after a control-plane restart. It launches a Runner and waits for recovery barriers (`run.attach`, a `runner.drain` probe, the provider identity). > - These waits poll with a wall-clock deadline. When the control plane and its Runner are stopped together (SIGSTOP, host sleep), the wall clock passes the deadline before either process can act. > - On thaw, the wait reports a timeout although nothing was slow. Recovery then spends an attempt and a retry delay. > - This pull request gives each startup or recovery admission a clock that does not count stopped time. > - The benefit is that a freeze or host sleep during an admission no longer turns into a false `PRP command ... timed out` failure. ## Linked Issues or Issue Description **What happened?** A restart-chaos wave (local, codex, fault TM2) stopped the server and its Runner tree for 44 s, 1 s after a resumed Runner started. The resume barrier `runner.drain` had a 30 s deadline. On thaw, the server reported `runner_local_connect_failed: PRP command runner.drain timed out` 45 s after the wait began (`provider.session.load` span 45130 ms). Recovery spent attempt 1 and waited 30 s more before attempt 2. **Expected behavior** Time that the waiting process spends stopped does not count as waiting time. A real timeout still fires when the Runner does not answer while both processes run. **Steps to reproduce** 1. Start a Runner command wait with a 30 s deadline. 2. After 1 s, stop the process for 44 s (the test moves the system clock without running timers). 3. Let the Runner complete the command 2 s after thaw. 4. Before this change, the wait rejects with `runner.drain timed out`. After this change, it resolves. Note: in that chaos task, this false timeout was not the reason that the task needed a manual Retry. An earlier SIGKILL of the whole server tree stopped the Codex turn while a foreground shell command (`./bench.sh`) was running. On restore, Codex had no active turn (`provider_turn_lost_on_restore`). Recovery correctly blocked automatic replay (`uncertain_provider_action`), because no durable record proves that the interrupted command had no side effect. The manual Retry then completed the task. This PR does not change that policy. Refs #20675 ## What Changed - `packages/paperclip-runner/src/live/runnerd-codex-transport.ts`: add `RunnerStallLedger`, the clock of one startup or recovery admission. `now()` is wall time minus the stopped time observed since the admission began. Its poll loops and a 1 s ticker share one last-observation time, so each stop is credited once, wherever the process was when it stopped (a poll loop, a checkpoint flush, a spawn). Only the part of a gap beyond 5 s is credited. - `#start` and `#resume` run under one ledger (`#withAdmissionClock`). A nested startup keeps the outer ledger. The ticker stops when the admission ends. - During an admission, `waitForRunnerCommand`, the provider-identity wait, the cold admission deadline, the recovery admission deadline, and the default 30 s command deadline all use this clock. - Waits after admission, including `turn.start` and its event and snapshot waits, keep wall-clock deadlines. Their behavior does not change. - Tests in `runnerd-codex-transport.test.ts`: the chaos sequence (red before, green after), the unchanged wall-clock timeout outside an admission, a barrier that still times out after a freeze, a 70 s freeze between two barriers on one cold deadline, and a slow-but-running process that still reaches its deadline. ## Verification - Red: `cd packages/paperclip-runner && npx vitest run src/live/runnerd-codex-transport.test.ts -t "stopped"` failed before the fix with `runner_local_connect_failed: PRP command runner.drain timed out`. - Green: the same command passes after the fix. - `npx vitest run src/live/runnerd-codex-transport.test.ts`: 301/301 pass, including the existing "shares Pi's absolute cold deadline across recovery barriers and rejects a late ACK" test. - `npx tsc --noEmit -p packages/paperclip-runner/tsconfig.json`: clean. - `pnpm verify` exits 2 (changes outside resolved test graphs). Required CI supplies the broad coverage. - Not run: a new chaos wave. The unit tests reproduce the exact wait and clock sequence from the artifacts. ## Risks - A real event-loop hang longer than 5 s during an admission now extends that admission by the hang minus 5 s. The Runner answer could not be observed during the hang either. Each credited gap still costs 5 s of budget, so a process that is slow on every observation still reaches its deadline. - The ticker runs only while a startup or recovery admission runs (an active operation), every 1 s, does no I/O, and is cleared in `finally`. It does not keep an idle process awake. - A `turn.start` that is cut by a freeze still reports a wall-clock timeout, as before. That case needs its own change, because its event and snapshot waits share one deadline. - No persisted state, launch identity, or saved-session shape changes. Old saved runs resume through the same code. A deploy mid-run only changes how long an in-process admission wait tolerates a stop. No new wait or file operation runs before `turn.start`. > 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 (Anthropic), model ID `claude-opus-5-5`, run in Claude Code with tool use (shell, file edit) and extended reasoning. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- .../src/live/runnerd-codex-transport.test.ts | 105 ++++++++++++++++- .../src/live/runnerd-codex-transport.ts | 107 ++++++++++++++++-- 2 files changed, 201 insertions(+), 11 deletions(-) diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts index 88ebd100055..ab762e4d317 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts @@ -4,7 +4,7 @@ import { runnerLaunchRequirementsDigest, type RunnerProviderLaunchRequirements, } from "./runner-provider-launch.js"; -import { coldAdmissionTimeoutMs, waitForRunnerCommand } from "./runnerd-codex-transport.js"; +import { coldAdmissionTimeoutMs, RUNNER_STALL_THRESHOLD_MS, RunnerStallLedger, waitForRunnerCommand } from "./runnerd-codex-transport.js"; import { configuredEnvironmentProjection } from "../configured-environment.js"; import { chmod, cp, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, stat, truncate, writeFile } from "node:fs/promises"; import { createHash } from "node:crypto"; @@ -6703,6 +6703,109 @@ it("shares Pi's absolute cold deadline across recovery barriers and rejects a la } finally { vi.useRealTimers(); } }); +// Chaos w-20261111T011704-s9107/t01: the control plane was stopped (SIGSTOP, as in +// a host sleep) 1 s into the resume barrier, together with the Runner it waits on. +// On thaw, the wall clock had passed the 30 s deadline before either process could +// act, so recovery reported "runner.drain timed out" and spent a recovery attempt. +describe("admission waits do not count time this process was stopped", () => { + const pending = (clock: RunnerStallLedger | undefined, deadline: number, status: () => string, type = "runner.drain") => + waitForRunnerCommand({ + type, deadline, clock, abortOnClose: true, isClosed: () => false, + throwIfFailed: () => undefined, command: () => ({ status: status() }), + runnerHasExited: async () => false, failureCode: () => "runner_local_connect_failed", + }); + + it("completes a resume barrier that the Runner answers after a 44 s freeze", async () => { + vi.useFakeTimers(); + const clock = new RunnerStallLedger(); + const stop = clock.watch(); + try { + let status = "pending"; + const drain = pending(clock, clock.now() + 30_000, () => status); + await vi.advanceTimersByTimeAsync(1_000); + // Stopped for 44 s: the wall clock moves, but no timer of this process runs. + vi.setSystemTime(Date.now() + 44_000); + await vi.advanceTimersByTimeAsync(2_000); + status = "completed"; + await vi.advanceTimersByTimeAsync(10); + await expect(drain).resolves.toBeUndefined(); + } finally { stop(); vi.useRealTimers(); } + }); + + it("keeps the wall-clock timeout for a wait outside an admission", async () => { + vi.useFakeTimers(); + try { + const drain = pending(undefined, Date.now() + 30_000, () => "pending"); + const rejection = expect(drain).rejects.toThrow("runner_local_connect_failed: PRP command runner.drain timed out"); + await vi.advanceTimersByTimeAsync(1_000); + vi.setSystemTime(Date.now() + 44_000); + await vi.advanceTimersByTimeAsync(10); + await rejection; + } finally { vi.useRealTimers(); } + }); + + it("still times out a barrier that the Runner never answers after a freeze", async () => { + vi.useFakeTimers(); + const clock = new RunnerStallLedger(); + const stop = clock.watch(); + try { + const drain = pending(clock, clock.now() + 30_000, () => "pending"); + const rejection = expect(drain).rejects.toThrow("runner_local_connect_failed: PRP command runner.drain timed out"); + await vi.advanceTimersByTimeAsync(1_000); + vi.setSystemTime(Date.now() + 44_000); + // Running time reaches the deadline: 1 s before, the uncredited 5 s of the + // gap, then the rest of the 30 s budget. + await vi.advanceTimersByTimeAsync(30_000); + await rejection; + } finally { stop(); vi.useRealTimers(); } + }); + + it("credits a freeze outside any poll loop to the next barrier on the same deadline", async () => { + vi.useFakeTimers(); + const clock = new RunnerStallLedger(); + const stop = clock.watch(); + try { + const deadline = clock.now() + coldAdmissionTimeoutMs("acpx", "pi", true); + let status = "pending"; + const prepared = pending(clock, clock.now() + 30_000, () => status, "run.prepare"); + await vi.advanceTimersByTimeAsync(5_000); + status = "completed"; + await vi.advanceTimersByTimeAsync(10); + await prepared; + // Stopped for 70 s between barriers (a checkpoint flush, a spawn): only the ticker observes it. + vi.setSystemTime(Date.now() + 70_000); + await vi.advanceTimersByTimeAsync(1_000); + status = "pending"; + const opened = pending(clock, deadline, () => status, "session.open"); + await vi.advanceTimersByTimeAsync(20_000); + status = "completed"; + await vi.advanceTimersByTimeAsync(10); + await expect(opened).resolves.toBeUndefined(); + } finally { stop(); vi.useRealTimers(); } + }); + + it("credits only stalls, so a slow but running process still reaches its deadline", () => { + let wall = 0; + const clock = new RunnerStallLedger(() => wall); + const deadline = clock.now() + 30_000; + // Every observation is 4.9 s apart on a loaded host: that is running time. + while (clock.now() < deadline) wall += 4_900; + expect(wall).toBeGreaterThanOrEqual(30_000); + expect(wall).toBeLessThan(35_000); + expect(clock.creditedMs).toBe(0); + // A 6 s gap is credited only beyond the stall threshold, and only once. + wall += 6_000; + clock.now(); + clock.now(); + expect(clock.creditedMs).toBe(6_000 - RUNNER_STALL_THRESHOLD_MS); + // A wall-clock grace taken now moves onto the clock without the earlier + // credit, so it keeps exactly its own running-time budget. + const wallGrace = wall + 5_000; + const onClock = wallGrace - clock.creditedMs; + expect(onClock - clock.now()).toBe(5_000); + }); +}); + it("aborts startup promptly on close while allowing the owned cleanup command to drain", async () => { vi.useFakeTimers(); try { diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index 3e38d1e2fb0..15cb01e41f8 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -4064,6 +4064,8 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { #nextTraceDebugSequence = 1; #traceRehydrationSpoolOverflow = false; readonly #traceFrameIndex = new RunnerdTraceFrameIndex(); + /** Clock of the startup or recovery admission in progress, if any. */ + #admissionClock: RunnerStallLedger | null = null; #startupSteps: { begin(name: RunnerdStartupStep["name"]): void; /** Move on only from the named open step (later reconnects are not startup milestones). */ @@ -5967,7 +5969,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { async #start( params: Record, ): Promise> { - const work = () => this.#withStartupSteps("bootstrap", () => this.#startWork(params)); + const work = () => this.#withAdmissionClock(() => this.#withStartupSteps("bootstrap", () => this.#startWork(params))); return this.options.measureOperation ? this.options.measureOperation("runner.transport.cold_start", work) : work(); } @@ -6219,10 +6221,42 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { } async #resume(): Promise { - const work = () => this.#withStartupSteps("resume", () => this.#resumeWork()); + const work = () => this.#withAdmissionClock(() => this.#withStartupSteps("resume", () => this.#resumeWork())); return this.options.measureOperation ? this.options.measureOperation("runner.transport.resume", work) : work(); } + /** + * One stopped-time clock per admission; a nested startup keeps the outer one. + * It covers the Runner command barriers and the provider-identity wait. The + * warm-transition and source-attachment reconnect polls keep their own + * wall-clock grace deadlines. + */ + async #withAdmissionClock(work: () => Promise): Promise { + if (this.#admissionClock !== null) return work(); + const clock = new RunnerStallLedger(); + const stopWatching = clock.watch(); + this.#admissionClock = clock; + try { + return await work(); + } finally { + stopWatching(); + if (this.#admissionClock === clock) this.#admissionClock = null; + } + } + + /** Wall time, or the admission clock while a startup or recovery runs. */ + #waitNow(): number { + return this.#admissionClock?.now() ?? Date.now(); + } + + /** Moves a wall-clock deadline onto the admission clock, without the stops already credited. */ + #onWaitClock(wallDeadline: number): number { + const clock = this.#admissionClock; + if (clock === null) return wallDeadline; + clock.now(); + return wallDeadline - clock.creditedMs; + } + async #resumeWork(): Promise { if (this.options.acpxCandidateAdmission?.agent === "antigravity") throw new Error("ACPX candidate durable runner recovery is not admitted"); this.#startupSteps?.begin("runner.runtime.stage"); @@ -6943,7 +6977,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { this.#assertStartupOpen(); const admissionDeadline = this.#sourceAttachmentDeadline === null ? this.#coldAdmissionDeadline(adoptedRunner === undefined) - : Math.min(Date.now() + 30_000, this.#sourceAttachmentDeadline); + : Math.min(this.#waitNow() + 30_000, this.#onWaitClock(this.#sourceAttachmentDeadline)); // An adopted runner is already live: no launch step (a launch span means a fresh process). if (adoptedRunner) this.#startupSteps?.end(); else this.#startupSteps?.begin("runner.process.launch"); @@ -7690,21 +7724,21 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { #coldAdmissionDeadline(coldProcess = true): number | undefined { const timeout = coldAdmissionTimeoutMs(this.options.provider, this.options.acpxAgent, coldProcess); // Preserve the existing independent waits for other providers and live adoption. - return timeout === 60_000 ? Date.now() + timeout : undefined; + return timeout === 60_000 ? this.#waitNow() + timeout : undefined; } async #waitForProviderIdentity( expectedEventType?: "harness.ready" | "session.started" | "session.resumed", - deadline = Date.now() + 30_000, + deadline = this.#waitNow() + 30_000, ): Promise { return this.options.measureOperation ? this.options.measureOperation("runner.transport.provider_identity", () => this.#waitForProviderIdentityWork(expectedEventType, deadline)) : this.#waitForProviderIdentityWork(expectedEventType, deadline); } async #waitForProviderIdentityWork( expectedEventType?: "harness.ready" | "session.started" | "session.resumed", - deadline = Date.now() + 30_000, + deadline = this.#waitNow() + 30_000, ): Promise { - while (Date.now() < deadline) { + while (this.#waitNow() < deadline) { this.#throwIfFailed(); if (this.#closed) throw new Error("runnerd transport closed during provider startup"); this.#pumpEvents(); @@ -7728,7 +7762,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { async #waitCommand( type: string, commandId?: string, - deadline = Date.now() + 30_000, + deadline = this.#waitNow() + 30_000, abortOnClose = false, ): Promise { return this.options.measureOperation ? this.options.measureOperation("runner.transport.command_ack", () => this.#waitCommandWork(type, commandId, deadline, abortOnClose)) : this.#waitCommandWork(type, commandId, deadline, abortOnClose); @@ -7737,12 +7771,13 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { async #waitCommandWork( type: string, commandId?: string, - deadline = Date.now() + 30_000, + deadline = this.#waitNow() + 30_000, abortOnClose = false, ): Promise { await waitForRunnerCommand({ type, deadline, + clock: this.#admissionClock, abortOnClose, isClosed: () => this.#closed, throwIfFailed: () => this.#throwIfFailed(), @@ -9165,10 +9200,61 @@ function closedAcpxRejection(message: unknown): string | null { ? message : null; } +/** + * A gap this long between two observations by a running process (its poll + * loops sleep 10 ms, its ticker 1 s) means the process was not running: + * SIGSTOP, host sleep, or a whole-process stall. + */ +export const RUNNER_STALL_THRESHOLD_MS = 5_000; +const RUNNER_STALL_TICK_MS = 1_000; + +/** + * The clock for one startup or recovery admission. Time this process spends + * stopped is not waiting time: the Runner it waits on is usually stopped with + * it (same host sleep or process tree), and could not answer. The wall clock + * still passes the deadline, so a thaw used to report a timeout before either + * process ran (chaos t01: "runner.drain timed out" 45 s into a 30 s wait that + * held a 44 s freeze). + * + * `now()` is wall time minus the stopped time observed since the ledger + * started. Poll loops and a 1 s ticker share one last-observation time, so a + * stop is credited once, wherever the process was when it stopped (a poll + * loop, a checkpoint flush, a spawn). Only the part of a gap beyond the + * threshold is credited, so a slow but running process still reaches its + * deadlines. Deadlines compared with `now()` must be taken from `now()`. + */ +export class RunnerStallLedger { + #creditedMs = 0; + #last: number; + constructor(private readonly wallNow: () => number = Date.now) { + this.#last = wallNow(); + } + + get creditedMs(): number { + return this.#creditedMs; + } + + now(): number { + const at = this.wallNow(); + if (at - this.#last > RUNNER_STALL_THRESHOLD_MS) this.#creditedMs += at - this.#last - RUNNER_STALL_THRESHOLD_MS; + this.#last = Math.max(this.#last, at); + return at - this.#creditedMs; + } + + /** Observes stops between poll loops; runs only while its admission runs. */ + watch(): () => void { + const ticker = setInterval(() => this.now(), RUNNER_STALL_TICK_MS); + ticker.unref?.(); + return () => clearInterval(ticker); + } +} + /** Shared polling path keeps startup cancellation separate from owned cleanup commands. */ export async function waitForRunnerCommand(input: { type: string; deadline: number; + /** Startup or recovery admission clock; `deadline` was taken from it. */ + clock?: RunnerStallLedger | null; abortOnClose: boolean; isClosed: () => boolean; throwIfFailed: () => void; @@ -9176,7 +9262,8 @@ export async function waitForRunnerCommand(input: { runnerHasExited: () => Promise; failureCode: () => string; }): Promise { - while (Date.now() < input.deadline) { + const now = () => input.clock ? input.clock.now() : Date.now(); + while (now() < input.deadline) { input.throwIfFailed(); if (input.abortOnClose && input.isClosed()) { throw new Error(`runnerd transport closed while waiting for ${input.type}`); From 855e241887e85292623a08ac99945e8a81703720 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:19:13 -0600 Subject: [PATCH 27/38] fix(server): record a long event-loop block with the deltas that name its cause (#20709) 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 > - One server process owns the controller leases of its runs, renews them on timers, and serves every request > - On a hosted instance, the process stopped for about 103 seconds without a restart. Every lease lapsed, and two runs needed a manual Retry (the symptom is fixed in #20694) > - Nobody can say what blocked the process. The server records no event-loop delay, and it has no CPU, GC or memory record for that minute > - This pull request logs one local line for each event-loop block of 2 s or more. The line holds the deltas that tell the possible causes apart, and a likely-cause class > - The benefit is that the next stall names its class (main-thread CPU, GC, paging, CPU throttling, host suspend, or a blocking sync call) and its exact time, so we can match it to the run timeline and fix the cause ## Linked Issues or Issue Description Refs #20694 **What happened?** On a hosted instance, the merged run-event timeline of all active runs had no events from 08:19:52.04Z to 08:21:35.37Z (103.3 s). Events from streaming runs arrived about every 0.5 s before and after the gap. The process did not restart (the run diagnostic shows an observer uptime of about 24 minutes when the reaper ran). The first event after the gap was a span with a 60 s timeout that ended after 103.5 s. Thus the timer callback ran about 43 s late. This agrees with a blocked event loop, or with a frozen process. Nothing in the process recorded which one. **Expected behavior** A long event-loop block is a product failure. It lapses every lease and freezes every user. The server must record each long block with enough data to identify its cause. **Steps to reproduce** 1. Start the server. 2. Block the main thread for more than 2 s, for example with a synchronous read on a slow disk or a busy loop. 3. Before this change: the logs show nothing. After this change: the logs show `event loop blocked for ms (likely )` with the measured deltas. ## What Changed - `server/src/event-loop-stall-monitor.ts` (new): one unref'd 1.5 s timeout, re-armed after each check, measures how late it runs. (Server startup creates no interval timers, so it is not a `setInterval`.) When a check is 2 s or more late, it logs once with these fields: - stall duration, start and end time (wall clock and monotonic clock) - process CPU (user and system), GC pause time and count (`perf_hooks` GC entries) - major and minor page faults, file-system reads and writes, voluntary and involuntary context switches (`process.resourceUsage()`) - cgroup v2 `throttled_usec` delta (Linux; read asynchronously, best effort) - RSS, heap and external memory - `likelyCause`: `host_suspended`, `gc`, `memory_paging`, `cpu_throttled`, `main_thread_cpu`, or `blocked_off_cpu` (sync file I/O, a sync child process, or another off-CPU wait) - `server/src/index.ts`: starts the monitor when the listener binds. It stops the monitor at the start of shutdown, and when a failed startup closes the listener. It writes the line with the existing `logger.warn`. - This is a local log line only. It is not the Telemetry path and not the Observability (OpenTelemetry) path. No data leaves the process. ## Verification - `pnpm --filter @paperclipai/server exec vitest run src/event-loop-stall-monitor.test.ts src/__tests__/server-startup-feedback-export.test.ts` (131 passed; the monitor file passed 5 runs in a row): - an 800 ms busy loop is recorded as `main_thread_cpu`, with the stall and CPU time - an 800 ms `Atomics.wait` (blocks without CPU, like a sync read on a stalled disk) is recorded as `blocked_off_cpu` - nothing is logged while the loop is responsive, or after `stop()` (injected clock) - the file-read delta of a stall is kept while the cgroup read is pending - server startup still creates no interval timer - a 100 s stall with 90 s of cgroup throttling is recorded as `cpu_throttled`, with the stall start and end times - each cause class is selected from its deltas - `pnpm --filter @paperclipai/server exec tsc --noEmit` passes. - CI supplies the broad server suites. ## Risks - Low risk. The timeout reads only process counters. Every 10 s it reads one small cgroup file asynchronously. It does not query the database or the network, so it does not keep an idle instance or its database awake. It is unref'd and stopped on shutdown. - `process.cpuUsage()` counts all threads of the process, not only the main thread. A busy libuv thread pool during a stall can make an off-CPU block look like `main_thread_cpu`. The raw deltas are in the line, so a reader can check this. - If a platform suspends and resumes the process, each resume can log one `host_suspended` line. This is expected and useful. - The monitor names the class of a block, not the call stack. If the class is not enough, the next step is a bounded CPU profile around the stall time. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used through Claude Code with tool use, shell, and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes (the module comment carries the contract) - [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 --- server/src/event-loop-stall-monitor.test.ts | 160 +++++++++++ server/src/event-loop-stall-monitor.ts | 288 ++++++++++++++++++++ server/src/index.ts | 9 + 3 files changed, 457 insertions(+) create mode 100644 server/src/event-loop-stall-monitor.test.ts create mode 100644 server/src/event-loop-stall-monitor.ts diff --git a/server/src/event-loop-stall-monitor.test.ts b/server/src/event-loop-stall-monitor.test.ts new file mode 100644 index 00000000000..303630709d3 --- /dev/null +++ b/server/src/event-loop-stall-monitor.test.ts @@ -0,0 +1,160 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + classifyEventLoopStall, + startEventLoopStallMonitor, + type EventLoopStall, +} from "./event-loop-stall-monitor.js"; + +const waitFor = async (predicate: () => boolean, timeoutMs = 5_000) => { + const deadline = Date.now() + timeoutMs; + while (!predicate()) { + if (Date.now() > deadline) throw new Error("timed out waiting for the stall report"); + await new Promise((resolve) => setTimeout(resolve, 10)); + } +}; + +const blockWithCpu = (ms: number) => { + const until = Date.now() + ms; + let spin = 0; + while (Date.now() < until) spin += 1; + return spin; +}; + +// Blocks the main thread without using CPU, like a sync read on a stalled disk +// or a sync child process. +const blockOffCpu = (ms: number) => { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); +}; + +describe("event-loop stall monitor", () => { + const stops: Array<() => void> = []; + afterEach(() => { + while (stops.length > 0) stops.pop()!(); + vi.useRealTimers(); + }); + + const start = (options: Parameters[0]) => { + const monitor = startEventLoopStallMonitor(options); + stops.push(monitor.stop); + return monitor; + }; + + it("records a main-thread CPU block with its duration and CPU time", async () => { + const stalls: EventLoopStall[] = []; + const caused = () => stalls.filter((stall) => stall.stallMs >= 700); + start({ log: (stall) => stalls.push(stall), intervalMs: 20, thresholdMs: 250, probes: { readCgroupThrottledUsec: async () => null } }); + await new Promise((resolve) => setTimeout(resolve, 60)); + + blockWithCpu(800); + await waitFor(() => caused().length > 0); + + // A loaded runner can add unrelated pauses; check the one this test caused. + const [stall] = caused(); + expect(stall!.cpuUserMs + stall!.cpuSystemMs).toBeGreaterThanOrEqual(400); + expect(stall!.likelyCause).toBe("main_thread_cpu"); + expect(Date.parse(stall!.stallEndedAt) - Date.parse(stall!.stallStartedAt)).toBeGreaterThanOrEqual(700); + }); + + it("records an off-CPU block, such as sync I/O, as blocked_off_cpu", async () => { + const stalls: EventLoopStall[] = []; + const caused = () => stalls.filter((stall) => stall.stallMs >= 700); + start({ log: (stall) => stalls.push(stall), intervalMs: 20, thresholdMs: 250, probes: { readCgroupThrottledUsec: async () => null } }); + await new Promise((resolve) => setTimeout(resolve, 60)); + + blockOffCpu(800); + await waitFor(() => caused().length > 0); + + const [stall] = caused(); + expect(stall!.likelyCause).toBe("blocked_off_cpu"); + }); + + const fakeProbes = (state: { monotonic: number; throttledUsec: number | null; fsRead: number }) => ({ + monotonicNow: () => state.monotonic, + wallNow: () => 1_794_298_792_000 + state.monotonic, + cpuUsage: () => ({ user: 0, system: 0 }), + resourceUsage: () => ({ + majorPageFault: 0, minorPageFault: 0, fsRead: state.fsRead, fsWrite: 0, + voluntaryContextSwitches: 0, involuntaryContextSwitches: 0, + }), + readCgroupThrottledUsec: async () => state.throttledUsec, + }); + + it("stays silent while the loop is responsive and after stop", async () => { + vi.useFakeTimers(); + const state = { monotonic: 0, throttledUsec: null, fsRead: 0 }; + const log = vi.fn(); + const monitor = start({ log, intervalMs: 500, thresholdMs: 2_000, gcEntries: () => [], probes: fakeProbes(state) }); + for (let tick = 1; tick <= 10; tick++) { + state.monotonic = tick * 500 + 100; + await vi.advanceTimersByTimeAsync(500); + } + expect(log).not.toHaveBeenCalled(); + + monitor.stop(); + state.monotonic += 60_000; + await vi.advanceTimersByTimeAsync(5_000); + expect(log).not.toHaveBeenCalled(); + }); + + it("keeps the I/O deltas of the stall while the cgroup read is pending", async () => { + vi.useFakeTimers(); + const state = { monotonic: 0, throttledUsec: 5_000_000 as number | null, fsRead: 10 }; + const stalls: EventLoopStall[] = []; + start({ log: (stall) => stalls.push(stall), intervalMs: 500, thresholdMs: 2_000, gcEntries: () => [], probes: fakeProbes(state) }); + await vi.advanceTimersByTimeAsync(0); + + state.monotonic = 100_500; + state.fsRead = 4_010; + await vi.advanceTimersByTimeAsync(500); + + expect(stalls).toHaveLength(1); + expect(stalls[0]).toMatchObject({ fsReads: 4_000, cgroupThrottledMs: 0, likelyCause: "blocked_off_cpu" }); + }); + + it("reports cgroup throttling measured across the stall", async () => { + vi.useFakeTimers(); + let monotonic = 0; + let throttledUsec = 1_000_000; + const stalls: EventLoopStall[] = []; + start({ + log: (stall) => stalls.push(stall), + intervalMs: 500, + thresholdMs: 2_000, + gcEntries: () => [], + probes: { + monotonicNow: () => monotonic, + wallNow: () => 1_794_298_792_000 + monotonic, + cpuUsage: () => ({ user: 0, system: 0 }), + resourceUsage: () => ({ + majorPageFault: 0, minorPageFault: 0, fsRead: 0, fsWrite: 0, + voluntaryContextSwitches: 0, involuntaryContextSwitches: 0, + }), + readCgroupThrottledUsec: async () => throttledUsec, + }, + }); + await vi.advanceTimersByTimeAsync(0); + + monotonic = 100_500; + throttledUsec += 90_000_000; + await vi.advanceTimersByTimeAsync(500); + + expect(stalls).toHaveLength(1); + expect(stalls[0]).toMatchObject({ + stallMs: 100_000, + stallStartedAt: "2026-11-10T08:19:52.000Z", + stallEndedAt: "2026-11-10T08:21:32.500Z", + cgroupThrottledMs: 90_000, + likelyCause: "cpu_throttled", + }); + }); + + it("classifies each cause from the measured deltas", () => { + const base = { stallMs: 100_000, monotonicElapsedMs: 100_500, wallElapsedMs: 100_500, cpuMs: 0, gcPauseMs: 0, majorPageFaults: 0, cgroupThrottledMs: null }; + expect(classifyEventLoopStall(base)).toBe("blocked_off_cpu"); + expect(classifyEventLoopStall({ ...base, cpuMs: 99_000 })).toBe("main_thread_cpu"); + expect(classifyEventLoopStall({ ...base, cpuMs: 99_000, gcPauseMs: 95_000 })).toBe("gc"); + expect(classifyEventLoopStall({ ...base, majorPageFaults: 50_000 })).toBe("memory_paging"); + expect(classifyEventLoopStall({ ...base, cgroupThrottledMs: 80_000 })).toBe("cpu_throttled"); + expect(classifyEventLoopStall({ ...base, monotonicElapsedMs: 500 })).toBe("host_suspended"); + }); +}); diff --git a/server/src/event-loop-stall-monitor.ts b/server/src/event-loop-stall-monitor.ts new file mode 100644 index 00000000000..989bbc6b279 --- /dev/null +++ b/server/src/event-loop-stall-monitor.ts @@ -0,0 +1,288 @@ +import { readFile } from "node:fs/promises"; +import { PerformanceObserver, performance, type PerformanceEntry } from "node:perf_hooks"; + +// Records a long event-loop block as one local log line. Nothing leaves the +// process: this is neither the Telemetry nor the Observability path. +// +// A timer that should fire every `intervalMs` measures how late it ran. When it +// is late by `thresholdMs` or more, the line carries the process-level deltas +// that tell the usual causes apart: +// - main-thread CPU work (sync JSON, regex, hashing, compression): CPU ≈ stall +// - garbage collection: GC pause time ≈ stall +// - memory paging: many major page faults +// - host suspend: wall clock advanced far more than the monotonic clock +// - CPU throttling by the container: cgroup throttled time grows +// - sync file I/O or a sync child process: little CPU, none of the above +// +// The timer reads only process counters (and, every ten seconds, the cgroup's +// cpu.stat). It never queries the database or the network, so it does not keep +// an idle instance or its database awake; it is unref'd and stopped on shutdown. +export type EventLoopStallCause = + | "gc" + | "main_thread_cpu" + | "memory_paging" + | "host_suspended" + | "cpu_throttled" + | "blocked_off_cpu"; + +export type EventLoopStall = { + stallMs: number; + monotonicElapsedMs: number; + wallElapsedMs: number; + stallStartedAt: string; + stallEndedAt: string; + likelyCause: EventLoopStallCause; + cpuUserMs: number; + cpuSystemMs: number; + gcPauseMs: number; + gcCount: number; + majorPageFaults: number; + minorPageFaults: number; + fsReads: number; + fsWrites: number; + voluntaryContextSwitches: number; + involuntaryContextSwitches: number; + cgroupThrottledMs: number | null; + rssBytes: number; + heapUsedBytes: number; + heapTotalBytes: number; + externalBytes: number; + arrayBuffersBytes: number; + processUptimeSec: number; +}; + +type ResourceSample = Pick< + NodeJS.ResourceUsage, + | "majorPageFault" + | "minorPageFault" + | "fsRead" + | "fsWrite" + | "voluntaryContextSwitches" + | "involuntaryContextSwitches" +>; + +export type EventLoopStallProbes = { + monotonicNow: () => number; + wallNow: () => number; + cpuUsage: () => NodeJS.CpuUsage; + resourceUsage: () => ResourceSample; + memoryUsage: () => NodeJS.MemoryUsage; + uptimeSec: () => number; + // Total time this process's cgroup was CPU-throttled, in microseconds, or null. + readCgroupThrottledUsec: () => Promise; +}; + +export type EventLoopStallMonitorOptions = { + log: (stall: EventLoopStall) => void; + intervalMs?: number; + thresholdMs?: number; + probes?: Partial; + // GC pause entries can be supplied by a test; by default a GC observer is used. + gcEntries?: () => readonly Pick[]; +}; + +export const EVENT_LOOP_STALL_INTERVAL_MS = 1_500; +export const EVENT_LOOP_STALL_THRESHOLD_MS = 2_000; +const CGROUP_SAMPLE_INTERVAL_MS = 10_000; +const MAX_GC_ENTRIES = 512; +const MAJOR_FAULTS_FOR_PAGING = 1_000; + +async function readCgroupV2ThrottledUsec(): Promise { + if (process.platform !== "linux") return null; + try { + const stat = await readFile("/sys/fs/cgroup/cpu.stat", "utf8"); + const match = /^throttled_usec\s+(\d+)$/m.exec(stat); + return match ? Number(match[1]) : null; + } catch { + return null; + } +} + +const defaultProbes: EventLoopStallProbes = { + monotonicNow: () => performance.now(), + wallNow: () => Date.now(), + cpuUsage: () => process.cpuUsage(), + resourceUsage: () => process.resourceUsage(), + memoryUsage: () => process.memoryUsage(), + uptimeSec: () => process.uptime(), + readCgroupThrottledUsec: readCgroupV2ThrottledUsec, +}; + +export function classifyEventLoopStall(input: { + stallMs: number; + monotonicElapsedMs: number; + wallElapsedMs: number; + cpuMs: number; + gcPauseMs: number; + majorPageFaults: number; + cgroupThrottledMs: number | null; +}): EventLoopStallCause { + const half = input.stallMs / 2; + if (input.wallElapsedMs - input.monotonicElapsedMs >= half) return "host_suspended"; + if (input.gcPauseMs >= half) return "gc"; + if (input.majorPageFaults >= MAJOR_FAULTS_FOR_PAGING) return "memory_paging"; + if (input.cgroupThrottledMs !== null && input.cgroupThrottledMs >= half) return "cpu_throttled"; + if (input.cpuMs >= half) return "main_thread_cpu"; + return "blocked_off_cpu"; +} + +export function startEventLoopStallMonitor(options: EventLoopStallMonitorOptions): { stop: () => void } { + const probes = { ...defaultProbes, ...options.probes }; + const intervalMs = options.intervalMs ?? EVENT_LOOP_STALL_INTERVAL_MS; + const thresholdMs = options.thresholdMs ?? EVENT_LOOP_STALL_THRESHOLD_MS; + + let gcObserver: PerformanceObserver | null = null; + const observedGc: Pick[] = []; + let gcEntries = options.gcEntries; + if (!gcEntries) { + try { + gcObserver = new PerformanceObserver((list) => { + for (const entry of list.getEntries()) { + observedGc.push({ startTime: entry.startTime, duration: entry.duration }); + } + if (observedGc.length > MAX_GC_ENTRIES) observedGc.splice(0, observedGc.length - MAX_GC_ENTRIES); + }); + gcObserver.observe({ entryTypes: ["gc"] }); + } catch { + gcObserver = null; + } + gcEntries = () => observedGc; + } + + let lastMonotonic = probes.monotonicNow(); + let lastWall = probes.wallNow(); + let lastCpu = probes.cpuUsage(); + let lastResources = probes.resourceUsage(); + let cgroupBaseline: number | null = null; + let cgroupSampledAt = Number.NEGATIVE_INFINITY; + let cgroupReading = false; + let stopped = false; + + const sampleCgroup = () => { + if (cgroupReading || stopped) return; + cgroupReading = true; + void probes.readCgroupThrottledUsec() + .then((value) => { cgroupBaseline = value; }) + .catch(() => { cgroupBaseline = null; }) + .finally(() => { cgroupReading = false; }); + }; + + const check = () => { + const monotonic = probes.monotonicNow(); + const wall = probes.wallNow(); + const monotonicElapsedMs = monotonic - lastMonotonic; + const wallElapsedMs = wall - lastWall; + // A host suspend may stop the monotonic clock, so use the larger of the two. + const stallMs = Math.max(monotonicElapsedMs, wallElapsedMs) - intervalMs; + if (stallMs >= thresholdMs) { + const cpu = probes.cpuUsage(); + const resources = probes.resourceUsage(); + const memory = probes.memoryUsage(); + const windowStart = lastMonotonic; + let gcPauseMs = 0; + let gcCount = 0; + for (const entry of gcEntries!()) { + if (entry.startTime + entry.duration < windowStart || entry.startTime > monotonic) continue; + gcPauseMs += entry.duration; + gcCount += 1; + } + const cpuUserMs = (cpu.user - lastCpu.user) / 1000; + const cpuSystemMs = (cpu.system - lastCpu.system) / 1000; + // Compute every delta now: the cgroup read below is asynchronous, and + // later ticks replace the baselines before it settles. + const previous = lastResources; + const majorPageFaults = resources.majorPageFault - previous.majorPageFault; + const minorPageFaults = resources.minorPageFault - previous.minorPageFault; + const fsReads = resources.fsRead - previous.fsRead; + const fsWrites = resources.fsWrite - previous.fsWrite; + const voluntaryContextSwitches = resources.voluntaryContextSwitches - previous.voluntaryContextSwitches; + const involuntaryContextSwitches = resources.involuntaryContextSwitches - previous.involuntaryContextSwitches; + const uptimeSec = Math.round(probes.uptimeSec()); + const baseline = cgroupBaseline; + const stallStartedAt = new Date(lastWall).toISOString(); + const stallEndedAt = new Date(wall).toISOString(); + const report = (cgroupThrottledMs: number | null) => { + const rounded = Math.round(stallMs); + options.log({ + stallMs: rounded, + monotonicElapsedMs: Math.round(monotonicElapsedMs), + wallElapsedMs: Math.round(wallElapsedMs), + stallStartedAt, + stallEndedAt, + likelyCause: classifyEventLoopStall({ + stallMs: rounded, + monotonicElapsedMs, + wallElapsedMs, + cpuMs: cpuUserMs + cpuSystemMs, + gcPauseMs, + majorPageFaults, + cgroupThrottledMs, + }), + cpuUserMs: Math.round(cpuUserMs), + cpuSystemMs: Math.round(cpuSystemMs), + gcPauseMs: Math.round(gcPauseMs), + gcCount, + majorPageFaults, + minorPageFaults, + fsReads, + fsWrites, + voluntaryContextSwitches, + involuntaryContextSwitches, + cgroupThrottledMs, + rssBytes: memory.rss, + heapUsedBytes: memory.heapUsed, + heapTotalBytes: memory.heapTotal, + externalBytes: memory.external, + arrayBuffersBytes: memory.arrayBuffers, + processUptimeSec: uptimeSec, + }); + }; + // Throttled time is read after the stall; the baseline is at most one + // sampling interval older than the stall start, so the delta can include + // a few seconds before it. + if (baseline === null) { + report(null); + } else { + void probes.readCgroupThrottledUsec() + .then((after) => stopped ? undefined : report(after === null ? null : Math.round((after - baseline) / 1000))) + .catch(() => report(null)); + } + cgroupSampledAt = Number.NEGATIVE_INFINITY; + lastCpu = cpu; + lastResources = resources; + } else { + lastCpu = probes.cpuUsage(); + lastResources = probes.resourceUsage(); + } + lastMonotonic = monotonic; + lastWall = wall; + if (monotonic - cgroupSampledAt >= CGROUP_SAMPLE_INTERVAL_MS) { + cgroupSampledAt = monotonic; + sampleCgroup(); + } + }; + + // One pending unref'd timeout, re-armed after each check. Server startup + // creates no interval timers, and this probe is not a work scan. + let timer: NodeJS.Timeout | null = null; + const arm = () => { + if (stopped) return; + timer = setTimeout(() => { + timer = null; + check(); + arm(); + }, intervalMs); + (timer as Partial).unref?.(); + }; + arm(); + sampleCgroup(); + cgroupSampledAt = lastMonotonic; + + return { + stop: () => { + stopped = true; + if (timer) clearTimeout(timer); + gcObserver?.disconnect(); + }, + }; +} diff --git a/server/src/index.ts b/server/src/index.ts index dfa92d5a9ad..37a0c42d20e 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -132,6 +132,7 @@ import { drainHttpRequestWork } from "./middleware/idle-admission.js"; import { initializeCloudRuntimeConfig } from "./services/cloud-runtime-config.js"; import { loadCloudBootstrapConfig, loadConfig, type Config } from "./config.js"; import { logger } from "./middleware/logger.js"; +import { startEventLoopStallMonitor } from "./event-loop-stall-monitor.js"; import { setStartupRecoveryPhase } from "./startup-recovery-state.js"; import { StartupRefusalError, @@ -1090,6 +1091,13 @@ async function startServerWithDatabaseTeardown( }); }); startupListenerBound = true; + // A blocked event loop lapses every controller lease and freezes every + // request, so record each long block with the deltas that name its class. + const eventLoopStallMonitor = startEventLoopStallMonitor({ + log: (stall) => logger.warn({ eventLoopStall: stall }, `event loop blocked for ${stall.stallMs} ms (likely ${stall.likelyCause})`), + }); + // A failed startup closes the listener without the ordered shutdown path. + server.once("close", () => eventLoopStallMonitor.stop()); // The factory publishes the verified numeric endpoint on listening. Native // recovery must never fall back to a configured/public URL if it is absent. resolveLocalRuntimeApiUrl(); @@ -2062,6 +2070,7 @@ async function startServerWithDatabaseTeardown( ) => { const shutdownStartedAt = Date.now(); logger.info({ signal }, "shutdown signal received; starting ordered shutdown"); + eventLoopStallMonitor.stop(); setStartupRecoveryPhase("draining"); for (const client of liveEventsWebSocketServer.clients) client.close(1012, "Server restarting"); liveEventsWebSocketServer.close(); From 08ea18085e2d0751ca5a7da1268f0dede20eb4cb Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:19:43 -0600 Subject: [PATCH 28/38] fix(workspaces): restore a saved workspace into one copy of sandbox disk (#20695) 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 > - A task on a remote (Daytona) sandbox continues from its saved workspace. Before the agent starts, the server uploads the saved archive into the sandbox and a sandbox script extracts it. > - The extraction wrote a full second copy of the workspace beside the uploaded archive. A 7.5 GB workspace on a fresh sandbox then needed about 15 GB, and the restore failed with `stage=extract code=ENOSPC disk=full`. > - The failure was classified as retryable, so every automatic retry and every Retry repeated it on a same-size sandbox. The task could not continue. > - On a retained sandbox it is worse: the old root, the archive, and the new tree all share the disk. > - This pull request makes the restore need about one copy of the workspace. The sandbox removes only data that control-plane storage already holds durably, and it never removes a root whose save the server did not prove. > - The benefit is that a workspace that fits once on the sandbox disk restores. A disk that is too small for one copy now gets a named failure that does not loop. ## Linked Issues or Issue Description **What happened?** A saved remote workspace of about 7.5 GB could not be restored on a new Daytona sandbox. The run failed with `remote_workspace_restore_failed: step=sandbox_restore; remote_workspace_operation_failed: operation=restore exit=1; remote_workspace_restore_failed: stage=extract code=ENOSPC disk=full exit=1`. The run marked the failure as retryable, and each retry failed the same way. **Steps to reproduce** 1. Save a remote workspace whose archive is larger than half of the free sandbox disk. 2. Start the next run on another sandbox, so that the server restores the saved archive. 3. The upload succeeds. The extraction writes the second copy and fails with ENOSPC. **Expected behavior** A workspace that fits once on the sandbox disk restores. A disk that cannot hold one copy gives a specific failure that is not retried automatically, and Retry works after the sandbox has more space. **What the disk holds during a restore (from the code)** - The uploaded archive (`/.paperclip-runtime/workspace-snapshots//workspace.pcws`, about the workspace size, because the archive is not compressed). - The extracted tree (`.restoring-*`, the workspace size). - On a retained sandbox only: the old root, which stayed until after the new root was published. - After a restore that died: its partial tree and its archive, which no later attempt removed. Refs #20678 (the save side of the same full-disk class). ## What Changed - `workspaceArchive` restore has a `consumeArchive` mode. It creates the directories and symlinks first, then writes the file bodies from the last to the first. After it verifies each file against the manifest hash, it truncates the archive behind that file. The archive and the tree together need the workspace size plus the largest file. The default mode, which the server uses for local restores, does not change. - The sandbox restore script uses that mode on a private rename of the uploaded archive. A later upload to the same path cannot change the file that is being consumed. The script removes the consumed file when it stops. - The helper's own staging is now inside the root-specific `.restoring-*` folder, not in a shared `.workspace-restore-*` sibling. - While it holds the root's restore lock, and after the epoch fence, the script removes leftovers of an earlier attempt on the same root that died: `.restoring-*` folders, `.consuming` archives in its own staging, and archive staging folders that a `restore-target.json` binds to the same root. Each restore writes that binding after the reclaim step. - When the server proved that a retained root is its own earlier, fully saved allocation (`replaceRetiredRoot` and a Paperclip receipt, as before), the script removes the root's files before the extraction, not after the publish. The receipt and `.paperclip-runtime` stay, so an interrupted restore proves the same root again and continues. - A full disk at any restore stage reports `reason=sandbox_disk_full`. The existing named-refusal rule makes it non-retryable, so it goes to the board recovery action and does not loop. - `doc/execution-semantics.md` describes the disk need, the reclaim, the early removal, and the new reason. ## Verification - `cd server && npx vitest run src/services/remote-workspace-transport.test.ts src/services/remote-workspace-snapshot-archive.test.ts` (287 passed). - `cd server && npx vitest run src/services/remote-workspaces.integration.test.ts src/services/remote-workspace-lifecycle.test.ts src/services/remote-workspace-archive-worker.test.ts src/services/remote-workspace-snapshot-archive-environments.test.ts` (122 passed, 16 skipped). - `cd server && npx tsc --noEmit -p tsconfig.json` (pass). - The new tests run the real sandbox scripts against a folder with a byte capacity. A `--require` preload makes each file write fail with ENOSPC when the folder would exceed the capacity. - Red on `origin/master`, green with this change: - Fresh sandbox, room for the archive plus one file: master fails with the exact production error `stage=extract code=ENOSPC disk=full exit=1`. The fix restores every byte and leaves only the restored files. - Retained root that the server proved, room for the old root, the archive, and one file: master fails with ENOSPC. The fix restores and keeps the runner state. - Too small for one copy: the failure is `stage=extract reason=sandbox_disk_full`, with no partial tree or archive left. A retry with more space then restores. - Both sandbox processes are killed mid-extraction (a restart): a retry with the same identity and a retry with a new identity and epoch both reclaim the leftovers and restore into the same capacity. - The command dies right after it removed a proven root's files: the next restore proves the root again from its kept receipt, restores, and keeps the runner state. - Integration test through `prepareRemoteWorkspace`: a full disk gives `retryable: false` with `reason=sandbox_disk_full`. On master the same case is `retryable: true`. - Guards (pass on master and with the fix): a retained root without the server proof, or without a Paperclip receipt, is refused with `reason=occupied_root`, and none of its files are removed. - Previous-release story: the archive format and the saved state do not change. A partial `.restoring-*` tree from the previous release is reclaimed (test). Archive staging from the previous release has no binding, so it is kept (test). The previous release's shared `.workspace-restore-*` siblings cannot be bound to a root, so they are kept. ## Risks - The consumed archive cannot be read again. Each restore uploads a new copy from control-plane storage, and the early-return path for an already restored root does not read the archive. Every file is still checked against the manifest, and the manifest is checked against the saved digest. - The reclaim step removes data only under the root's restore lock and after the epoch fence. It removes only names that a restore of the same root creates. Staging that names another root, or no root, is kept. - The early removal of a retained root depends on the existing server proof (`isRetiredOwnAllocation`) and the receipt check. If a restore fails after the removal, the saved version in storage is the source of truth, and the next restore proves the same root again. - Files in a lower overlay layer of a resumed sandbox image do not free space when they are removed. Such a sandbox can still be full. - A workspace that is larger than the free disk after the upload, plus its largest file, still fails. It now fails with the named, non-retryable `reason=sandbox_disk_full`. - No change to `packages/paperclip-runner`, the database schema, or the API. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used through 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 - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] 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 --- doc/execution-semantics.md | 23 +- .../remote-workspace-snapshot-archive.ts | 31 +- .../remote-workspace-transport.test.ts | 302 +++++++++++++++++- .../services/remote-workspace-transport.ts | 97 +++++- .../remote-workspaces.integration.test.ts | 22 +- 5 files changed, 451 insertions(+), 24 deletions(-) diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index d58586a675b..b788e06ff84 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -1449,6 +1449,22 @@ folder), or an exhausted budget leaves a board-owned recovery action. Stranded-w recovery names this failure for the statuses it scans; for other statuses, such as a `blocked` task woken by a reply, the failure path records the action directly. +A restore needs about one workspace of sandbox disk, not two. The uploaded +archive is a disposable copy of a saved version that control-plane storage +already holds, and the sandbox checks every file against that version's +manifest. Extraction writes the files from the last to the first and shortens the +archive behind each one, so the archive and the restored tree together need the +workspace size plus the largest file. Before the upload, a reclaim step takes the +root's restore lock and checks the epoch fence. It removes what an earlier attempt +on that root left when it died: a `.restoring-*` partial tree, an archive it +was uploading or consuming, and archive staging that names the same root. Each +attempt names its staging before its upload starts. Staging that an earlier +release left without that name is kept. A sandbox that still cannot hold one copy +fails with `reason=sandbox_disk_full` at the stage that ran out of space (`helper`, +`upload`, or a restore script stage). A retry on the same disk would fail again, +so it is not retried automatically. The board recovery action's Retry works once +the sandbox has room for the workspace. + A retained sandbox can still hold a workspace's earlier root after the workspace moved to another allocation, for example when child tasks that an older release bound to a parent's workspace saved newer work on their own sandboxes. When the parent wakes on its @@ -1458,7 +1474,12 @@ recorded use of that root on this sandbox is an earlier epoch that ended in a quiesced, committed final save, and the folder carries a Paperclip preparation or restore receipt. Its files are then already part of the saved lineage being restored. Any other occupant (no receipt, a later unsaved use, or a sandbox that -never saved that root) is still refused with `reason=occupied_root`. The replaced +never saved that root) is still refused with `reason=occupied_root`, and none of +its files are removed. After that proof, the reclaim step removes the root's files +before the saved archive is uploaded, so the old copy never shares the disk with +the new one. Its receipt and `.paperclip-runtime` stay until the restored root is +published, so a restore interrupted after the removal proves the same root again +and finishes from the saved version. The replaced root's `.paperclip-runtime` state, such as a retained runner session, is never in a snapshot and belongs to the sandbox, so it moves into the restored root. Only the old preparation or restore receipt and export staging are dropped. A retained diff --git a/server/src/services/remote-workspace-snapshot-archive.ts b/server/src/services/remote-workspace-snapshot-archive.ts index 990d92f1fc8..57339a6fbaa 100644 --- a/server/src/services/remote-workspace-snapshot-archive.ts +++ b/server/src/services/remote-workspace-snapshot-archive.ts @@ -26,6 +26,14 @@ export async function workspaceArchive(input: { maxEntries?: number; maxManifestBytes?: number; singlePass?: boolean; + /** + * Restore only: give the archive's space back while extracting. Files are + * written from the last body to the first and the archive is truncated + * behind each one, so the archive and the restored tree together need about + * one workspace of space plus the largest file. The archive is unusable + * afterwards; use this only for a disposable copy of a durably saved archive. + */ + consumeArchive?: boolean; }): Promise<{ schema: "paperclip.remote-workspace-archive.v1"; manifestDigest: string; byteSize: number; sha256: string; entries: number }> { const fs = await import("node:fs/promises"); const { createReadStream } = await import("node:fs"); @@ -633,7 +641,7 @@ export async function workspaceArchive(input: { if (!input.targetDir || !/^[a-f0-9]{64}$/.test(input.expectedManifestDigest ?? "")) fail("restore_binding_invalid"); if (input.maxEntries !== undefined && (!Number.isSafeInteger(input.maxEntries) || input.maxEntries < 0)) fail("restore_binding_invalid"); if (input.maxManifestBytes !== undefined && (!Number.isSafeInteger(input.maxManifestBytes) || input.maxManifestBytes < 0)) fail("restore_binding_invalid"); - const archive = await fs.open(input.archivePath, "r"); + const archive = await fs.open(input.archivePath, input.consumeArchive === true ? "r+" : "r"); let staging: string | undefined; const stagedDirectories: string[] = []; try { @@ -663,19 +671,29 @@ export async function workspaceArchive(input: { kinds.set(entry.path, entry.type); } if (!Number.isSafeInteger(bodySize) || (await archive.stat()).size !== prefix.length + manifestSize + bodySize) fail("size_mismatch"); + const archiveSize = prefix.length + manifestSize + bodySize; const parent = await fs.realpath(path.dirname(input.targetDir!)); const existing = await fs.lstat(input.targetDir!).catch((error: NodeJS.ErrnoException) => { if (error.code !== "ENOENT") throw error; return null; }); if (existing && (!existing.isDirectory() || existing.isSymbolicLink() || (await fs.readdir(input.targetDir!)).length)) fail("target_not_empty"); check(); staging = await fs.mkdtemp(path.join(parent, ".workspace-restore-")); - let offset = prefix.length + manifestSize; + // Each file body starts where the previous one ends. A consuming restore + // writes the bodies last to first and truncates the archive behind each. + const offsets = new Map(); + let next = prefix.length + manifestSize; + for (const entry of manifest.entries) if (entry.type === "file") { offsets.set(entry, next); next += entry.size!; } + const consume = input.consumeArchive === true; + const ordered = consume + ? [...manifest.entries.filter(entry => entry.type !== "file"), ...manifest.entries.filter(entry => entry.type === "file").reverse()] + : manifest.entries; const buffer = Buffer.alloc(1024 * 1024); - for (const entry of manifest.entries) { + for (const entry of ordered) { check(); const target = path.join(staging, entry.path); if (entry.type === "directory") { await fs.mkdir(target, { mode: 0o700 }); stagedDirectories.push(target); } else if (entry.type === "symlink") await fs.symlink(entry.target!, target); else { const output = await fs.open(target, "wx", 0o600), digest = crypto.createHash("sha256"); + let offset = offsets.get(entry)!; try { let remaining = entry.size!; while (remaining) { @@ -687,12 +705,15 @@ export async function workspaceArchive(input: { if (digest.digest("hex") !== entry.sha256) fail("file_hash_mismatch"); } finally { await output.close(); } await fs.chmod(target, entry.mode!); + if (consume) await archive.truncate(offsets.get(entry)!); } } for (const entry of manifest.entries.filter(entry => entry.type === "directory").reverse()) { check(); await fs.chmod(path.join(staging, entry.path), entry.mode!); } - const content = await hashFile(input.archivePath); + // Every body was checked against the manifest, whose digest was checked + // against the expected one; a consumed archive has no bytes left to hash. + const content = consume ? { sha256: "", byteSize: archiveSize } : await hashFile(input.archivePath); check(); await fs.rename(staging, input.targetDir!); staging = undefined; return { schema, manifestDigest: input.expectedManifestDigest!, ...content, entries: manifest.entries.length }; @@ -865,5 +886,5 @@ export function remoteWorkspaceFailureDetail(error: unknown): string { export function remoteWorkspaceArchiveScript(): string { // tsx's function-name preservation helper may appear in Function#toString. const source = workspaceArchive.toString().replaceAll("__vite_ssr_dynamic_import__", "import"); - return `const __name = (value) => value;\nconst captureFailure = ${remoteWorkspaceCaptureFailureMessage.toString()};\nconst failureDetail = ${remoteWorkspaceFailureDetail.toString()};\nconst archive = ${source};\nconst [kind, first, second, digest] = process.argv.slice(2);\narchive(kind === 'capture' ? {kind,cwd:first,archivePath:second} : {kind,archivePath:first,targetDir:second,expectedManifestDigest:digest}).then(value=>process.stdout.write(JSON.stringify(value))).catch(error=>{const detail = failureDetail(error);process.stderr.write(kind === 'capture' ? captureFailure(error) ?? ('remote_workspace_archive_failed' + (detail ? ': ' + detail : '')) : error.message);process.exitCode=1;});\n`; + return `const __name = (value) => value;\nconst captureFailure = ${remoteWorkspaceCaptureFailureMessage.toString()};\nconst failureDetail = ${remoteWorkspaceFailureDetail.toString()};\nconst archive = ${source};\nconst [kind, first, second, digest] = process.argv.slice(2), mode = process.argv[6];\narchive(kind === 'capture' ? {kind,cwd:first,archivePath:second} : {kind,archivePath:first,targetDir:second,expectedManifestDigest:digest,consumeArchive:mode === 'consume'}).then(value=>process.stdout.write(JSON.stringify(value))).catch(error=>{const detail = failureDetail(error);process.stderr.write(kind === 'capture' ? captureFailure(error) ?? ('remote_workspace_archive_failed' + (detail ? ': ' + detail : '')) : error.message);process.exitCode=1;});\n`; } diff --git a/server/src/services/remote-workspace-transport.test.ts b/server/src/services/remote-workspace-transport.test.ts index 1c46c97259e..8197db8ec2c 100644 --- a/server/src/services/remote-workspace-transport.test.ts +++ b/server/src/services/remote-workspace-transport.test.ts @@ -285,7 +285,8 @@ describe("remote workspace transport safety with real sandbox commands", () => { let lost = false; execute.mockImplementation(async input => { const result = await original(input); - if (!lost && input.args?.[0] === "-e" && input.args[1]?.includes("workspace-restored.json") && result.exitCode === 0) { + if (!lost && input.args?.[0] === "-e" && input.args[1]?.includes("workspace-restored.json") && input.args.at(-1) === "extract" + && result.exitCode === 0) { lost = true; throw new Error("synthetic lost restore reply"); } return result; @@ -333,7 +334,7 @@ describe("remote workspace transport safety with real sandbox commands", () => { if (scenario === "interrupted") { const run = execute.getMockImplementation()!; let interrupt = true; execute.mockImplementation(async command => { - if (interrupt && command.args?.[1]?.includes("remote_workspace_restore_failed")) { + if (interrupt && command.args?.[1]?.includes("remote_workspace_restore_failed") && command.args.at(-1) === "extract") { interrupt = false; return run({ ...command, args: command.args.map((arg, index) => index === 1 ? arg.replace("try{await fs.rename(staged,root);}", "throw Error('interrupted');try{await fs.rename(staged,root);}") : arg) }); @@ -388,6 +389,7 @@ fs.unlinkSync(${JSON.stringify(postPublish)});throw Error('published_interrupted const run = execute.getMockImplementation()!; let interrupt = scenario === "interrupted"; execute.mockImplementation(async command => { if (!command.args?.[1]?.includes("remote_workspace_restore_failed")) return run(command); + if (command.args.at(-1) !== "extract") return run({ ...command, args: ["--require", preload, ...command.args] }); const args = interrupt ? command.args.map((arg, index) => index === 1 ? arg.replace("await fs.rename(path.join(staged,'.paperclip-runtime','workspace-restored.json')", "throw Error('interrupted');await fs.rename(path.join(staged,'.paperclip-runtime','workspace-restored.json')") : arg) : command.args; interrupt = false; @@ -720,6 +722,292 @@ fs.unlinkSync(${JSON.stringify(kill)});process.kill(process.pid,'SIGKILL');}retu } finally { await captured.cleanup(); } }); + describe("restoring into a sandbox disk that cannot hold two workspace copies", () => { + const MiB = 1024 * 1024; + // The sandbox disk is a folder with a byte capacity. Every write the restore + // commands make through a file handle counts what the folder already holds. + async function boundedDisk(capacity: number, kill?: { afterWrites: number }) { + const disk = path.join(scratch, "disk"), preload = path.join(scratch, `disk-${randomUUID()}.cjs`); + await fs.mkdir(disk, { recursive: true }); + await fs.writeFile(preload, `const fs=require('node:fs'),path=require('node:path'); +const disk=${JSON.stringify(disk)},capacity=${capacity},killAfter=${kill?.afterWrites ?? 0}; +const used=()=>{let total=0;const walk=d=>{for(const e of fs.readdirSync(d,{withFileTypes:true})){const p=path.join(d,e.name); + if(e.isDirectory())walk(p);else if(e.isFile())total+=fs.lstatSync(p).size;}};walk(disk);return total;}; +let writes=0;const helper=process.argv.includes('restore');const open=fs.promises.open; +fs.promises.open=async(...args)=>{const handle=await open.apply(fs.promises,args); + if(!String(args[0]).startsWith(disk+path.sep))return handle;const writeFile=handle.writeFile.bind(handle); + handle.writeFile=async(data,...rest)=>{ + if(used()+Buffer.byteLength(data)>capacity)throw Object.assign(Error('ENOSPC: no space left on device, write'),{code:'ENOSPC',errno:-28,syscall:'write'}); + const result=await writeFile(data,...rest); + if(helper&&killAfter&&++writes>=killAfter){process.kill(process.ppid,'SIGKILL');process.kill(process.pid,'SIGKILL');} + return result;}; + return handle;}; +const writeFile=fs.promises.writeFile; +fs.promises.writeFile=async(file,data,...rest)=>{ + if(String(file).startsWith(disk+path.sep)&&used()+Buffer.byteLength(data)>capacity) + throw Object.assign(Error('ENOSPC: no space left on device, write'),{code:'ENOSPC',errno:-28,syscall:'write'}); + return writeFile.call(fs.promises,file,data,...rest);}; +require('node:module').syncBuiltinESMExports();`); + const { remote, execute } = target(); + const actual = execute.getMockImplementation()!; + // Every sandbox command, including the helper install, writes to this disk. + execute.mockImplementation(command => actual({ ...command, env: { ...command.env, NODE_OPTIONS: `--require ${preload}` } })); + const used = async () => { + let total = 0; + const walk = async (directory: string): Promise => { + for (const entry of await fs.readdir(directory, { withFileTypes: true })) { + if (entry.isDirectory()) await walk(path.join(directory, entry.name)); + else if (entry.isFile()) total += (await fs.lstat(path.join(directory, entry.name))).size; + } + }; + await walk(disk); + return total; + }; + // The upload lands on the same disk, so it must fit beside what is already there. + const syncIn = remote.runner!.syncIn!; + remote.runner!.syncIn = async (operations, options) => { + let incoming = 0; + for (const operation of operations) for (const file of operation.files) { + incoming += (await fs.stat(file.sourcePath)).size; + incoming -= (await fs.stat(file.targetPath).catch(() => null))?.size ?? 0; + } + if (await used() + incoming > capacity) throw Object.assign(new Error("upload failed: ENOSPC: no space left on device"), { code: "ENOSPC" }); + return syncIn(operations, options); + }; + return { disk, remote, execute, used, root: path.join(disk, "workspace-root") }; + } + async function savedWorkspace() { + const files = Array.from({ length: 4 }, (_, index) => ({ name: `part-${index}.bin`, bytes: randomBytes(MiB) })); + await fs.mkdir(path.join(workspace, "nested")); + for (const file of files) await fs.writeFile(path.join(workspace, "nested", file.name), file.bytes); + const { remote } = target(); + const captured = await captureRemoteWorkspaceArchive({ target: remote, remoteCwd: workspace, operationId: randomUUID() }); + return { files, captured, archiveSize: (await fs.stat(captured.archivePath)).size }; + } + async function expectRestored(root: string, files: Array<{ name: string; bytes: Buffer }>) { + for (const file of files) expect((await fs.readFile(path.join(root, "nested", file.name))).equals(file.bytes)).toBe(true); + } + + it("restores a saved workspace when the archive and the extracted tree do not both fit", async () => { + const { files, captured, archiveSize } = await savedWorkspace(); + try { + // Room for the uploaded archive and one file, not for a second copy. + const { remote, root, used, disk } = await boundedDisk(archiveSize + 1.5 * MiB); + await restoreRemoteWorkspaceDirectory({ target: remote, remoteCwd: root, archivePath: captured.archivePath, + manifestDigest: captured.manifestDigest, restorationIdentity: "1".repeat(64), restorationEpoch: 1 }); + await expectRestored(root, files); + // The consumed archive is gone; nothing but the restored files holds space. + expect(await used()).toBeLessThan(4 * MiB + 256 * 1024); + expect((await fs.readdir(disk)).filter(name => name.includes(".restoring-") || name.startsWith(".workspace-restore-"))).toEqual([]); + } finally { await captured.cleanup(); } + }); + + it("names a disk that cannot take the upload so it is not retried automatically", async () => { + const { captured, archiveSize } = await savedWorkspace(); + try { + const { remote, root } = await boundedDisk(archiveSize / 2); + await expect(restoreRemoteWorkspaceDirectory({ target: remote, remoteCwd: root, archivePath: captured.archivePath, + manifestDigest: captured.manifestDigest, restorationIdentity: "9".repeat(64), restorationEpoch: 1 })).rejects.toThrow( + /^remote_workspace_operation_failed: operation=upload; remote_workspace_restore_failed: stage=upload reason=sandbox_disk_full$/); + } finally { await captured.cleanup(); } + }); + + it("names a disk that cannot take the archive helper so it is not retried automatically", async () => { + const { remote, execute } = target(); + // The reclaim phase runs first; then the helper install finds the disk full. + execute.mockResolvedValueOnce({ exitCode: 0, stdout: "", stderr: "", timedOut: false, signal: null, + pid: process.pid, startedAt: new Date().toISOString() }); + execute.mockResolvedValueOnce({ exitCode: 1, stdout: "", stderr: REMOTE_WORKSPACE_SANDBOX_DISK_FULL, timedOut: false, signal: null, + pid: process.pid, startedAt: new Date().toISOString() }); + const archivePath = path.join(scratch, "restore.pcws"); await fs.writeFile(archivePath, "synthetic archive"); + await expect(restoreRemoteWorkspaceDirectory({ target: remote, remoteCwd: path.join(scratch, "restored"), archivePath, + manifestDigest: "a".repeat(64), restorationIdentity: "b".repeat(64) })).rejects.toThrow( + /^remote_workspace_operation_failed: operation=archive_helper; remote_workspace_restore_failed: stage=helper reason=sandbox_disk_full$/); + }); + + it("names a disk too small for one workspace copy so it is not retried automatically, and restores once space exists", async () => { + const { files, captured, archiveSize } = await savedWorkspace(); + try { + const small = await boundedDisk(archiveSize + MiB / 2); + const input = { target: small.remote, remoteCwd: small.root, archivePath: captured.archivePath, + manifestDigest: captured.manifestDigest, restorationIdentity: "2".repeat(64), restorationEpoch: 1 }; + await expect(restoreRemoteWorkspaceDirectory(input)).rejects.toThrow( + /^remote_workspace_operation_failed: operation=restore exit=1; remote_workspace_restore_failed: stage=extract reason=sandbox_disk_full$/); + expect(await fs.lstat(small.root).catch(() => null)).toBeNull(); + // The failed attempt leaves no partial tree or consumed archive behind. + expect(await small.used()).toBeLessThan(256 * 1024); + const larger = await boundedDisk(archiveSize + 1.5 * MiB); + await restoreRemoteWorkspaceDirectory({ ...input, target: larger.remote }); + await expectRestored(small.root, files); + } finally { await captured.cleanup(); } + }); + + it.each(["same", "new"] as const)("reclaims a restore that died mid-extraction before retrying with the %s identity", async identity => { + const { files, captured, archiveSize } = await savedWorkspace(); + try { + const dying = await boundedDisk(archiveSize + 1.5 * MiB, { afterWrites: 2 }); + const input = { target: dying.remote, remoteCwd: dying.root, archivePath: captured.archivePath, + manifestDigest: captured.manifestDigest, restorationIdentity: "3".repeat(64), restorationEpoch: 1 }; + await expect(restoreRemoteWorkspaceDirectory(input)).rejects.toThrow(/^remote_workspace_operation_failed: operation=restore/); + // Both processes died: a partial tree and the unconsumed archive remain. + expect((await fs.readdir(dying.disk)).some(name => name.startsWith("workspace-root.restoring-"))).toBe(true); + expect(await fs.lstat(dying.root).catch(() => null)).toBeNull(); + const retry = await boundedDisk(archiveSize + 1.5 * MiB); + await restoreRemoteWorkspaceDirectory(identity === "same" ? { ...input, target: retry.remote } + : { ...input, target: retry.remote, restorationIdentity: "4".repeat(64), restorationEpoch: 2 }); + await expectRestored(dying.root, files); + expect((await fs.readdir(dying.disk)).filter(name => name.includes(".restoring-"))).toEqual([]); + } finally { await captured.cleanup(); } + }); + + it("reclaims an earlier release's partial extraction and leaves its unbound archive staging alone", async () => { + const { files, captured, archiveSize } = await savedWorkspace(); + try { + const { remote, root, disk } = await boundedDisk(archiveSize + 1.5 * MiB); + // An earlier release's restore died here: its partial tree carries this + // root's staging name, and its archive staging names no root. + const partial = path.join(disk, "workspace-root.restoring-Ab12Cd"); + await fs.mkdir(path.join(partial, "tree", "nested"), { recursive: true }); + await fs.writeFile(path.join(partial, "tree", "nested", "part-0.bin"), randomBytes(MiB)); + await fs.chmod(path.join(partial, "tree", "nested"), 0o555); + const unbound = path.join(disk, ".paperclip-runtime", "workspace-snapshots", randomUUID()); + await fs.mkdir(unbound, { recursive: true }); + await fs.writeFile(path.join(unbound, "workspace.pcws"), "earlier release archive"); + await restoreRemoteWorkspaceDirectory({ target: remote, remoteCwd: root, archivePath: captured.archivePath, + manifestDigest: captured.manifestDigest, restorationIdentity: "8".repeat(64), restorationEpoch: 1 }); + await expectRestored(root, files); + expect(await fs.lstat(partial).catch(() => null)).toBeNull(); + expect(await fs.readFile(path.join(unbound, "workspace.pcws"), "utf8")).toBe("earlier release archive"); + } finally { await captured.cleanup(); } + }); + + it("reclaims a full disk before the helper install needs space", async () => { + const { files, captured, archiveSize } = await savedWorkspace(); + try { + const capacity = archiveSize + 1.5 * MiB; + const { remote, root, disk, used } = await boundedDisk(capacity); + // A dead attempt of this root left a partial tree that fills the disk. + const partial = path.join(disk, "workspace-root.restoring-Zz98Yy"); + await fs.mkdir(path.join(partial, "tree"), { recursive: true }); + await fs.writeFile(path.join(partial, "tree", "filler.bin"), Buffer.alloc(Math.floor(capacity - 1024))); + expect(capacity - await used()).toBeLessThan(2048); + await restoreRemoteWorkspaceDirectory({ target: remote, remoteCwd: root, archivePath: captured.archivePath, + manifestDigest: captured.manifestDigest, restorationIdentity: "a1".repeat(32), restorationEpoch: 1 }); + await expectRestored(root, files); + expect(await fs.lstat(partial).catch(() => null)).toBeNull(); + } finally { await captured.cleanup(); } + }); + + it("keeps a later attempt's upload when an earlier attempt's reclaim with the same identity runs late", async () => { + const { files, captured, archiveSize } = await savedWorkspace(); + try { + const { remote, execute, root } = await boundedDisk(archiveSize + 1.5 * MiB); + const bounded = execute.getMockImplementation()!; + let delayed = false; + execute.mockImplementation(async command => { + if (!delayed && command.args?.at(-1) === "extract") { + delayed = true; + // The earlier attempt's reclaim reached the sandbox only now. It names its own upload. + expect(command.args[3]).toMatch(/workspace-[0-9]{16}-[a-f0-9-]{36}\.pcws$/); + const late = command.args.map((arg, index) => index === 3 + ? path.join(path.dirname(arg), `workspace-${String(Date.now() - 60_000).padStart(16, "0")}-${randomUUID()}.pcws`) : index === command.args!.length - 1 ? "reclaim" : arg); + expect((await bounded({ ...command, args: late })).exitCode).toBe(0); + } + return bounded(command); + }); + await restoreRemoteWorkspaceDirectory({ target: remote, remoteCwd: root, archivePath: captured.archivePath, + manifestDigest: captured.manifestDigest, restorationIdentity: "b2".repeat(32), restorationEpoch: 1 }); + expect(delayed).toBe(true); + await expectRestored(root, files); + } finally { await captured.cleanup(); } + }); + + it("reclaims an abandoned upload of the same identity before uploading again", async () => { + const { files, captured, archiveSize } = await savedWorkspace(); + try { + const { remote, root, disk } = await boundedDisk(archiveSize + 1.5 * MiB); + const identity = "c3".repeat(32); + const operationId = `${identity.slice(0, 8)}-${identity.slice(8, 12)}-${identity.slice(12, 16)}-${identity.slice(16, 20)}-${identity.slice(20, 32)}`; + // An earlier attempt finished its upload, then the server stopped before extraction. + const staging = path.join(disk, ".paperclip-runtime", "workspace-snapshots", operationId); + await fs.mkdir(staging, { recursive: true }); + const abandoned = path.join(staging, `workspace-${String(Date.now() - 60_000).padStart(16, "0")}-${randomUUID()}.pcws`); + await fs.copyFile(captured.archivePath, abandoned); + await restoreRemoteWorkspaceDirectory({ target: remote, remoteCwd: root, archivePath: captured.archivePath, + manifestDigest: captured.manifestDigest, restorationIdentity: identity, restorationEpoch: 1 }); + await expectRestored(root, files); + expect(await fs.lstat(abandoned).catch(() => null)).toBeNull(); + } finally { await captured.cleanup(); } + }); + + async function retainedRoot(root: string) { + const runtime = path.join(root, ".paperclip-runtime"); + await fs.mkdir(path.join(runtime, "paperclip-runner"), { recursive: true }); + await fs.writeFile(path.join(runtime, "paperclip-runner", "runner-state.json"), "{\"lifecycle\":\"suspended\"}"); + await fs.writeFile(path.join(runtime, "workspace-ready.json"), JSON.stringify({ preparationIdentity: "f".repeat(64) })); + await fs.mkdir(path.join(root, "nested")); + for (let index = 0; index < 4; index++) await fs.writeFile(path.join(root, "nested", `old-${index}.bin`), randomBytes(MiB)); + } + + it("removes a retained root whose save the server proved before extracting into its space", async () => { + const { files, captured, archiveSize } = await savedWorkspace(); + try { + // The old copy, the uploaded archive, and one file fit; a third copy does not. + const { remote, root } = await boundedDisk(4 * MiB + archiveSize + 1.5 * MiB); + await retainedRoot(root); + await restoreRemoteWorkspaceDirectory({ target: remote, remoteCwd: root, archivePath: captured.archivePath, + manifestDigest: captured.manifestDigest, restorationIdentity: "5".repeat(64), restorationEpoch: 1, replaceRetiredRoot: true }); + await expectRestored(root, files); + expect(await fs.lstat(path.join(root, "nested", "old-0.bin")).catch(() => null)).toBeNull(); + expect(await fs.readFile(path.join(root, ".paperclip-runtime", "paperclip-runner", "runner-state.json"), "utf8")) + .toBe("{\"lifecycle\":\"suspended\"}"); + } finally { await captured.cleanup(); } + }); + + it.each(["unproven", "no_receipt"] as const)("never removes a retained root whose save is %s", async scenario => { + const { captured, archiveSize } = await savedWorkspace(); + try { + const { remote, root } = await boundedDisk(4 * MiB + archiveSize + 1.5 * MiB); + await retainedRoot(root); + if (scenario === "no_receipt") await fs.rm(path.join(root, ".paperclip-runtime", "workspace-ready.json")); + const before = await fs.readdir(path.join(root, "nested")); + await expect(restoreRemoteWorkspaceDirectory({ target: remote, remoteCwd: root, archivePath: captured.archivePath, + manifestDigest: captured.manifestDigest, restorationIdentity: "6".repeat(64), restorationEpoch: 1, + replaceRetiredRoot: scenario !== "unproven" })) + .rejects.toThrow(/; remote_workspace_restore_failed: stage=inspect_root reason=occupied_root$/); + expect(await fs.readdir(path.join(root, "nested"))).toEqual(before); + } finally { await captured.cleanup(); } + }); + + it("finishes the removal and restore after a proven retained root's removal is interrupted", async () => { + const { files, captured, archiveSize } = await savedWorkspace(); + try { + const { remote, execute, root, disk } = await boundedDisk(4 * MiB + archiveSize + 1.5 * MiB); + await retainedRoot(root); + const flag = path.join(scratch, "interrupt-removal"), interrupt = path.join(scratch, "interrupt-removal.cjs"); + await fs.writeFile(flag, "once"); + // The command dies right after deleting the old files, as a restart would leave it. + await fs.writeFile(interrupt, `const fs=require('node:fs'),rm=fs.promises.rm; +fs.promises.rm=async(file,options)=>{const result=await rm.call(fs.promises,file,options); +if(String(file)===${JSON.stringify(path.join(root, "nested"))}&&fs.existsSync(${JSON.stringify(flag)})){fs.unlinkSync(${JSON.stringify(flag)});process.kill(process.pid,'SIGKILL');} +return result};`); + const bounded = execute.getMockImplementation()!; + execute.mockImplementation(command => bounded(command.args?.[1]?.includes("remote_workspace_restore_failed") + ? { ...command, args: ["--require", interrupt, ...command.args!] } : command)); + const input = { target: remote, remoteCwd: root, archivePath: captured.archivePath, manifestDigest: captured.manifestDigest, + restorationIdentity: "7".repeat(64), restorationEpoch: 1, replaceRetiredRoot: true }; + await expect(restoreRemoteWorkspaceDirectory(input)).rejects.toThrow(/^remote_workspace_operation_failed: operation=restore/); + expect(await fs.lstat(path.join(root, "nested")).catch(() => null)).toBeNull(); + expect((await fs.lstat(path.join(root, ".paperclip-runtime", "workspace-ready.json"))).isFile()).toBe(true); + await restoreRemoteWorkspaceDirectory(input); + await expectRestored(root, files); + expect(await fs.readFile(path.join(root, ".paperclip-runtime", "paperclip-runner", "runner-state.json"), "utf8")) + .toBe("{\"lifecycle\":\"suspended\"}"); + expect((await fs.readdir(disk)).filter(name => name.includes(".restoring-") || name.startsWith("workspace-root.retired-"))).toEqual([]); + } finally { await captured.cleanup(); } + }); + }); + it("names the preparation step that could not select a missing branch", async () => { const origin = await repository(), { remote } = target(), root = path.join(workspace, "missing-branch-cause"); await expect(prepareRemoteWorkspaceDirectory({ target: remote, remoteCwd: root, @@ -740,8 +1028,9 @@ fs.unlinkSync(${JSON.stringify(kill)});process.kill(process.pid,'SIGKILL');}retu it.each(["prepare", "repository", "restore"] as const)("drops %s output that is outside the closed cause grammar", async operation => { const { remote, execute } = target(); const forged = `remote_workspace_${operation}_failed: stage=extract reason=/home/secret`; - if (operation === "restore") execute.mockResolvedValueOnce({ exitCode: 0, stdout: "", stderr: "", timedOut: false, - signal: null, pid: process.pid, startedAt: new Date().toISOString() }); + // A restore runs its reclaim phase and installs its helper before extracting. + if (operation === "restore") for (let call = 0; call < 2; call++) execute.mockResolvedValueOnce({ exitCode: 0, stdout: "", stderr: "", + timedOut: false, signal: null, pid: process.pid, startedAt: new Date().toISOString() }); execute.mockResolvedValueOnce({ exitCode: 1, stdout: "", stderr: forged, timedOut: false, signal: null, pid: process.pid, startedAt: new Date().toISOString() }); const request = operation === "prepare" @@ -1352,7 +1641,8 @@ fs.unlinkSync(${JSON.stringify(kill)});process.kill(process.pid,'SIGKILL');}retu const { remote, execute } = target(); const failed = { exitCode: 1, stdout: "remote_workspace_archive_fs_enoent", stderr: "", timedOut: false, signal: null, pid: process.pid, startedAt: new Date().toISOString() }; - if (operation === "restore") execute.mockResolvedValueOnce({ ...failed, exitCode: 0, stdout: "" }); + // A restore runs its reclaim phase and installs its helper before extracting. + if (operation === "restore") execute.mockResolvedValueOnce({ ...failed, exitCode: 0, stdout: "" }).mockResolvedValueOnce({ ...failed, exitCode: 0, stdout: "" }); execute.mockResolvedValueOnce(failed); const request = operation === "prepare" ? prepareRemoteWorkspaceDirectory({ target: remote, remoteCwd: workspace, source: { kind: "empty" }, @@ -1367,7 +1657,7 @@ fs.unlinkSync(${JSON.stringify(kill)});process.kill(process.pid,'SIGKILL');}retu manifestDigest: "a".repeat(64), restorationIdentity: "b".repeat(64) }); })(); await expect(request).rejects.toThrow(/^remote_workspace_operation_failed: operation=[a-z_]+ exit=1$/); - expect(execute).toHaveBeenCalledTimes(operation === "restore" ? 2 : 1); + expect(execute).toHaveBeenCalledTimes(operation === "restore" ? 3 : 1); }); it("keeps the existing disk diagnostic ahead of a new capture diagnostic", async () => { diff --git a/server/src/services/remote-workspace-transport.ts b/server/src/services/remote-workspace-transport.ts index 42ecdfd82bd..79e2fac753f 100644 --- a/server/src/services/remote-workspace-transport.ts +++ b/server/src/services/remote-workspace-transport.ts @@ -639,6 +639,22 @@ async function captureSandboxWorkspaceArchive(input: { } } +/** A full sandbox disk repeats on every retry of the same restore, so it names a refusal reason. */ +function restoreDiskFull(operation: RemoteWorkspaceOperation, stage: "helper" | "upload") { + return new RemoteWorkspaceOperationError( + `remote_workspace_operation_failed: operation=${operation}; remote_workspace_restore_failed: stage=${stage} reason=sandbox_disk_full`); +} + +/** Provider text only selects this answer; it is never copied. */ +function sandboxDiskFull(error: unknown) { + for (let cause = error, depth = 0; cause && depth < 4; cause = (cause as { cause?: unknown }).cause, depth++) { + const { code, message } = cause as { code?: unknown; message?: unknown }; + if (code === "ENOSPC" || code === "EDQUOT" + || (typeof message === "string" && /\bENOSPC\b|\bEDQUOT\b|No space left on device|Disk quota exceeded/i.test(message))) return true; + } + return false; +} + export async function restoreRemoteWorkspaceDirectory(input: { target: RemoteWorkspaceTarget; remoteCwd: string; archivePath: string; manifestDigest: string; restorationIdentity: string; restorationEpoch?: number; allowEmptyRoot?: boolean; allocationFiles?: Array<{ relativePath: string; sha256: string }>; @@ -654,15 +670,14 @@ export async function restoreRemoteWorkspaceDirectory(input: { const operationId = `${id.slice(0, 8)}-${id.slice(8, 12)}-${id.slice(12, 16)}-${id.slice(16, 20)}-${id.slice(20, 32)}`; // Stage outside the destination; the restore validator requires an empty target. const parent = path.posix.dirname(input.remoteCwd); - const staged = await installArchiveHelper(input.target, parent, operationId); - await measureRunPhase("workspace.snapshot.sandbox_upload", () => stat(input.archivePath).then(archive => transferArchive(input.target, "syncIn", [{ operationId, - files: [{ kind: "file", sourcePath: input.archivePath, targetPath: staged.archive }], - }], archive.size))).catch((error: unknown) => { noteProviderRefusal("upload", error); throw error; }); // Publish the restored folder and its identity together. A lost successful // reply can then adopt the same files without repeating a destructive restore. const restore = String.raw`const fs=require('node:fs/promises'),path=require('node:path'),cp=require('node:child_process'),crypto=require('node:crypto'); ${DISK_FULL_CHECK}${CAPTURE_FAILURE_CHECK}${SETUP_FAILURE_CHECK}let stage='validate'; - (async()=>{const [helper,archive,root,digest,identity,allowEmpty,rawFiles,replaceRetired,rawEpoch]=process.argv.slice(1),files=JSON.parse(rawFiles); + (async()=>{const [helper,archive,root,digest,identity,allowEmpty,rawFiles,replaceRetired,rawEpoch,phase]=process.argv.slice(1),files=JSON.parse(rawFiles); + // The reclaim phase runs before the upload: it frees what this root's + // earlier attempts and proven retired files hold, then stops before extraction. + const reclaimOnly=phase==='reclaim'; const validEpoch=value=>Number.isSafeInteger(value)&&value>0,restorationEpoch=rawEpoch===undefined||rawEpoch===''?null:Number(rawEpoch); if(restorationEpoch!==null&&!validEpoch(restorationEpoch))throw Error('invalid_epoch'); const completedReceipt=(id,manifestDigest,epoch)=>epoch===null?{identity:id,manifestDigest} @@ -736,6 +751,12 @@ export async function restoreRemoteWorkspaceDirectory(input: { await fs.writeFile(receiptFile,JSON.stringify(receipt),{mode:0o600}); await fs.rename(path.join(staged,'.paperclip-runtime','workspace-restored.json'),path.join(runtime,'workspace-restored.json')); await finishInPlace(receipt);}; + // The reclaim phase runs before the helper install, so it creates the + // operation's staging folder itself without following a symlink. + if(reclaimOnly){stage='create_parent';let current='/'; + for(const part of path.dirname(archive).split('/').filter(Boolean)){current=path.join(current,part); + await fs.mkdir(current,{mode:0o700}).catch(e=>{if(e.code!=='EEXIST')throw e}); + const s=await fs.lstat(current);if(!s.isDirectory()||s.isSymbolicLink())throw Error('unsafe_root');}} stage='restore_lock';await directory(path.dirname(root)); const lockRoot=path.join(path.dirname(root),'.paperclip-runtime','workspace-restore-locks'); await directory(path.dirname(lockRoot)); @@ -782,6 +803,33 @@ export async function restoreRemoteWorkspaceDirectory(input: { await fs.rename(pending,fencePath);const directory=await fs.open(lockRoot,'r');try{await directory.sync();}finally{await directory.close();}} finally{await fs.rm(pending,{force:true});} } + // Only a restore of this root, under this lock, creates its staging folders + // and binds its archive staging to the root. While the lock is held, any + // such leftover is from an attempt that died, and its bytes are disposable: + // the saved version in control-plane storage is the source of truth. + stage='reclaim';const stagingRoot=path.dirname(archive),snapshotsRoot=path.dirname(stagingRoot); + const discard=async p=>{await open(p);await fs.rm(p,{recursive:true,force:true});}; + // Uploads are named by the attempt's start time. An older attempt's upload is + // abandoned once a newer attempt holds the lock; a newer one is left alone. + const attemptOf=name=>name==='workspace.pcws'?0:Number(/^workspace-([0-9]{16})-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\.pcws$/.exec(name)?.[1]??NaN); + const ownAttempt=attemptOf(path.basename(archive));if(!Number.isSafeInteger(ownAttempt)||ownAttempt<1)throw Error('invalid_attempt'); + for(const name of await fs.readdir(stagingRoot)) + if(/\.pcws\.[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\.consuming$/.test(name)||attemptOf(name)16384)continue; + const value=await readJson(path.join(directory,'restore-target.json'),'unsafe_staging').catch(()=>null); + if(value?.schema==='paperclip.workspace-restore-staging.v1'&&value.root===root)await discard(directory);} + // Bind this attempt's staging only after the space is reclaimed. + const binding=path.join(stagingRoot,'restore-target.json'),bindingTemp=binding+'.'+crypto.randomUUID()+'.tmp'; + try{await fs.writeFile(bindingTemp,JSON.stringify({schema:'paperclip.workspace-restore-staging.v1',root}),{flag:'wx',mode:0o600}); + await fs.rename(bindingTemp,binding);}finally{await fs.rm(bindingTemp,{force:true});} stage='allocation';if(await stat(parked)){if(allowEmpty!=='true')throw Error('unexpected_allocation');await allocation(parked);if(!await stat(root))await fs.rename(parked,root);} stage='inspect_root';const prior=await stat(root);if(prior)await directory(root); const marker=path.join(root,'.paperclip-runtime','workspace-restored.json'); @@ -807,9 +855,19 @@ export async function restoreRemoteWorkspaceDirectory(input: { if(prior&&!retire&&allowEmpty!=='true')throw Error('occupied_root'); stage='allocation';const retained=prior&&!retire?await allocation(root):[]; if(!prior&&files.length)throw Error('allocation_missing'); - stage='extract';const staged=await fs.mkdtemp(root+'.restoring-'); + // The server proved this root's files are already in the saved lineage being + // restored, so they are removed before extraction instead of after it. Its + // receipt and runtime state stay, so an interrupted restore repeats this step. + if(retire){stage='reclaim_retired';const s=await fs.lstat(root);await fs.chmod(root,(s.mode&0o7777)|0o700); + for(const name of await fs.readdir(root))if(name!=='.paperclip-runtime')await discard(path.join(root,name)); + if(await stat(path.join(root,'.paperclip-runtime','workspace-snapshots')))await discard(path.join(root,'.paperclip-runtime','workspace-snapshots'));} + if(reclaimOnly)return; + stage='extract';const staging=await fs.mkdtemp(root+'.restoring-'),staged=path.join(staging,'tree'); + // A private name keeps a later upload to the same path out of this extraction. + const consuming=archive+'.'+crypto.randomUUID()+'.consuming'; try{ - await require('node:util').promisify(cp.execFile)(process.execPath,[helper,'restore',archive,staged,digest],{maxBuffer:1048576}); + await fs.rename(archive,consuming); + await require('node:util').promisify(cp.execFile)(process.execPath,[helper,'restore',consuming,staged,digest,'consume'],{maxBuffer:1048576}); stage='write_receipt';const runtime=path.join(staged,'.paperclip-runtime');await fs.mkdir(runtime,{mode:0o700}); for(const file of retained)await fs.writeFile(path.join(runtime,file.name),file.content,{flag:'wx',mode:0o600}); await fs.writeFile(path.join(runtime,'workspace-restored.json'),JSON.stringify(completedReceipt(identity,digest,restorationEpoch)),{flag:'wx',mode:0o600}); @@ -821,12 +879,29 @@ export async function restoreRemoteWorkspaceDirectory(input: { try{await fs.rename(staged,root);}catch(e){if(prior&&!await stat(root))await fs.rename(holding,root);throw e;} stage='cleanup_parked';if(prior&&!retire){await allocation(parked);await fs.rm(parked,{recursive:true});} await removeRetired(); - }finally{await fs.rm(staged,{recursive:true,force:true});} + }finally{await fs.rm(consuming,{force:true});await open(staging).catch(()=>{});await fs.rm(staging,{recursive:true,force:true});} }finally{lock.close();} - })().catch(error=>{process.stderr.write(setupFailure('remote_workspace_restore_failed',stage,error));process.exitCode=1});`; - await measureRunPhase("workspace.snapshot.sandbox_extract", () => command(input.target, "restore", ["-e", restore, staged.helper, staged.archive, input.remoteCwd, + })().catch(error=>{process.stderr.write(setupFailure('remote_workspace_restore_failed',stage,diskFull(error)?Error('sandbox_disk_full'):error));process.exitCode=1});`; + // Each attempt uploads to its own name, so a delayed command of an earlier + // attempt with the same identity never removes or consumes this upload. + const directory = path.posix.join(parent, ".paperclip-runtime", "workspace-snapshots", operationId); + const archive = path.posix.join(directory, `workspace-${String(Date.now()).padStart(16, "0")}-${randomUUID()}.pcws`); + const args = (phase: "reclaim" | "extract") => ["-e", restore, path.posix.join(directory, "archive.cjs"), archive, input.remoteCwd, input.manifestDigest, input.restorationIdentity, String(input.allowEmptyRoot === true), JSON.stringify(input.allocationFiles ?? []), - String(input.replaceRetiredRoot === true), input.restorationEpoch === undefined ? "" : String(input.restorationEpoch)])); + String(input.replaceRetiredRoot === true), input.restorationEpoch === undefined ? "" : String(input.restorationEpoch), phase]; + // Free what this root's earlier attempts left before anything new needs space. + await command(input.target, "restore", args("reclaim")); + const staged = await installArchiveHelper(input.target, parent, operationId).catch((error: unknown) => { + throw error instanceof Error && error.message === REMOTE_WORKSPACE_SANDBOX_DISK_FULL ? restoreDiskFull("archive_helper", "helper") : error; + }); + if (staged.directory !== directory) throw new Error("remote_workspace_operation_identity_invalid"); + await measureRunPhase("workspace.snapshot.sandbox_upload", () => stat(input.archivePath).then(source => transferArchive(input.target, "syncIn", [{ operationId, + files: [{ kind: "file", sourcePath: input.archivePath, targetPath: archive }], + }], source.size))).catch((error: unknown) => { + if (sandboxDiskFull(error)) throw restoreDiskFull("upload", "upload"); + noteProviderRefusal("upload", error); throw error; + }); + await measureRunPhase("workspace.snapshot.sandbox_extract", () => command(input.target, "restore", args("extract"))); // Publish the restored location before cleanup can fail, stall, or lose its // reply. The owner journals this receipt and then reclaims disposable staging. return { operationId, stagingRoot: parent, cleanupPending: true }; diff --git a/server/src/services/remote-workspaces.integration.test.ts b/server/src/services/remote-workspaces.integration.test.ts index a990f11d667..88cb8cf0a8c 100644 --- a/server/src/services/remote-workspaces.integration.test.ts +++ b/server/src/services/remote-workspaces.integration.test.ts @@ -407,7 +407,7 @@ suite("remote workspace lifecycle with real Postgres and independent filesystem } }, 60_000); - it.each(["same root", "different root", "destroyed allocation", "occupied root", "missing object", "stalled download", "transient restore", "restore lock busy"] as const)( + it.each(["same root", "different root", "destroyed allocation", "occupied root", "missing object", "stalled download", "transient restore", "full sandbox disk", "restore lock busy"] as const)( "preserves the published workspace path and files on a cold restore (%s)", async mode => { const reserved = await reserve({ kind: "empty" }), first = await target("sandbox-A"); const prepared = await prepareRemoteWorkspace({ db, storage, workspace: reserved, runId: ids.run, lease: await lease(), target: first }); @@ -464,6 +464,26 @@ suite("remote workspace lifecycle with real Postgres and independent filesystem expect(await fs.lstat(expectedRemoteRoot).catch(() => null)).toBeNull(); vi.mocked(second.runner!.execute).mockRestore(); } + if (mode === "full sandbox disk") { + // The sandbox cannot hold even one copy: every restored file write fails + // with ENOSPC. That repeats on every automatic retry, so it is named and + // goes to the board, whose Retry works once the sandbox has space. + const preload = path.join(root, "full-disk.cjs"); + await fs.writeFile(preload, `const fs=require('node:fs'),open=fs.promises.open; +fs.promises.open=async(...args)=>{const handle=await open.apply(fs.promises,args); + if(process.argv.includes('restore'))handle.writeFile=async()=>{throw Object.assign(Error('ENOSPC: no space left on device, write'),{code:'ENOSPC'})}; + return handle;}; +require('node:module').syncBuiltinESMExports();`); + const run = second.runner!.execute.bind(second.runner); + vi.spyOn(second.runner!, "execute").mockImplementation(async command => run(command.args?.[1]?.includes("remote_workspace_restore_failed") + ? { ...command, env: { ...command.env, NODE_OPTIONS: `--require ${preload}` } } : command)); + const full = await prepareRemoteWorkspace({ db, storage, workspace: reservedAgain, runId: nextRun, lease: newLease, target: second }) + .then(() => null, (error: unknown) => error as RemoteWorkspaceRestoreError); + expect(full).toMatchObject({ step: "sandbox_restore", retryable: false, message: "remote_workspace_restore_failed: step=sandbox_restore; " + + "remote_workspace_operation_failed: operation=restore exit=1; remote_workspace_restore_failed: stage=extract reason=sandbox_disk_full" }); + expect(await fs.lstat(expectedRemoteRoot).catch(() => null)).toBeNull(); + vi.mocked(second.runner!.execute).mockRestore(); + } if (mode === "restore lock busy") { const lockDirectory = path.join(path.dirname(expectedRemoteRoot), ".paperclip-runtime", "workspace-restore-locks"); await fs.mkdir(lockDirectory, { recursive: true, mode: 0o700 }); From f77b8a288e8667a70382a82000409b4e4a43c9c3 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:36:40 -0600 Subject: [PATCH 29/38] fix(ui): keep the GitHub star prompt off tasks that need a Retry (#20713) 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 > - A task that fails shows a banner with a Retry button. The user clicks Retry to run the task again. > - Self-hosted boards also show a "You completed 5 tasks! Star on GitHub" modal (#20453). > - The modal can open on the task page while the task shows its Retry banner. > - The modal is a Radix dialog. It sets `aria-hidden="true"` on the rest of the page and sets `pointer-events: none` on the body. The Retry button is visible, but a click does not reach it and assistive technology cannot find it. > - This pull request makes the star prompt wait for a calm moment. It does not open on a task or agent chat page, and it does not open while a task Retry or status banner is on screen. > - The benefit is that a visible Retry is always reachable. ## Linked Issues or Issue Description Refs #20453 **What happened?** A restart chaos run left a task in the failed state with the Retry banner. The "You completed 5 tasks!" star modal opened over the same page. The Retry button was in the DOM and visible. Playwright `getByRole('button', { name: 'Retry' })` did not find it, because the modal had set `aria-hidden="true"` on the banner. The body also had `pointer-events: none`, so a user click on Retry did not reach the button. **Expected behavior** A promotional prompt never covers a task that needs the user. A visible Retry is always reachable. **Steps to reproduce** 1. On a self-hosted instance, finish five tasks in one company. Do not open the star prompt before. 2. Let a sixth task fail so that it shows "Couldn't finish this attempt" with Retry. 3. Open that task. The star modal opens over the Retry banner. **Paperclip version or commit** master at 200c6e40e2 ## What Changed - `GitHubStarPrompt` waits while the location is one task (`/:prefix/issues/:ref`) or one agent chat (`/:prefix/chats/:agent`). Task list views (`issues/all`, `issues/done`, and so on) do not count as one task. - `GitHubStarPrompt` waits while a task Retry (`data-testid="task-execution-retry"`) or a task status banner (`role="status"` with `aria-label="Task status"`) is on screen. It uses the same DOM observer that already waits for other dialogs. - If the prompt is open and the user goes back to a task or chat page, or a task Retry or status banner appears, the prompt closes. - `useModalOpen` in `AnnouncementWell.tsx` takes an optional selector. The default is the existing modal selector, so other callers do not change. - New tests in `GitHubStarPrompt.test.tsx`: the prompt stays closed while a Retry banner is on screen and the banner is not `aria-hidden`; the prompt stays closed on a task and a chat page and opens on the task list. The prompt closes when the user goes back to a task, and when a Retry appears. ## Verification - Red first: the two new tests failed on master. A temporary probe in the red run showed the prompt open, the banner with `aria-hidden="true"`, and `document.body.style.pointerEvents === "none"`. - Green: `cd ui && npx vitest run src/components/GitHubStarPrompt.test.tsx src/components/BoardDialogs.test.tsx` passes. - `pnpm verify` passes (481 UI test files). - `pnpm check:token-gates`: all gates clean. - `npx tsc --noEmit -p ui`: no errors in the changed files. ## Risks - Low risk. The prompt can show later than before, because it waits for a non-task page. It still shows only once per browser. - The "seen" marker is written only when the prompt opens, so a user who stays on task pages does not lose the prompt. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), in Claude Code with tool use (shell, file edit, 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 - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- ui/src/components/AnnouncementWell.tsx | 6 +-- ui/src/components/GitHubStarPrompt.test.tsx | 54 ++++++++++++++++++++- ui/src/components/GitHubStarPrompt.tsx | 21 +++++++- 3 files changed, 74 insertions(+), 7 deletions(-) diff --git a/ui/src/components/AnnouncementWell.tsx b/ui/src/components/AnnouncementWell.tsx index c6212de9fb7..2eb996dd33c 100644 --- a/ui/src/components/AnnouncementWell.tsx +++ b/ui/src/components/AnnouncementWell.tsx @@ -14,16 +14,16 @@ import { AnnouncementCard } from "./AnnouncementCard"; // Includes the command palette, sheets and dialogs created outside DialogContext. export const MODAL_SELECTOR = '[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"], [aria-modal="true"]:not([data-state="closed"]), dialog[open]'; -export function useModalOpen(enabled: boolean) { +export function useModalOpen(enabled: boolean, selector = MODAL_SELECTOR) { const [open, setOpen] = useState(false); useEffect(() => { if (!enabled) return; - const scan = () => setOpen(Boolean(document.querySelector(MODAL_SELECTOR))); + const scan = () => setOpen(Boolean(document.querySelector(selector))); scan(); const observer = new MutationObserver(scan); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["data-state", "aria-modal", "open"] }); return () => observer.disconnect(); - }, [enabled]); + }, [enabled, selector]); return open; } diff --git a/ui/src/components/GitHubStarPrompt.test.tsx b/ui/src/components/GitHubStarPrompt.test.tsx index 8da3c90fa54..223f4a849f2 100644 --- a/ui/src/components/GitHubStarPrompt.test.tsx +++ b/ui/src/components/GitHubStarPrompt.test.tsx @@ -2,6 +2,7 @@ import { act } from "react"; import { createRoot, type Root } from "react-dom/client"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { MemoryRouter, useNavigate, type NavigateFunction } from "react-router-dom"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { ONBOARDING_FIRST_TASK_ORIGIN_KIND } from "@paperclipai/shared"; import type { HealthStatus } from "@/api/health"; @@ -22,10 +23,14 @@ vi.mock("@/api/issues", () => ({ issuesApi: { describe("GitHub star prompt", () => { let container: HTMLDivElement; let root: Root; - const render = async (health: Partial | null = { deploymentMode: "local_trusted" }) => { + let navigate: NavigateFunction | null = null; + function NavigateHandle() { navigate = useNavigate(); return null; } + const render = async (health: Partial | null = { deploymentMode: "local_trusted" }, path = "/CHA/dashboard") => { const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); if (health) client.setQueryData(["health"], health); - await act(async () => root.render()); + await act(async () => root.render( + + )); // Let the onboarding and done-count queries settle, however slow the run. for (let idle = 0, tick = 0; idle < 2 && tick < 100; tick++) { await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); }); @@ -65,6 +70,51 @@ describe("GitHub star prompt", () => { expect(visible()).toBe(true); }); + it("never covers a task's Retry: it waits until no Retry banner is on screen", async () => { + const banner = document.createElement("div"); + banner.setAttribute("role", "status"); banner.setAttribute("aria-label", "Task status"); + banner.innerHTML = 'Couldn’t finish this attempt. Your message is saved.'; + document.body.append(banner); + try { + await render(); + expect(visible()).toBe(false); + expect(banner.closest('[aria-hidden="true"]')).toBeNull(); + await act(async () => { banner.remove(); }); + expect(visible()).toBe(true); + } finally { banner.remove(); } + }); + + it("does not interrupt while the user is looking at a task or a chat", async () => { + await render(undefined, "/CHA/issues/CHA-4"); + expect(visible()).toBe(false); + await act(async () => { navigate!("/CHA/chats/claude"); }); + expect(visible()).toBe(false); + expect(window.localStorage.getItem(STAR_PROMPT_SEEN_KEY)).toBeNull(); + await act(async () => { navigate!("/CHA/issues"); }); + expect(visible()).toBe(true); + }); + + it("closes when the user goes back to a task, or a task asks for Retry", async () => { + await render(); + expect(visible()).toBe(true); + await act(async () => { navigate!("/CHA/issues/CHA-4"); }); + expect(visible()).toBe(false); + + window.localStorage.clear(); + await act(async () => root.unmount()); + root = createRoot(container); + await render(); + expect(visible()).toBe(true); + const retry = document.createElement("button"); + retry.setAttribute("data-testid", "task-execution-retry"); + document.body.append(retry); + try { + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); }); + expect(visible()).toBe(false); + expect(retry.closest('[aria-hidden="true"]')).toBeNull(); + } finally { retry.remove(); } + }); + it("does not open after another tab has shown it", async () => { const other = document.createElement("div"); other.setAttribute("role", "dialog"); other.setAttribute("data-state", "open"); diff --git a/ui/src/components/GitHubStarPrompt.tsx b/ui/src/components/GitHubStarPrompt.tsx index 598804a29d8..70edef31f5d 100644 --- a/ui/src/components/GitHubStarPrompt.tsx +++ b/ui/src/components/GitHubStarPrompt.tsx @@ -7,6 +7,7 @@ import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { useCompany } from "@/context/CompanyContext"; import { useDialogState } from "@/context/DialogContext"; +import { useLocation } from "@/lib/router"; import { queryKeys } from "@/lib/queryKeys"; import { MODAL_SELECTOR, useModalOpen, useOnboardingInProgress } from "./AnnouncementWell"; import { PaperclipMark } from "./PaperclipLockup"; @@ -14,6 +15,15 @@ import { PaperclipMark } from "./PaperclipLockup"; export const STAR_PROMPT_COMPLETED_TASKS = 5; export const STAR_PROMPT_SEEN_KEY = "paperclip.github-star-prompt.seen"; export const PAPERCLIP_GITHUB_URL = "https://github.com/paperclipai/paperclip"; +export const TASK_ATTENTION_SELECTOR = '[data-testid="task-execution-retry"], [role="status"][aria-label="Task status"]'; +const TASK_LIST_VIEWS = new Set(["all", "active", "backlog", "done", "recent"]); + +export function isTaskFocusPath(pathname: string) { + const segments = pathname.split("/").filter(Boolean); + const [section, ref] = segments.slice(-2); + return (segments.length === 2 || segments.length === 3) && Boolean(ref) + && (section === "chats" || (section === "issues" && !TASK_LIST_VIEWS.has(ref!))); +} function readSeen() { try { return window.localStorage.getItem(STAR_PROMPT_SEEN_KEY) !== null; } catch { return true; } @@ -48,6 +58,8 @@ export function GitHubStarPrompt() { }); const reached = eligible && done.isSuccess && done.data.length >= STAR_PROMPT_COMPLETED_TASKS; const otherModalOpen = useModalOpen(reached); + const taskNeedsAttention = useModalOpen(reached || open, TASK_ATTENTION_SELECTOR); + const midTask = isTaskFocusPath(useLocation().pathname); useEffect(() => { if (seen) return; @@ -59,13 +71,18 @@ export function GitHubStarPrompt() { }, [seen]); useEffect(() => { - if (!reached || otherModalOpen || document.querySelector(MODAL_SELECTOR)) return; + if (!reached || otherModalOpen || taskNeedsAttention || midTask + || document.querySelector(`${MODAL_SELECTOR}, ${TASK_ATTENTION_SELECTOR}`)) return; // Another tab may have shown it after this one mounted. if (readSeen()) { setSeen(true); return; } markSeen(); setSeen(true); setOpen(true); - }, [reached, otherModalOpen]); + }, [reached, otherModalOpen, taskNeedsAttention, midTask]); + + useEffect(() => { + if (open && (midTask || taskNeedsAttention)) setOpen(false); + }, [open, midTask, taskNeedsAttention]); return ( From 156212cfd58a22f6d8cce464d1c625e113db2bc9 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:40:49 -0600 Subject: [PATCH 30/38] test(chaos): close a covering modal before clicking Retry, and name it when it blocks (#20715) 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 > - The restart chaos harness (`tests/restart-chaos/`) clicks every needed Retry in the real board UI with Playwright. > - In one wave, a task failed and showed Retry. The "You completed 5 tasks!" star modal was open over the page. > - The modal is a Radix dialog. It sets `aria-hidden="true"` on the rest of the page, so `getByRole('button', { name: 'Retry' })` did not find the visible Retry. > - The grade said `ui_retry_button_missing`. That name hides the real cause. > - This pull request makes the harness close a covering modal before it looks for Retry. When a modal does not close and keeps a visible Retry unreachable, the grade says `ui_retry_blocked_by_modal`. > - The benefit is that a chaos grade names the real cause, and a promotional prompt does not fail a wave. ## Linked Issues or Issue Description Refs #20713 (product fix: the star prompt no longer opens over a task that needs Retry) **What happened?** A restart chaos wave saved a "Retry missing" screenshot. The screenshot shows the Retry banner and the star modal over it. The saved DOM shows the Retry button as visible, with a box, inside the banner. The harness still graded the task `ui_retry_button_missing`. **Expected behavior** The harness closes a modal that covers the page, as a user does, and then clicks Retry. If a modal does not close, the grade names the modal as the cause. **Steps to reproduce** 1. Open a task page that shows a failed attempt with Retry. 2. Open a Radix modal over the page (the star prompt did this). 3. Run `BoardUi.clickRetry` on that task. It reports `ui_retry_button_missing`. ## What Changed - `board-ui.ts`: before and while it waits for Retry, `clickRetryOnPage` closes an open modal that does not itself offer Retry. It clicks "Not now" (or "No thanks", "Maybe later", "Dismiss") when present, else it presses Escape. It also closes a modal that opens after Retry appears and swallows the click, then clicks again. At most three dialogs are closed. Each click has a timeout equal to the per-button request wait. - The click result has a new optional `dismissedDialogs` list (first line of each closed dialog). The observer copies it into the task's retry attempt. - New failure reason `ui_retry_blocked_by_modal` (in `types.ts`): a visible Retry exists in the DOM, it is not reachable by role, and a modal stays open. R3 in `grader.ts` reports it with the banner text, like the other UI reasons. - `README.md`: the board UI Retry paragraph names the dismissal and the new reason. - Tests in `board-ui.test.ts` use real Chromium pages with a modal and an `aria-hidden` page: "Not now" closes it and Retry is clicked; Escape closes it and Retry is clicked; a modal that opens on hover over Retry is closed and Retry is clicked; a modal that does not close gives `ui_retry_blocked_by_modal`. `grader.test.ts` covers the new R3 detail. ## Verification - Red first: the three new `board-ui.test.ts` cases failed on master (the covered Retry was reported as missing). - Green: `cd tests/restart-chaos && npx vitest run board-ui.test.ts grader.test.ts triggers.test.ts` (with `observer.test.ts`) gives 99 passed. - `npx tsc --noEmit -p tests/restart-chaos/tsconfig.json` passes. - `pnpm verify` exits 2 because the README is a global CI input. CI supplies the broad coverage. ## Risks - Low risk. This changes only the test harness. - The harness can close a dialog that the product meant to keep open. The closed dialog is recorded in `dismissedDialogs`, so the evidence still shows it. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), in Claude Code with tool use (shell, file edit, 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 - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- tests/restart-chaos/README.md | 5 +- tests/restart-chaos/board-ui.test.ts | 48 +++++++++++++++- tests/restart-chaos/board-ui.ts | 84 ++++++++++++++++++++++------ tests/restart-chaos/grader.test.ts | 2 + tests/restart-chaos/grader.ts | 4 +- tests/restart-chaos/observer.ts | 3 +- tests/restart-chaos/types.ts | 2 + 7 files changed, 126 insertions(+), 22 deletions(-) diff --git a/tests/restart-chaos/README.md b/tests/restart-chaos/README.md index b457d35b03f..f0e1731365d 100644 --- a/tests/restart-chaos/README.md +++ b/tests/restart-chaos/README.md @@ -511,7 +511,10 @@ windows are written to `storage-faults.json` and removed from the speed grade li Every Retry the grader needs is clicked in the real board UI: the harness opens the issue in a headless Chromium, waits for the visible Retry button and clicks it. A task whose Retry button is missing fails R3 as `ui_retry_button_missing (user saw: …)`; a click that sends no retry request fails as -`ui_retry_no_request`. Crash-point waves serve no UI and click Retry through the API. +`ui_retry_no_request`. Before it looks for Retry, the harness closes any open modal that covers the page +("Not now", else Escape) and records it in the attempt's `dismissedDialogs`. A visible Retry that stays +unreachable behind a modal that will not close fails as `ui_retry_blocked_by_modal`. Crash-point waves +serve no UI and click Retry through the API. ## Daytona (`--env daytona`) diff --git a/tests/restart-chaos/board-ui.test.ts b/tests/restart-chaos/board-ui.test.ts index 2a5ba83b88a..b8897d8f42f 100644 --- a/tests/restart-chaos/board-ui.test.ts +++ b/tests/restart-chaos/board-ui.test.ts @@ -4,10 +4,24 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { once } from "node:events"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { BoardUi, UI_RETRY_BUTTON_MISSING, UI_RETRY_NO_REQUEST, isRetryRequestFor } from "./board-ui.js"; +import { BoardUi, UI_RETRY_BLOCKED_BY_MODAL, UI_RETRY_BUTTON_MISSING, UI_RETRY_NO_REQUEST, isRetryRequestFor } from "./board-ui.js"; const retry = (issue: string) => `fetch('/api/issues/${issue}/retry',{method:'POST'})`; +const modal = (buttons: string) => `
+

You completed 5 tasks!

${buttons}
`; +const coveredRetry = (issue: string) => `
+
Couldn’t finish this attempt.
`; +const closeModal = "document.querySelector('[role=dialog]').remove();document.querySelector('main').removeAttribute('aria-hidden')"; +const lateModal = `
+

You completed 5 tasks!

`; +const openLateModal = `document.querySelector('main').setAttribute('aria-hidden','true');document.body.insertAdjacentHTML('beforeend', ${JSON.stringify(lateModal).replace(/"/g, """)})`; const pages: Record = { + "/issues/CHA-8": coveredRetry("i8") + modal(``), + "/issues/CHA-9": coveredRetry("i9") + modal(`No way out`), + "/issues/CHA-11": `
Couldn’t finish this attempt. +
`, + "/issues/CHA-10": coveredRetry("i10") + modal(`Press Escape`) + + ``, "/issues/CHA-1": `
Couldn’t finish this attempt.
`, "/issues/CHA-2": `
Saving files from the previous attempt
`, "/issues/CHA-7": `
Couldn’t finish this attempt.
`, @@ -89,6 +103,38 @@ describe("BoardUi.clickRetry", () => { } }, 60_000); + it("dismisses a prompt that covers the Retry with Not now, then clicks Retry", async () => { + await withBoard(async board => { + expect(await board.clickRetry("CHA-8", "i8", 5_000, 1_000)).toMatchObject({ clicked: true, httpStatus: 202, accepted: true, error: null, + dismissedDialogs: [expect.stringContaining("You completed 5 tasks!")] }); + }); + expect(posts).toContain("/api/issues/i8/retry"); + }, 60_000); + + it("closes a prompt without a Not now button with Escape", async () => { + await withBoard(async board => { + expect(await board.clickRetry("CHA-10", "i10", 5_000, 1_000)).toMatchObject({ clicked: true, accepted: true, + dismissedDialogs: [expect.stringContaining("You completed 5 tasks!")] }); + }); + expect(posts).toContain("/api/issues/i10/retry"); + }, 60_000); + + it("closes a prompt that opens after Retry appeared, then clicks Retry", async () => { + await withBoard(async board => { + expect(await board.clickRetry("CHA-11", "i11", 5_000, 1_500)).toMatchObject({ clicked: true, httpStatus: 202, accepted: true, error: null, + dismissedDialogs: [expect.stringContaining("You completed 5 tasks!")] }); + }); + expect(posts).toContain("/api/issues/i11/retry"); + }, 60_000); + + it("names a modal that keeps a visible Retry unreachable", async () => { + await withBoard(async board => { + expect(await board.clickRetry("CHA-9", "i9", 2_000, 500)).toMatchObject({ clicked: false, error: UI_RETRY_BLOCKED_BY_MODAL, + bannerText: expect.stringContaining("Couldn’t finish this attempt") }); + }); + expect(posts).not.toContain("/api/issues/i9/retry"); + }, 60_000); + it("reports a Retry button whose click sends no retry request", async () => { await withBoard(async board => { expect(await board.clickRetry("CHA-3", "i3", 1_500, 500)).toMatchObject({ clicked: true, httpStatus: null, error: UI_RETRY_NO_REQUEST }); diff --git a/tests/restart-chaos/board-ui.ts b/tests/restart-chaos/board-ui.ts index 90390b45288..3677360e8a6 100644 --- a/tests/restart-chaos/board-ui.ts +++ b/tests/restart-chaos/board-ui.ts @@ -1,9 +1,9 @@ import { mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; import { chromium, type Browser, type ElementHandle, type Page } from "@playwright/test"; -import { UI_RETRY_BUTTON_MISSING, UI_RETRY_NO_REQUEST } from "./types.js"; +import { UI_RETRY_BLOCKED_BY_MODAL, UI_RETRY_BUTTON_MISSING, UI_RETRY_NO_REQUEST } from "./types.js"; -export { UI_RETRY_BUTTON_MISSING, UI_RETRY_NO_REQUEST }; +export { UI_RETRY_BLOCKED_BY_MODAL, UI_RETRY_BUTTON_MISSING, UI_RETRY_NO_REQUEST }; export interface UiRetryClick { clicked: boolean; @@ -12,6 +12,7 @@ export interface UiRetryClick { error: string | null; bannerText: string | null; diagnostics?: { screenshot: string | null; dom: string | null } | null; + dismissedDialogs?: string[]; } export async function saveRetryMissingDiagnostics(page: Page, directory: string, label: string) { @@ -37,6 +38,28 @@ export async function saveRetryMissingDiagnostics(page: Page, directory: string, } const PER_BUTTON_REQUEST_MS = 5_000; +const DIALOG_SCAN_MS = 1_000; +const MAX_DISMISSED_DIALOGS = 3; +const BLOCKING_DIALOG = '[role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"], ' + + '[aria-modal="true"]:not([data-state="closed"]), dialog[open]'; +const DISMISS_BUTTON = /^(not now|no thanks|maybe later|dismiss)$/i; + +const blockingDialog = (page: Page) => page.locator(BLOCKING_DIALOG).filter({ visible: true }).first(); + +async function dismissBlockingDialog(page: Page): Promise { + const dialog = blockingDialog(page); + if (!await dialog.isVisible().catch(() => false)) return null; + if (await dialog.getByRole("button", { name: "Retry", exact: true }).count().catch(() => 0)) return null; + const label = (await dialog.innerText().catch(() => "")).trim().split(/\r?\n/)[0]?.slice(0, 120) || "dialog"; + const handle = await dialog.elementHandle().catch(() => null); + const notNow = dialog.getByRole("button", { name: DISMISS_BUTTON }).filter({ visible: true }).first(); + const clicked = await notNow.count().catch(() => 0) > 0 && await notNow.click({ timeout: 2_000 }).then(() => true, () => false); + if (!clicked) await page.keyboard.press("Escape").catch(() => undefined); + const closed = handle + ? await handle.waitForElementState("hidden", { timeout: 2_000 }).then(() => true, () => false) + : !await blockingDialog(page).isVisible().catch(() => false); + return closed ? label : null; +} export function isRetryRequestFor(issueRefs: readonly string[], method: string, url: string): boolean { if (method !== "POST") return false; @@ -61,28 +84,55 @@ export async function clickRetryOnPage(page: Page, url: string, issueRefs: reado const texts = await page.locator("[role=status], [role=alert]").allInnerTexts().catch(() => []); return texts.map(text => text.trim()).filter(Boolean).join(" | ").slice(0, 500) || null; }; - try { - await page.getByRole("button", { name: "Retry", exact: true }).filter({ visible: true }).first() - .waitFor({ state: "visible", timeout: timeoutMs }); - } catch { + const reachable = page.getByRole("button", { name: "Retry", exact: true }).filter({ visible: true }).first(); + const dismissedDialogs: string[] = []; + const dismissed = () => (dismissedDialogs.length ? { dismissedDialogs } : {}); + const dismissDialogs = async () => { + const before = dismissedDialogs.length; + while (dismissedDialogs.length < MAX_DISMISSED_DIALOGS) { + const closed = await dismissBlockingDialog(page); + if (closed === null) break; + dismissedDialogs.push(closed); + } + return dismissedDialogs.length > before; + }; + const blockedByModal = async () => await blockingDialog(page).isVisible().catch(() => false) + && await page.getByRole("button", { name: "Retry", exact: true, includeHidden: true }).filter({ visible: true }).count().catch(() => 0) > 0; + const deadline = Date.now() + timeoutMs; + for (;;) { + await dismissDialogs(); + const remaining = deadline - Date.now(); + if (remaining <= 0) break; + if (await reachable.waitFor({ state: "visible", timeout: Math.min(remaining, DIALOG_SCAN_MS) }).then(() => true, () => false)) break; + } + if (!await reachable.isVisible().catch(() => false)) { const bannerText = await banner(); const diagnostics = diagnosticsDirectory ? await saveRetryMissingDiagnostics(page, diagnosticsDirectory, issueRefs[0] ?? "issue").catch(() => null) : undefined; - return { clicked: false, httpStatus: null, accepted: null, error: UI_RETRY_BUTTON_MISSING, bannerText, - ...(diagnostics !== undefined ? { diagnostics } : {}) }; + const blocked = await blockedByModal(); + return { clicked: false, httpStatus: null, accepted: null, error: blocked ? UI_RETRY_BLOCKED_BY_MODAL : UI_RETRY_BUTTON_MISSING, bannerText, + ...(diagnostics !== undefined ? { diagnostics } : {}), ...dismissed() }; } const bannerText = await banner(); for (const button of await retryButtonsBannerFirst(page)) { - const response = page.waitForResponse(candidate => isRetryRequestFor(issueRefs, candidate.request().method(), candidate.url()), - { timeout: perButtonMs }).catch(() => null); - await button.click().catch(() => undefined); - const answered = await response; - if (!answered) continue; - const body = await answered.json().catch(() => null) as { accepted?: unknown } | null; - return { clicked: true, httpStatus: answered.status(), accepted: answered.ok() ? body?.accepted === true : false, - error: answered.ok() ? null : `retry request failed with ${answered.status()}`, bannerText }; + for (let attempt = 0; attempt < 2; attempt++) { + await dismissDialogs(); + const response = page.waitForResponse(candidate => isRetryRequestFor(issueRefs, candidate.request().method(), candidate.url()), + { timeout: perButtonMs }).catch(() => null); + await button.click({ timeout: perButtonMs }).catch(() => undefined); + const answered = await response; + if (answered) { + const body = await answered.json().catch(() => null) as { accepted?: unknown } | null; + return { clicked: true, httpStatus: answered.status(), accepted: answered.ok() ? body?.accepted === true : false, + error: answered.ok() ? null : `retry request failed with ${answered.status()}`, bannerText, ...dismissed() }; + } + if (!await dismissDialogs()) break; + } } - return { clicked: true, httpStatus: null, accepted: null, error: UI_RETRY_NO_REQUEST, bannerText }; + if (await blockedByModal()) { + return { clicked: false, httpStatus: null, accepted: null, error: UI_RETRY_BLOCKED_BY_MODAL, bannerText, ...dismissed() }; + } + return { clicked: true, httpStatus: null, accepted: null, error: UI_RETRY_NO_REQUEST, bannerText, ...dismissed() }; } export class BoardUi { diff --git a/tests/restart-chaos/grader.test.ts b/tests/restart-chaos/grader.test.ts index cf6aed66e04..f6495d49e68 100644 --- a/tests/restart-chaos/grader.test.ts +++ b/tests/restart-chaos/grader.test.ts @@ -244,6 +244,8 @@ describe("T-oracles", () => { retry: { at: 2, observedRunId: "r1", httpStatus: null, accepted: null, error: "ui_retry_button_missing", via: "ui", bannerText: "Saving files" } } as unknown as TaskRecord; expect(gradeR3(record)).toEqual({ verdict: "fail", detail: "ui_retry_button_missing (user saw: Saving files)" }); expect(gradeR3({ ...record, retry: { ...record.retry!, clicked: true, error: "ui_retry_no_request" } } as TaskRecord).detail).toMatch(/^ui_retry_no_request/); + expect(gradeR3({ ...record, retry: { ...record.retry!, error: "ui_retry_blocked_by_modal" } } as TaskRecord).detail) + .toBe("ui_retry_blocked_by_modal (user saw: Saving files)"); }); it("reports R2 as not checked for a sandbox-only workspace instead of passing it", () => { diff --git a/tests/restart-chaos/grader.ts b/tests/restart-chaos/grader.ts index 14815988041..1a3730f456e 100644 --- a/tests/restart-chaos/grader.ts +++ b/tests/restart-chaos/grader.ts @@ -1,4 +1,4 @@ -import { UI_RETRY_BUTTON_MISSING, UI_RETRY_NO_REQUEST, type FaultReceipt, type OracleResult, type RuleId, type RuleResult, type TaskGrade, type TaskRecord, type TaskSample } from "./types.js"; +import { UI_RETRY_BLOCKED_BY_MODAL, UI_RETRY_BUTTON_MISSING, UI_RETRY_NO_REQUEST, type FaultReceipt, type OracleResult, type RuleId, type RuleResult, type TaskGrade, type TaskRecord, type TaskSample } from "./types.js"; import { g1Decision } from "./workloads.js"; import { enforcedUniversalFailures, gradeUniversal, type UniversalDbEvidence } from "./universal.js"; @@ -112,7 +112,7 @@ function gradeOwnRetry(record: TaskRecord): RuleResult { } return { verdict: "n/a", detail: "no Retry needed" }; } - if (record.retry.via === "ui" && (record.retry.error === UI_RETRY_BUTTON_MISSING || record.retry.error === UI_RETRY_NO_REQUEST)) { + if (record.retry.via === "ui" && [UI_RETRY_BUTTON_MISSING, UI_RETRY_NO_REQUEST, UI_RETRY_BLOCKED_BY_MODAL].includes(record.retry.error ?? "")) { return { verdict: "fail", detail: `${record.retry.error}${record.retry.bannerText ? ` (user saw: ${record.retry.bannerText})` : ""}` }; } if (record.retry.error || record.retry.accepted !== true) { diff --git a/tests/restart-chaos/observer.ts b/tests/restart-chaos/observer.ts index 7ba82e01fda..8618de508c1 100644 --- a/tests/restart-chaos/observer.ts +++ b/tests/restart-chaos/observer.ts @@ -718,7 +718,8 @@ export class TaskObserver { if (this.board) { const click = await this.board.clickRetry(issueRef, issueId); Object.assign(attempt, { via: "ui", httpStatus: click.httpStatus, accepted: click.accepted, error: click.error, bannerText: click.bannerText, - ...(click.diagnostics !== undefined ? { diagnostics: click.diagnostics } : {}) }); + ...(click.diagnostics !== undefined ? { diagnostics: click.diagnostics } : {}), + ...(click.dismissedDialogs?.length ? { dismissedDialogs: click.dismissedDialogs } : {}) }); if (click.accepted) attempt.acceptedAt = Math.max(now, Date.now()); return attempt; } diff --git a/tests/restart-chaos/types.ts b/tests/restart-chaos/types.ts index 0dee982800e..451dc26240e 100644 --- a/tests/restart-chaos/types.ts +++ b/tests/restart-chaos/types.ts @@ -256,10 +256,12 @@ export interface RetryAttempt { via?: "ui" | "api"; bannerText?: string | null; diagnostics?: { screenshot: string | null; dom: string | null } | null; + dismissedDialogs?: string[]; } export const UI_RETRY_BUTTON_MISSING = "ui_retry_button_missing"; export const UI_RETRY_NO_REQUEST = "ui_retry_no_request"; +export const UI_RETRY_BLOCKED_BY_MODAL = "ui_retry_blocked_by_modal"; export interface FaultReceipt { faultId: string; From e719d425571c14727a07899517d5988282115655 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:53:53 -0600 Subject: [PATCH 31/38] fix(runner): accept the acknowledgement of an indeterminate suspend replay (#20714) 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. > - A native run talks to a Runner process (runnerd). The controller in the server sends commands. The Runner journals each command before it acts and replies with a result. > - `runner.suspend` and `runner.shutdown` are terminal commands. The Runner waits for a `command_result_ack` before it exits. It compares that acknowledgement with the receipt that it journaled. > - A Runner that is killed inside `runner.suspend` journals the command but not its result. The next Runner replays the command as `indeterminate`. It sends it on the wire as `failed` with `execution_indeterminate`, and it still treats it as terminal. > - The controller acknowledged the `failed` status that it received. The Runner compared that with its journal status `indeterminate` and exited with "terminal command result acknowledgement changed its durable identity". The controller also lifted its terminal fence for a failed suspend and sent the next command to a Runner that was about to exit. > - This pull request makes both sides agree on the status of that one receipt, and keeps the fence. > - The benefit is that a freeze or restart during a suspend no longer burns the same-run retries and leaves the task at a manual Retry. ## Linked Issues or Issue Description **What happened?** A restart-chaos task (local Runner, Claude, a 28-second freeze of the server during a live turn) needed a manual Retry. Retry worked. 1. The turn completed. The server then sent `runner.suspend`. The server froze before the Runner reported the result. 2. The close found the Runner not durably suspended (`commandStatus: pending`, `runnerLifecycle: ready`). The run failed with `native_runner_checkpoint_owner_lost`, and same-run recovery stopped the old runnerd. The suspend was journaled but not finished. 3. Attempt 2 started a new runnerd on the same state. The welcome delivered the stale suspend. The Runner replayed it as `indeterminate` and sent `failed`. The controller acknowledged `failed`. The Runner exited with code 1: "terminal command result acknowledgement changed its durable identity". The controller had recorded the suspend as `failed`. 4. Attempt 3 found the fence for a suspend that the controller no longer listed as pending. The Runner reconciled it and exited with code 0. The server reported "runnerd exited unexpectedly with code 0", and `native_session_retry_exhausted` stopped automatic recovery. **Expected behavior** The controller acknowledges exactly the receipt that the Runner sent. The Runner accepts that acknowledgement, records `suspended`, and the next attempt starts from a clean suspended Runner. **Steps to reproduce** 1. Start a native run with a local Runner. Let the turn complete so that the server sends `runner.suspend`. 2. Freeze the server (SIGSTOP) for about 30 seconds before the suspend result arrives, so that recovery stops the Runner inside the suspend. 3. Let same-run recovery start a new Runner. It exits with "terminal command result acknowledgement changed its durable identity". The unit tests in this PR reproduce the same sequence without a live run. **Paperclip version or commit** `master` at 200c6e40e2. The failing wave ran on 9296c74e8d plus #20656. **Root cause** `command_result_envelope` changes the journal status `indeterminate` to `failed` on the wire. `wait_for_terminal_result_ack` compared the acknowledgement with the journal status, not with the status that it sent. The controller also treated a `failed` suspend as a refused suspend (the Runner keeps serving), but the Runner treats an indeterminate suspend as terminal. ## What Changed - Runner (`runner.rs`): a new `wire_command_status` gives the status that goes on the wire. `wait_for_terminal_result_ack` accepts the acknowledgement when its status is the wire status (`failed`) or the journal status (`indeterminate`). Command id, type, and controller sequence must still match exactly. - Controller (`durable-prp-control-plane.ts`): for a result with `execution_indeterminate`, the `command_result_ack` names `indeterminate`. Runners that shipped before this change accept only that status. The controller keeps the terminal-lifecycle fence for an indeterminate suspend, so it does not send the next command to a Runner that is exiting. The command stays `failed` in the controller journal, as before. - Runner Rust test `indeterminate_suspend_replay_accepts_the_acknowledged_wire_status`: it seeds a journaled suspend, starts the Runner against a fake controller that acknowledges `failed` and then `indeterminate`, and checks that the Runner finishes as `suspended` with no fence. Before the fix it failed with the production message. - Controller test: it checks the `indeterminate` acknowledgement and that the next queued command is not delivered on that connection. - `docs/durable-recovery.md`: it describes this case. ## Verification - Red, then green: `cargo test -p paperclip-runner-core --lib indeterminate_suspend_replay` failed with `DurableRunnerError("terminal command result acknowledgement changed its durable identity")` before the Runner change and passes after it. - Red, then green: `npx vitest run src/control-plane/durable-prp-control-plane.test.ts -t "indeterminate suspension"` failed (`status: "failed"`, expected `"indeterminate"`) before the controller change and passes after it. - `cargo test -p paperclip-runner-core --lib durable`: 152 passed. - `npx vitest run src/control-plane/durable-prp-control-plane.test.ts`: 215 passed. - `npx vitest run src/live/runnerd-codex-transport-settlement.test.ts src/live/runnerd-codex-transport-suspension.test.ts`: 30 passed. These use the real runnerd binary built from `master`, so they also cover the new controller with an old Runner. - `npx tsc --noEmit -p packages/paperclip-runner`: clean. - `pnpm verify` returned exit 2 (broad input). Required CI supplies the broad coverage. - Not run: a chaos wave. The unit tests reproduce the exact sequence at the Runner and controller boundary. ## Risks - Version mix. Old Runner with new server: the acknowledgement says `indeterminate`, which is the old Runner's journal status, so it is accepted. New Runner with old server: the acknowledgement says `failed`, which is the new Runner's wire status, so it is accepted. New with new: accepted. - No command runs again. The indeterminate suspend is never executed again; only its acknowledgement changes. The Runner still refuses a different command id, type, or controller sequence. - The Runner change takes effect only after a new Runner image. The controller change alone removes the failure for Runners that already shipped. - Remaining gap: the attempt that delivers the stale suspend still ends when that Runner exits as suspended. The next same-run attempt then starts from a clean suspended Runner. A later change can restart the Runner inside the same attempt. > 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, in Claude Code with tool use (shell, file edits, test runs). Extended reasoning. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude --- .../paperclip-runner/docs/durable-recovery.md | 10 ++ .../crates/runner-core/src/durable/runner.rs | 25 ++- .../tests/indeterminate_terminal_ack.rs | 142 ++++++++++++++++++ .../runner-core/src/durable/transport.rs | 1 + .../durable-prp-control-plane.test.ts | 48 ++++++ .../durable-prp-control-plane.ts | 19 ++- 6 files changed, 236 insertions(+), 9 deletions(-) create mode 100644 packages/paperclip-runner/runner/crates/runner-core/src/durable/tests/indeterminate_terminal_ack.rs diff --git a/packages/paperclip-runner/docs/durable-recovery.md b/packages/paperclip-runner/docs/durable-recovery.md index b146dc651a2..040fb5748e2 100644 --- a/packages/paperclip-runner/docs/durable-recovery.md +++ b/packages/paperclip-runner/docs/durable-recovery.md @@ -233,6 +233,16 @@ Attaching starts no turn, and the runner admits the new command only for a settled session, so the run continues instead of failing on the old command. Warm transitions and staged attachments keep their exact replay paths. +A restart can kill the runner inside `runner.suspend` in the same way. The +next runner replays it from the welcome as `execution_indeterminate`, sends it +as `failed`, and still treats it as terminal: it records `suspended` and exits +once the controller acknowledges the result. The controller therefore keeps the +terminal fence for that result (it lifts the fence only for a suspension the +runner refused), and its acknowledgement names the runner's journal status +`indeterminate`. Current runners accept either `indeterminate` or `failed`; older +runners accept only `indeterminate` and otherwise exit with "terminal command +result acknowledgement changed its durable identity". + A kill during that attachment's provider launch can also leave a `spawned` startup fence over a `prepared` state that holds a saved thread. The next runner retires that fence once the recorded provider process and its group have exited, diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/durable/runner.rs b/packages/paperclip-runner/runner/crates/runner-core/src/durable/runner.rs index fb8099b141a..ae1d3bb7aa4 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/durable/runner.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/durable/runner.rs @@ -1752,13 +1752,18 @@ fn wait_for_terminal_result_ack( "terminal command result acknowledgement payload is required", ) })?; + // The controller acknowledges the status it received. An + // indeterminate journal entry travels as `failed`, so either + // spelling names this exact receipt. + let status = payload.get("status").and_then(Value::as_str); if payload.get("commandId").and_then(Value::as_str) != Some(result.command_id.as_str()) || payload.get("commandType").and_then(Value::as_str) != Some(result.command_type.as_str()) || payload.get("controllerSeq").and_then(Value::as_u64) != Some(result.controller_seq) - || payload.get("status").and_then(Value::as_str) != Some(result.status.as_str()) + || (status != Some(result.status.as_str()) + && status != Some(wire_command_status(result))) { return Err(DurableRunnerError::invalid( "terminal command result acknowledgement changed its durable identity", @@ -2551,18 +2556,24 @@ fn send_outbox( Ok(()) } +/// "indeterminate" is an internal crash-recovery journal state. On the wire it +/// is a failed command with the preserved execution_indeterminate reason so the +/// controller can settle the command and continue replay. +fn wire_command_status(result: &StoredCommandResult) -> &str { + if result.status == "indeterminate" { + "failed" + } else { + result.status.as_str() + } +} + fn command_result_envelope( state: &DurableState, result: &StoredCommandResult, protocol_version: u64, ) -> Value { let mut payload = json!(result); - // "indeterminate" is an internal crash-recovery journal state. On the - // wire it is a failed command with the preserved execution_indeterminate - // reason so the controller can settle the command and continue replay. - if result.status == "indeterminate" { - payload["status"] = json!("failed"); - } + payload["status"] = json!(wire_command_status(result)); json!({ "protocol": PROTOCOL, "version": protocol_version, diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/durable/tests/indeterminate_terminal_ack.rs b/packages/paperclip-runner/runner/crates/runner-core/src/durable/tests/indeterminate_terminal_ack.rs new file mode 100644 index 00000000000..2fd8d69188b --- /dev/null +++ b/packages/paperclip-runner/runner/crates/runner-core/src/durable/tests/indeterminate_terminal_ack.rs @@ -0,0 +1,142 @@ +/// A runnerd killed inside `runner.suspend` leaves it journaled but unfinished. +/// The next process replays it as `indeterminate`, sends it as `failed`, and the +/// controller acknowledges the `failed` it received. That acknowledgement names +/// the same receipt: the runner finishes the suspension instead of exiting with +/// "terminal command result acknowledgement changed its durable identity". +#[test] +fn indeterminate_suspend_replay_accepts_the_acknowledged_wire_status() { + for acknowledged in ["failed", "indeterminate"] { + indeterminate_suspend_replay_is_acknowledged(acknowledged); + } +} + +fn indeterminate_suspend_replay_is_acknowledged(acknowledged_status: &'static str) { + struct NeverExecutes; + + impl super::super::CommandExecutor for NeverExecutes { + fn execute( + &mut self, + command: &Command, + ) -> Result { + panic!("an indeterminate {} must never execute again", command.command_type); + } + } + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let mut config = config(port); + config.max_runtime = Duration::from_secs(5); + let directory = std::env::temp_dir().join(format!( + "paperclip-runner-indeterminate-terminal-ack-{}-{acknowledged_status}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&directory); + config.state_dir = directory.clone(); + let suspend = json!({ + "schema": "paperclip.prp.command.v1", + "commandId": "command_suspend", + "controllerSeq": 1, + "type": "runner.suspend", + "issuedAt": "2026-11-11T01:34:11.000Z", + "payload": {}, + }); + { + // The prior process journaled the suspend before its effect and died. + let store = super::super::DurableStateStore::new(&directory).unwrap(); + let (mut state, _) = store.load_or_create(&config).unwrap(); + let command: Command = serde_json::from_value(suspend.clone()).unwrap(); + assert_eq!( + state.begin_command(&command).unwrap(), + super::super::CommandDisposition::Execute + ); + store.save(&state).unwrap(); + } + + let state = test_state(&config); + let expires = current_unix_ms().unwrap() + 60_000; + let server_config = config.clone(); + let server_state = state.clone(); + let server = thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let mut socket = accept(stream).unwrap(); + let mut secure = server_authenticate( + &mut socket, + &server_config, + &server_state, + ServerCredential { + token: "bootstrap-secret", + kind: "bootstrap", + lease_id: None, + expires_at_unix_ms: expires, + revocation_epoch: 0, + }, + ); + send_secure( + &mut socket, + &mut secure, + &server_config, + &welcome( + &server_state, + "connection_1", + Some("lease-secret"), + expires, + 0, + vec![suspend], + ), + ); + let result = receive_secure(&mut socket, &mut secure, &server_config); + assert_eq!(result["kind"], "command_result"); + assert_eq!(result["payload"]["commandId"], "command_suspend"); + assert_eq!(result["payload"]["status"], "failed"); + assert_eq!( + result["payload"]["result"]["code"], + "execution_indeterminate" + ); + send_secure( + &mut socket, + &mut secure, + &server_config, + &control( + &server_state, + "connection_1", + "command_result_ack", + json!({ + "commandId": "command_suspend", + "commandType": "runner.suspend", + "controllerSeq": 1, + "status": acknowledged_status, + }), + ), + ); + // Acknowledge any terminal suffix until the runner closes. + while let Ok(frame) = receive_plain(&mut socket, server_config.max_frame_bytes) { + let message = secure.decrypt(&frame, true).unwrap(); + if message["kind"] == "event" { + send_secure( + &mut socket, + &mut secure, + &server_config, + &control( + &server_state, + "connection_1", + "ack", + json!({"ackedSourceSeq": message["payload"]["sourceSeq"]}), + ), + ); + } + } + }); + + super::super::run_durable_runner( + config.clone(), + BootstrapTicket::new("bootstrap-secret".to_owned()).unwrap(), + NeverExecutes, + ) + .unwrap(); + server.join().unwrap(); + let store = super::super::DurableStateStore::new(&directory).unwrap(); + let (state, _) = store.load_or_create(&config).unwrap(); + assert_eq!(state.lifecycle, "suspended"); + assert!(state.pending_terminal_delivery.is_none()); + std::fs::remove_dir_all(directory).unwrap(); +} diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/durable/transport.rs b/packages/paperclip-runner/runner/crates/runner-core/src/durable/transport.rs index e64d60ddf9a..8b245375882 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/durable/transport.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/durable/transport.rs @@ -1764,6 +1764,7 @@ mod tests { #[cfg(unix)] include!("tests/hosted_retention.rs"); include!("tests/ack_release_poll.rs"); + include!("tests/indeterminate_terminal_ack.rs"); use std::net::{IpAddr, Ipv4Addr, TcpListener}; use std::path::PathBuf; diff --git a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.test.ts b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.test.ts index fa77aafb347..698f8a475bc 100644 --- a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.test.ts +++ b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.test.ts @@ -5377,6 +5377,54 @@ describe("DurablePrpControlPlane", () => { } }); + it("acknowledges an indeterminate suspension in the Runner's journal status and keeps its fence", async () => { + // A runnerd killed inside runner.suspend journals it as indeterminate. The + // next runnerd replays it from the welcome as `failed` with + // execution_indeterminate and then exits as suspended. Shipped Runners + // compare the acknowledgement with their journal status and exited with + // "terminal command result acknowledgement changed its durable identity". + const root = mkdtempSync(resolve(tmpdir(), "paperclip-prp-indeterminate-suspend-")); + const controlPlane = new DurablePrpControlPlane({ + stateDirectory: root, + identity, + expectedRunnerVersion, + expectedRunnerDigest, + }); + try { + await controlPlane.start(); + const stale = controlPlane.queueCommand("runner.suspend", {}, "command-suspend-stale"); + const next = controlPlane.queueCommand("session.snapshot", {}, "command-snapshot-next"); + const client = await authenticate(controlPlane, controlPlane.issueBootstrapTicket()); + sendSecure(client!, { + protocol: "paperclip.runner", version: 1, kind: "command_result", + payload: { + commandId: stale.commandId, commandType: stale.type, controllerSeq: stale.controllerSeq, + status: "failed", + result: { + code: "execution_indeterminate", + message: "runner recovered after journaling this command; it will not execute twice", + }, + }, + }); + await expect(receiveSecure(client!)).resolves.toMatchObject({ + kind: "command_result_ack", + payload: { + commandId: "command-suspend-stale", + commandType: "runner.suspend", + controllerSeq: stale.controllerSeq, + status: "indeterminate", + }, + }); + expect(controlPlane.getCommand(stale.commandId)?.status).toBe("failed"); + // The Runner is leaving as suspended; nothing may follow on this connection. + expect(controlPlane.store.state.commandDeliveryCounts[next.commandId]).toBeUndefined(); + client?.socket.destroy(); + } finally { + await controlPlane.stop(); + rmSync(root, { recursive: true, force: true }); + } + }); + it("acknowledges terminal command results after persisting them", async () => { const root = mkdtempSync(resolve(tmpdir(), "paperclip-prp-terminal-ack-")); const controlPlane = new DurablePrpControlPlane({ diff --git a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts index 6e755c227f0..4a0ca8354a8 100644 --- a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts +++ b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts @@ -84,6 +84,15 @@ export function isRunnerRecoveryMaintenanceCommand(type: string): boolean { return ["session.snapshot", "session.goal.get", "runner.drain", "runner.suspend", "runner.shutdown", "turn.stop"].includes(type); } +/** The Runner journaled this command before its effect, then died. It sends + * that `indeterminate` entry as `failed` with `execution_indeterminate`, never + * executes it again, and still treats a lifecycle command as terminal. */ +function isIndeterminateCommandResult(command: DurableRecoveryCoreCommand): boolean { + if (command.status === "indeterminate") return true; + const detail = command.result?.result; + return command.status === "failed" && isRecord(detail) && detail.code === "execution_indeterminate"; +} + const commandTypes = new Set([ "run.prepare", "run.attach", @@ -4102,7 +4111,8 @@ export class DurablePrpControlPlane { * A rejected runner.suspend changes no provider state, and the runner keeps * serving this connection. Lift the terminal-lifecycle fence it installed * so the controller's next command (a fresh suspend) can be delivered. - * Completed suspensions and every shutdown keep the fence. + * Completed suspensions and every shutdown keep the fence. So does an + * indeterminate suspension: the Runner treats it as terminal and exits. */ #releaseServingLifecycle( connection: AuthorityConnection, @@ -4111,6 +4121,7 @@ export class DurablePrpControlPlane { if ( command.type === "runner.suspend" && (command.status === "failed" || command.status === "rejected") && + !isIndeterminateCommandResult(command) && connection.terminalLifecycleCommandId === command.commandId ) { connection.terminalLifecycleCommandId = null; @@ -4159,7 +4170,11 @@ export class DurablePrpControlPlane { commandId: command.commandId, commandType: command.type, controllerSeq: command.controllerSeq, - status: command.status, + // A Runner journals a command it may have started before dying as + // `indeterminate` and sends it as `failed`. Runners compare this + // acknowledgement with their journal, so name that journal status; + // current Runners accept either spelling. + status: isIndeterminateCommandResult(command) ? "indeterminate" : command.status, }, ), ); From e039be9202ae500f7a0448127f4c7bff42123495 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 22:57:54 -0600 Subject: [PATCH 32/38] fix(runner): replace a follow-up session whose remote workspace root moved (#20712) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Native runs keep an execution lease. Restart recovery takes over a run only when it can prove that the recorded controller stopped. > - A stall (SIGSTOP) longer than the lease, with no restart, makes the executor lose its own lease. The executor then detaches for "the next controller" and exits. > - The next controller is this same process. Recovery asks the PID probe if the recorded controller is alive. The recorded controller is this process, so the answer is always "alive". > - The task then waits forever: `in_progress`, no Retry, an active run, and an active environment lease. > - This pull request lets recovery recognise its own process. When this process no longer drives the run and its own lease lapsed, the prior owner is gone. The existing evidence checks then decide, as for any stopped controller. > - The benefit is that a same-boot stall never needs a manual Retry. When provider work may have started, the run fails with a working Retry instead of a wait with no end. ## Linked Issues or Issue Description Refs #20694 (the same class of fix for legacy `preparing` runs), #20529, #20691. **What happened?** Chaos wave `w-20261111T034105-s9330`, task t02 (Daytona, OpenCode, fault TM1). The server process was frozen with SIGSTOP for about 84 s while run `89a3922b` prepared. After SIGCONT, `native.process_start_requested` was recorded and `native.session.execute` failed after 118 ms: the lease renewal found the lease lapsed, and the executor detached and exited. From then on, recovery recorded `native.recovery.transition` "waiting for safe ownership evidence" with reason `controller_still_alive` every 30 s for more than 20 minutes. The run stayed `running`, the issue stayed `in_progress`, no Retry was shown, and the environment lease stayed `active`. **Expected behavior** When this process no longer drives a run that it recorded as its own, recovery takes the run back. No turn reached the runner here, so the bootstrap restarts on the same run. When a turn or runner work may have started, the run fails and shows a working Retry. **Steps to reproduce** 1. Start a native remote (Daytona) run. 2. Send SIGSTOP to the server during preparation, and hold it longer than the execution lease. 3. Send SIGCONT. The executor loses its lease, detaches and exits. 4. See that every recovery scan waits with `controller_still_alive`, and the run never settles. The new tests in `native-runner-restart-recovery.integration.test.ts` ("same-boot controller whose own lease lapsed") reproduce this at the recovery layer. ## What Changed - `claimNativeRestartRecoveries`: when the recorded controller is this exact process (same boot ID and PID): - If this process still drives the run (heartbeat execution or native executor registered), recovery leaves the run to it (`current_controller_preparing`). - If neither drives it and the self lease lapsed, the takeover is allowed (`current_controller_released`). The existing evidence checks then choose the outcome: bootstrap again on the same run when a durable record proves no command reached the runner, or fail with a Retry (`blocked`) when runner or provider work may have started. - An unexpired self lease still waits. A claim that has not reached its executor holds it, and it lapses by itself. - A run that this process handed to the next server (graceful drain `restart_suspended` record, or the in-process hot-restart handoff marker) stays with the next server. - `heartbeat/shutdown-handoff.ts`: add `isRunHandedOffForShutdown`. Heartbeat recovery passes it to the claim. - `suspendedByCleanDrain` now uses the shared `handedToNextControllerSinceClaim` helper. Behavior is the same. - Tests: five cases for the same-boot lapsed lease: bootstrap again with no runner command; fail with a working Retry when a runner identity was recorded; leave the run to a live in-process executor; leave a handed-off run to the next server; still wait for a different live controller. ## Verification - Red before the fix: the three same-boot cases returned `awaiting_evidence` / `controller_still_alive`. - Green after the fix: - `pnpm --dir server exec vitest run src/services/native-runtime/native-runner-restart-recovery.integration.test.ts src/services/native-runtime/native-restart-recovery.test.ts src/__tests__/heartbeat-native-restart-suspension.test.ts` - `pnpm verify` (see the PR comments for the selected scope). - `tsc --noEmit -p server` is clean. ## Risks - A same-process recovery scan can now claim a run that this process recorded as its own. The guard needs all of these: the self lease lapsed, no in-process execution of the run, and no handoff to the next server. A claim that is still on its way to its executor holds a live lease, so it is not taken twice. - Upgrade safety: the decision uses only the coordinator row and in-process state. Old saved rows are judged by the same rules. A new process never matches an old boot ID, so deploys keep the existing proof path. - No new waits or file operations run before `turn.start`. - There is still no ceiling on `awaiting_evidence` for a genuinely different live controller (case c). This PR does not change that policy. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code, with tool use (shell, file edit) and extended reasoning. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- .../backends/native-backend-factory.test.ts | 60 +++++++++++++++++++ .../codex/codex-app-server-driver-impl.ts | 20 +++++++ .../src/drivers/codex/codex-boundaries.ts | 24 ++++++++ 3 files changed, 104 insertions(+) diff --git a/packages/paperclip-runner/src/backends/native-backend-factory.test.ts b/packages/paperclip-runner/src/backends/native-backend-factory.test.ts index a0cf6f0e9b5..afaadd9defa 100644 --- a/packages/paperclip-runner/src/backends/native-backend-factory.test.ts +++ b/packages/paperclip-runner/src/backends/native-backend-factory.test.ts @@ -407,6 +407,66 @@ describe("native backend factory", () => { if (recovered.recovered) await recovered.session!.close({ reason: "test complete" }); }); + // An abandoned remote workspace epoch is restored into a new sibling root + // under `.paperclip-workspaces`, while the follow-up inherits a checkpoint + // that names the old root. Resume there is impossible, but it is an ordinary + // resume failure: the runtime's replacement policy must decide, not a thrown + // admission error that ends the run as native_session_interrupted. + it.each([ + ["Codex", execution()], + ["ACPX Claude", acpxExecution("claude")], + ])("declines to recover a %s session saved under a moved remote workspace root", async (_label, input) => { + const { transport, factory, backend, snapshot } = movedRootRecovery(input); + const recovered = await backend.recoverSession!(snapshot as never, { signal: new AbortController().signal }); + expect(recovered).toEqual({ + recovered: false, + reason: "persisted session working directory is not the assigned remote workspace", + }); + // No Runner or provider process is started for a session that cannot resume here. + expect(factory).not.toHaveBeenCalled(); + expect(transport.calls).toEqual([]); + }); + + it.each([ + ["an active turn", { activeTurnId: "turn-in-flight" }], + ["a pending runtime request", { pendingRuntimeRequests: [{ requestId: "request-1" }] }], + ])("keeps refusing a moved-root session that holds %s", async (_label, inFlight) => { + const { factory, backend, snapshot } = movedRootRecovery(acpxExecution("claude")); + await expect(backend.recoverSession!({ ...snapshot, ...inFlight } as never, { signal: new AbortController().signal })) + .rejects.toThrow("Remote Codex working directory does not match the assigned workspace"); + expect(factory).not.toHaveBeenCalled(); + }); + + it.each([ + ["a filesystem root", "/", "Codex working directory cannot be a filesystem root"], + ["an unnormalized path", "/home/daytona/../root", "normalized absolute path"], + ])("keeps refusing a saved session whose working directory is %s", async (_label, workingDirectory, message) => { + const { factory, backend, snapshot } = movedRootRecovery(acpxExecution("claude")); + await expect(backend.recoverSession!({ ...snapshot, workingDirectory } as never, { signal: new AbortController().signal })) + .rejects.toThrow(message); + expect(factory).not.toHaveBeenCalled(); + }); + + function movedRootRecovery(input: NativeExecutionInputV1) { + const parent = "/home/daytona/paperclip-workspace/.paperclip-workspaces"; + const workspaceId = "a5a34403-04fe-4e7e-97cf-d8f371a802a4"; + const savedRoot = `${parent}/${workspaceId}-1-80214561-2151-4112-a43a-7d65f3071b56`; + const assignedRoot = `${parent}/${workspaceId}-5-ef79592c-6784-438f-8a17-9800dd2fa2fc`; + const transport = new FakeCodexTransport(); + const factory = vi.fn(() => transport); + const backend = createNativeSessionBackend(input, { + codexTransportFactory: factory, workingDirectoryAuthority: "remote_runner", + environment: { PAPERCLIP_WORKSPACE_CWD: assignedRoot }, + }); + const snapshot = { + schema: "paperclip.native-session.v1", backendKind: "codex_app_server", driverKind: "codex_app_server", + sessionId: transport.threadId, providerSessionId: transport.providerSessionId, workingDirectory: savedRoot, + identity: { runId: "run", sessionId: "session", companyId: "company", issueId: "issue", agentId: "agent" }, + activeTurnId: null, terminalTurns: [], pendingRuntimeRequests: [], lastCursor: null, + }; + return { transport, factory, backend, snapshot }; + } + describe("runner-prepared launch working directory", () => { // The transport reports the prepared directory; it exists only on the VM. class PreparedLaunchTransport extends FakeCodexTransport { diff --git a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts index 7086713a4dc..52641c405ed 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts @@ -38,6 +38,7 @@ import { import { boundedCodexValue, codexThreadWorkingDirectory, + remoteRunnerWorkingDirectoryMoved, validateCodexWorkingDirectory as validateWorkingDirectory, } from "./codex-boundaries.js"; import { @@ -395,6 +396,25 @@ export class CodexAppServerDriver implements HarnessDriver { reason: "persisted session identity is incomplete", }; } + // A session saved under an abandoned remote workspace root cannot resume + // in the newly assigned root. When it holds no in-flight turn or runtime + // request (a follow-up's inherited checkpoint, for example), decline + // before any Runner or provider process starts, so the runtime's recovery + // policy decides: a replacement in the assigned workspace, or a named + // refusal. In-flight provider work keeps the stricter admission refusal, + // because nothing here can prove its side effects settled. + if ( + snapshot.workingDirectory && + !snapshot.activeTurnId && + !(snapshot.pendingRuntimeRequests?.length) && + this.#options.workingDirectoryAuthority === "remote_runner" && + remoteRunnerWorkingDirectoryMoved(snapshot.workingDirectory, this.#options.environment) + ) { + return { + recovered: false, + reason: "persisted session working directory is not the assigned remote workspace", + }; + } const transport = this.#transport({ workingDirectory: snapshot.workingDirectory ? validateWorkingDirectory(snapshot.workingDirectory, this.#options.environment, this.#options.workingDirectoryAuthority) diff --git a/packages/paperclip-runner/src/drivers/codex/codex-boundaries.ts b/packages/paperclip-runner/src/drivers/codex/codex-boundaries.ts index 84de048918a..cd36389978f 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-boundaries.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-boundaries.ts @@ -187,6 +187,30 @@ export function codexThreadWorkingDirectory( return returned; } +/** + * Whether a saved session names a remote workspace root other than the one + * Core assigned to this run. A workspace epoch that was abandoned (for example + * after a restart killed its preparation) is restored into a new sibling root, + * so a session saved under the old root cannot resume here. That is an + * ordinary resume failure, not an invalid admission: both paths are + * well-formed and only differ. Malformed paths and a missing assignment are + * still refused by validateCodexWorkingDirectory. + */ +export function remoteRunnerWorkingDirectoryMoved( + savedWorkingDirectory: string, + environment: NodeJS.ProcessEnv = process.env, +): boolean { + const assigned = environment.PAPERCLIP_WORKSPACE_CWD?.trim(); + return Boolean( + assigned && + isNormalizedRemotePath(assigned) && + assigned !== posix.parse(assigned).root && + isNormalizedRemotePath(savedWorkingDirectory) && + savedWorkingDirectory !== posix.parse(savedWorkingDirectory).root && + savedWorkingDirectory !== assigned, + ); +} + function validateRemoteRunnerWorkingDirectory( workingDirectory: string, environment: NodeJS.ProcessEnv, From 1fa7e92fa83087fbf427ff18c2d11fa0a4a21d85 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:25:29 -0600 Subject: [PATCH 33/38] fix(native): restart in place a Runner that only settled an earlier attempt's suspend (#20724) 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. > - A native run talks to a Runner process. When the control plane loses that Runner, the run resumes itself with a limited number of same-run attempts. > - A server freeze while the controller suspends a finished turn can stop the Runner inside `runner.suspend`. The controller journal then keeps that suspend as pending. > - The next attempt starts a new Runner. It settles the old suspend from the welcome, records `suspended`, and exits with code 0 before it accepts any command of the new attempt. The server reported "runnerd exited unexpectedly with code 0", so one freeze spent one same-run attempt. If a second fault then occurs, no attempt is left in reserve. > - #20714 made both sides agree on that suspend's acknowledgement. This pull request handles the clean exit that follows it. > - During startup, the server restarts that Runner in place once, through the existing `#recoverRunnerProcess` path, and only when the durable Runner journal proves the exit. > - The benefit is that one freeze during a suspend costs zero same-run attempts. ## Linked Issues or Issue Description Refs #20714. **What happened?** A restart-chaos task (local Runner, Claude, a freeze of the server during a live turn) needed a manual Retry. #20714 fixed the identity mismatch. The second same-run attempt still ended with `runner_local_connect_failed: runnerd exited unexpectedly with code 0`, because that Runner only settled the suspend left by the first attempt and then exited as suspended. **Expected behavior** The attempt continues. The server restarts the Runner once. The new Runner starts from a clean `suspended` state and serves the attempt's commands. No provider work is repeated. **Steps to reproduce** 1. Start a native run. Let the controller send `runner.suspend` when it closes the session. 2. Stop the Runner after it journaled the suspend and before the controller records the result (a server freeze does this). 3. Resume the same run. The new Runner settles the old suspend and exits with code 0, and startup fails. The new live test reproduces this with the real runnerd and the fake Codex provider. **Paperclip version or commit** `master` at e719d42557 (after #20714). ## What Changed - `runnerd-codex-transport.ts`: when the transport opens its controller, it records the number of commands already in the journal. These commands come from earlier attempts. - When a Runner exits with code 0 during startup, the transport reads the local Runner state once. It restarts the Runner in place, once per attempt, with a bounded 30 s grace through the existing `#recoverRunnerProcess`, only when all of these are true: - the Runner's last command is a `runner.suspend` from an earlier attempt, with the same command id, type and controller sequence in both journals; - the controller has settled that suspend; - the Runner is `suspended`, with no terminal fence, no provider cleanup fence and no warm transition; - no command of this attempt has a result, so no turn started and no provider work ran. - While that one restart runs, the startup waits for the replacement. The startup does not fail on the old process. - An exit that does not have that proof keeps its earlier failure. So do remote, external-state and adopted Runners. - The proof is a pure function, `carriedSuspendSettlementProven`, exported through `runnerdRecoveryInternals`. - `docs/durable-recovery.md`: it describes the restart. ## Verification - Red, then green. New live test `runnerd-codex-transport-carried-suspend.test.ts` (real runnerd binary, fake Codex): - `journaled`: the journals are rewritten to the freeze moment. Before the change: `runner_local_connect_failed: runnerd exited unexpectedly with code 0`. After the change: `thread/read` succeeds in the same attempt, the old suspend is `failed / execution_indeterminate`, and the provider has no `turn/start`. - `fenced`: a released build left a terminal fence. The next Runner keeps a provider cleanup fence, so it is not restarted. The test checks that the earlier failure stays. - Unit negatives for the proof: a suspend that this attempt queued, an unsettled suspend, a last command that is not a suspend, a Runner that went on to a later command, a command of this attempt with a result, a Runner that is not suspended or has a fence, a receipt mismatch, and another run identity. - The live test passes with the Runner binary from before #20714 and with the current `master` Runner. - `npx tsc --noEmit -p packages/paperclip-runner`: clean. - `runnerd-codex-transport.test.ts`, `-cut-attach`, `-settlement`, `-suspension`, `-cold-restore`: 335 of 336 passed in one parallel run. The one failure was a 20 s settlement case under load, and it passed when run alone (19/19). ## Risks - A clean exit that is not this case keeps its earlier failure. The proof needs exact durable evidence. The restart happens at most once per attempt and is bounded to 30 s. - No command runs again. The old suspend is never executed again. The replacement Runner starts from `suspended` and receives this attempt's commands for the first time. - Old Runners and old saved state: the proof only reads the Runner state fields that released Runners already write. A state with a fence or a provider cleanup fence is not restarted. - The normal path has no added waits or file reads. The Runner file is read only after a code-0 exit during startup. - This changes no Runner (Rust) code. No new Runner image is needed. > 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, in Claude Code with tool use (shell, file edits, test runs). Extended reasoning. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude --- .../paperclip-runner/docs/durable-recovery.md | 9 + ...rd-codex-transport-carried-suspend.test.ts | 160 ++++++++++++++++++ .../src/live/runnerd-codex-transport.ts | 96 ++++++++++- 3 files changed, 261 insertions(+), 4 deletions(-) create mode 100644 packages/paperclip-runner/src/live/runnerd-codex-transport-carried-suspend.test.ts diff --git a/packages/paperclip-runner/docs/durable-recovery.md b/packages/paperclip-runner/docs/durable-recovery.md index 040fb5748e2..9b43063fd5c 100644 --- a/packages/paperclip-runner/docs/durable-recovery.md +++ b/packages/paperclip-runner/docs/durable-recovery.md @@ -243,6 +243,15 @@ runner refused), and its acknowledgement names the runner's journal status runners accept only `indeterminate` and otherwise exit with "terminal command result acknowledgement changed its durable identity". +That runner exits before it accepts any command of the new attempt. During +startup, the controller restarts it in place once, so the attempt continues. +It does this only when the runner's durable journal proves the exit: its last +command is exactly the suspend that an earlier attempt journaled, the +controller has settled that suspend, the runner rests `suspended` with no +terminal or provider cleanup fence, and no command of this attempt has a +result. The runner file is read only after such an exit. Any other exit keeps +its earlier failure. + A kill during that attachment's provider launch can also leave a `spawned` startup fence over a `prepared` state that holds a saved thread. The next runner retires that fence once the recorded provider process and its group have exited, diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport-carried-suspend.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport-carried-suspend.test.ts new file mode 100644 index 00000000000..87cf56ba2e9 --- /dev/null +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport-carried-suspend.test.ts @@ -0,0 +1,160 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, it, vi } from "vitest"; +import { createCapabilityRunnerdCodexTransport, runnerdRecoveryInternals } from "./runnerd-codex-transport.js"; +import { defaultCapabilityRunnerdBinary, fakeCodex, fakeCodexArgs } from "../../test/support/runnerd-transport.js"; + +/** + * A server freeze while the controller suspends a finished turn can stop the + * runner inside `runner.suspend`: the runner journaled the command, its + * outcome is not recorded, and the controller still lists it as pending. The + * next same-run attempt starts a new runner. That runner settles the old + * suspend from the welcome (as `execution_indeterminate`; it never runs it + * again), records `suspended` and exits with code 0 before it accepts any of + * this attempt's commands. The attempt restarts the runner in place once, and + * the resume completes in the same attempt without another provider turn. + * + * `fenced` is the state a released build can leave: the controller already + * recorded the suspend as failed and the runner kept its terminal fence. The + * next runner reconciles that fence, keeps a provider cleanup fence and exits. + * That runner would refuse new work, so the attempt is not restarted in place: + * any exit without the exact proof keeps the earlier failure. + */ +it.each(["journaled", "fenced"] as const)("restarts in place only a runner that settled the previous attempt's suspend (%s)", async (mode) => { + const root = await mkdtemp(join(tmpdir(), "runnerd-carried-suspend-")); + const callsPath = join(root, "calls.log"); + const identity = { + runnerInstanceId: "carried-suspend-runner", + environmentLeaseId: "carried-suspend-lease", + runId: "carried-suspend-run", + normalizedSessionId: "carried-suspend-session", + turnId: "carried-suspend-turn", + itemId: "carried-suspend-item", + }; + const options = { + runnerBinary: defaultCapabilityRunnerdBinary(), + codexCommand: fakeCodex, + codexArgs: fakeCodexArgs(root, "--call-log", callsPath), + stateDirectory: root, + }; + const kill = (pid: number | null | undefined) => { + if (!pid) return; + try { process.kill(pid, "SIGKILL"); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; } + }; + const first = createCapabilityRunnerdCodexTransport({ ...options, prpIdentity: identity }); + let resumed: ReturnType | undefined; + try { + const opened = await first.transport.request("thread/start", { cwd: tmpdir(), dynamicTools: [] }); + const openedThread = opened.thread as { id: string; sessionId: string }; + const thread = { id: openedThread.id, sessionId: openedThread.sessionId }; + await first.transport.close(); + + // Rewrite both journals to the moment of the freeze: the runner journaled + // the suspend before its effect; the controller never saw its result. + const controlPath = join(root, "control-plane", "control-plane-state.json"); + const control = JSON.parse(await readFile(controlPath, "utf8")); + const suspend = control.commands.findLast((command: { type: string }) => command.type === "runner.suspend"); + expect(suspend).toMatchObject({ status: "completed" }); + expect(control.commands.at(-1).commandId).toBe(suspend.commandId); + const indeterminate = { code: "execution_indeterminate", message: "runner recovered after journaling this command; it will not execute twice" }; + Object.assign(suspend, mode === "journaled" ? { status: "pending", result: null } : { + status: "failed", + result: { commandId: suspend.commandId, controllerSeq: suspend.controllerSeq, commandType: "runner.suspend", + status: "failed", result: indeterminate }, + }); + await writeFile(controlPath, JSON.stringify(control)); + const runnerPath = join(root, "runner", "runner-state.json"); + const runner = JSON.parse(await readFile(runnerPath, "utf8")); + expect(runner.lastControllerCommandSeq).toBe(suspend.controllerSeq); + runner.processedCommands[suspend.commandId] = { + ...runner.processedCommands[suspend.commandId], + ...(mode === "journaled" + ? { status: "pending", result: { code: "execution_indeterminate", message: "command was journaled before its effect" } } + : { status: "indeterminate", result: indeterminate }), + }; + runner.lifecycle = mode === "journaled" ? "ready" : "suspended"; + runner.pendingTerminalDelivery = mode === "journaled" ? null : { + commandId: suspend.commandId, controllerSeq: suspend.controllerSeq, commandType: "runner.suspend", lifecycle: "suspended", + }; + await writeFile(runnerPath, JSON.stringify(runner)); + const callsBefore = (await readFile(callsPath, "utf8")).trim().split(/\r?\n/); + + resumed = createCapabilityRunnerdCodexTransport({ + ...options, + prpIdentity: identity, + resumeProviderSession: { driverSessionId: thread.id, providerSessionId: thread.sessionId }, + }); + if (mode === "fenced") { + await expect(resumed.transport.request("thread/read", {})).rejects.toThrow( + "runnerd exited unexpectedly with code 0", + ); + expect(resumed.evidence().diagnostics).not.toContain( + "runner settled a suspend left by an earlier attempt and exited; restarting it in place", + ); + return; + } + expect((await resumed.transport.request("thread/read", {})).thread).toMatchObject(thread); + expect(resumed.evidence().diagnostics).toContain( + "runner settled a suspend left by an earlier attempt and exited; restarting it in place", + ); + const recovered = JSON.parse(await readFile(controlPath, "utf8")); + expect(recovered.commands.find((command: { commandId: string }) => command.commandId === suspend.commandId)) + .toMatchObject({ status: "failed", result: { result: { code: "execution_indeterminate" } } }); + const calls = (await readFile(callsPath, "utf8")).trim().split(/\r?\n/).slice(callsBefore.length); + expect(calls.filter(call => call === "turn/start")).toHaveLength(0); + } finally { + await Promise.allSettled([first.transport.close(), resumed?.transport.close()]); + for (const bundle of [first, resumed]) { + const evidence = bundle?.evidence(); + kill(evidence?.runnerPid); + kill(evidence?.providerPid); + } + await vi.waitFor(() => undefined); + await rm(root, { recursive: true, force: true }); + } +}, 60_000); + +it("restarts only for the exact settled suspend left by an earlier attempt", () => { + const prove = runnerdRecoveryInternals.carriedSuspendSettlementProven; + const identity = { + runnerInstanceId: "runner", environmentLeaseId: "lease", runId: "run", + normalizedSessionId: "session", turnId: "turn", itemId: "item", + }; + const runnerState = (overrides: Record = {}) => ({ + schema: "paperclip.runner.durable.state.v1", ...identity, lifecycle: "suspended", + pendingTerminalDelivery: null, pendingProviderCleanup: null, lastControllerCommandSeq: 3, + processedCommands: { suspend: { commandId: "suspend", controllerSeq: 3, commandType: "runner.suspend", status: "indeterminate" } }, + ...overrides, + }); + const commands = (overrides: Record = {}, later: Record[] = []) => [ + { commandId: "prepare", controllerSeq: 1, type: "run.prepare", status: "completed" }, + { commandId: "turn", controllerSeq: 2, type: "turn.start", status: "completed" }, + { commandId: "suspend", controllerSeq: 3, type: "runner.suspend", status: "failed", ...overrides }, + { commandId: "probe", controllerSeq: 4, type: "runner.drain", status: "pending" }, + ...later, + ] as { commandId: string; controllerSeq: number; type: string; status: string }[]; + const proven = (state = runnerState(), journal = commands(), carriedCommandCount = 3) => + prove({ runnerState: state, identity, commands: journal, carriedCommandCount }); + + expect(proven()).toBe(true); + // This attempt queued the suspend, as a normal close does. + expect(proven(runnerState(), commands(), 2)).toBe(false); + // The controller has not settled it yet. + expect(proven(runnerState(), commands({ status: "pending" }))).toBe(false); + // The last command is not a suspend. + expect(proven(runnerState(), commands({ type: "runner.shutdown" }))).toBe(false); + // The runner went on to a command of this attempt. + expect(proven(runnerState({ lastControllerCommandSeq: 4 }))).toBe(false); + expect(proven(runnerState(), commands({}, []).map(command => + command.commandId === "probe" ? { ...command, status: "completed" } : command))).toBe(false); + // The runner did not rest cleanly suspended. + expect(proven(runnerState({ lifecycle: "ready" }))).toBe(false); + expect(proven(runnerState({ pendingTerminalDelivery: { commandId: "suspend" } }))).toBe(false); + expect(proven(runnerState({ pendingProviderCleanup: { commandId: "suspend" } }))).toBe(false); + // The runner's receipt names another command or another authority. + expect(proven(runnerState({ processedCommands: { suspend: { commandId: "suspend", controllerSeq: 3, + commandType: "runner.shutdown", status: "completed" } } }))).toBe(false); + expect(proven(runnerState({ processedCommands: {} }))).toBe(false); + expect(proven(runnerState({ runId: "other-run" }))).toBe(false); +}); diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index 15cb01e41f8..b5ce4030a0c 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -119,6 +119,8 @@ const RUNNER_CLIENT_VERSION = "0.3.0"; const RUNNER_BOOTSTRAP_TICKET_TTL_MS = 60_000; const RUNNER_RESTORE_STABLE_MS = 60_000; const MAX_UNSTABLE_RUNNER_RESTORES = 3; +// Bounds the one in-place restart after a runner settles an earlier attempt's suspend. +const CARRIED_SUSPEND_RESTART_GRACE_MS = 30_000; const RUNNERD_MAX_OUTBOX_BYTES = 16 * 1024 * 1024; const RUNNERD_P0_RESERVE_BYTES = 1024 * 1024; @@ -4052,6 +4054,11 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { readonly #failureSignal: Promise; #rejectFailureSignal!: (error: Error) => void; #runnerRecoveryInProgress = false; + /** Controller commands journaled before this attempt queued any. */ + #carriedCommandCount: number | null = null; + /** Each runner exit's carried-suspend classification, read once after exit. */ + readonly #carriedSuspendExits = new WeakMap>(); + #carriedSuspendRestartUsed = false; #lastRunnerRestoreAt: number | null = null; #unstableRunnerRestores = 0; #startupComplete = false; @@ -6081,6 +6088,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { connectionLeaseTtlMs: 60 * 60 * 1_000, }); this.#core = core; + this.#carriedCommandCount = core.store.state.commands.length; // Externally launched runners own their state directory (for example in a // Daytona sandbox). Do not create an empty controller-side placeholder: // prior-run authority checks must be able to distinguish absent remote @@ -6655,6 +6663,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { connectionLeaseTtlMs: 60 * 60 * 1_000, }); this.#core = core; + this.#carriedCommandCount = core.store.state.commands.length; // Reusing resources still requires current environment authorization. The // optional hook avoids re-preparation after controller storage is lost. // Existing consumers retain the preparation callback's authorization path. @@ -8402,8 +8411,16 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { async #runnerHasExited(): Promise { // A runnerd killed by a signal reports exitCode null and its signalCode. - if (this.#handle) return this.#handle.isExitConfirmed?.() - ?? (this.#handle.child.exitCode !== null || (this.#handle.child.signalCode ?? null) !== null); + if (this.#handle) { + const handle = this.#handle; + const exited = handle.isExitConfirmed?.() + ?? (handle.child.exitCode !== null || (handle.child.signalCode ?? null) !== null); + // A runner that only settled a suspend left by an earlier attempt is + // being restarted in place; startup keeps waiting for its replacement. + if (exited && !this.#startupComplete && await this.#carriedSuspendExits.get(handle)) + return this.#closed || this.#failure !== null; + return exited; + } const adoptedRunner = this.options.adoptExistingRunner; if (!adoptedRunner) return true; return !(await adoptedRunner.isAlive()); @@ -8481,8 +8498,13 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { } #watchRunner(handle: RunnerProcessHandle): void { + const carriedSuspendExit = handle.completion.then( + (result) => this.#settledOnlyCarriedSuspend(handle, result.code), + () => false, + ); + this.#carriedSuspendExits.set(handle, carriedSuspendExit); void handle.completion.then( - (result) => { + async (result) => { const exitConfirmed = handle.isExitConfirmed?.() ?? true; this.#evidence.runnerExited = exitConfirmed; this.#evidence.runnerExitCode = result.code; @@ -8498,6 +8520,14 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { this.#lostRunnerHandle = handle; if (this.#closed || this.#failure !== null || this.#handle !== handle || (this.#releaseEpisode && !this.#releaseEpisode.claimed)) return; + if (await carriedSuspendExit) { + if (this.#closed || this.#failure !== null || this.#handle !== handle) return; + this.#carriedSuspendRestartUsed = true; + this.#diagnostic("runner settled a suspend left by an earlier attempt and exited; restarting it in place"); + void this.#recoverRunnerProcess(handle, detail, CARRIED_SUSPEND_RESTART_GRACE_MS); + return; + } + if (this.#closed || this.#failure !== null || this.#handle !== handle) return; // A per-turn runner exits after its terminal suffix is durably ACKed. // Drain that suffix into the provider-facing queue before classifying // process completion; clean terminal exit is the expected lifecycle. @@ -8567,6 +8597,37 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { ); } + /** + * A freeze or restart during `runner.suspend` leaves that command pending in + * the controller journal. The next attempt's runner settles it from the + * welcome and exits as suspended before it accepts this attempt's work. Only + * that exit is restarted in place, once, and only when the durable runner + * journal proves it: the runner's last command is exactly that earlier + * suspend, settled by the controller, and the runner rests suspended with no + * fence. It then executed nothing this attempt queued, so no turn started and + * no provider work can repeat. The runner file is read only after an exit. + */ + async #settledOnlyCarriedSuspend(handle: RunnerProcessHandle, code: number | null): Promise { + const core = this.#core; + const carried = this.#carriedCommandCount; + if (code !== 0 || handle.isExitConfirmed?.() === false || !handle.restart || core === null || carried === null + || this.#carriedSuspendRestartUsed || this.#startupComplete || this.#closed || this.#failure !== null + || this.options.adoptExistingRunner || this.options.runnerProcessLauncher || this.options.readRunnerState + || this.options.runnerStateDirectory !== undefined) return false; + let state: Record; + try { + state = await this.#readDurableRunnerState(); + } catch { + return false; + } + return carriedSuspendSettlementProven({ + runnerState: state, + identity: core.store.state.identity, + commands: core.store.state.commands, + carriedCommandCount: carried, + }); + } + #recoverOrFailRunnerProcess(handle: RunnerProcessHandle, detail: string): void { this.#unstableRunnerRestores = unstableRunnerRestoreCount( this.#unstableRunnerRestores, @@ -8587,6 +8648,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { async #recoverRunnerProcess( failedHandle: RunnerProcessHandle, initialDetail: string, + graceOverrideMs?: number, ): Promise { if ( this.#runnerRecoveryInProgress || @@ -8598,7 +8660,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { ) return; this.#runnerRecoveryInProgress = true; - const graceMs = this.options.runnerReconnectGraceMs ?? 0; + const graceMs = graceOverrideMs ?? this.options.runnerReconnectGraceMs ?? 0; const deadline = Date.now() + graceMs; const delays = [250, 500, 1_000, 2_000, 5_000] as const; let attempt = 0; @@ -9118,7 +9180,33 @@ function unstableRunnerRestoreCount(previous: number, restoredAt: number | null, return restoredAt !== null && now - restoredAt < RUNNER_RESTORE_STABLE_MS ? previous + 1 : 0; } +/** The durable proof that a runner's clean exit only settled a suspend that an + * earlier attempt journaled: its last command is exactly that suspend, which + * the controller has settled; it rests suspended with no fence; and nothing + * this attempt queued has a result, so no turn or provider work ran. */ +function carriedSuspendSettlementProven(input: { + runnerState: Record; + identity: DurableRecoveryIdentity; + commands: readonly { commandId: string; controllerSeq: number; type: string; status: string }[]; + carriedCommandCount: number; +}): boolean { + const { runnerState: state, commands, carriedCommandCount: carried } = input; + const seq = state.lastControllerCommandSeq; + if (state.schema !== "paperclip.runner.durable.state.v1" + || !recoveryIdentityMatches(state, input.identity) + || state.lifecycle !== "suspended" || state.pendingTerminalDelivery != null + || state.pendingProviderCleanup != null || state.warmTransition != null + || typeof seq !== "number" || !Number.isSafeInteger(seq) || seq < 1 || seq > carried) return false; + const suspend = commands.find((command) => command.controllerSeq === seq); + if (suspend?.type !== "runner.suspend" || suspend.status === "pending") return false; + if (commands.some((command) => command.controllerSeq > carried && command.status !== "pending")) return false; + const processed = record(record(state.processedCommands)[suspend.commandId]); + return processed.commandId === suspend.commandId && processed.commandType === "runner.suspend" + && processed.controllerSeq === seq && processed.status !== "pending"; +} + export const runnerdRecoveryInternals = Object.freeze({ + carriedSuspendSettlementProven, unstableRunnerRestoreCount, projectCopilotRunGrant, completedMaintenanceTerminalReceipt, From fcf4e39b41df0b871c1391566f911b39b8af1b71 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:25:32 -0600 Subject: [PATCH 34/38] fix(runner): do not count stopped time against a turn start or an ACPX sidecar request (#20720) 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 > - A native run starts each provider turn with `turn.start`. The control plane waits for the Runner, and an ACPX Runner waits for its sidecar, which starts the provider and sends the prompt. > - Both waits use a 30 s bound. When the host or container stops the whole tree (SIGSTOP, a host sleep), the clocks keep moving while no process can act. > - On thaw both bounds have passed. The control plane reports `PRP command turn.start timed out`, and the Runner fails the sidecar request and closes the ACPX session. > - #20704 added a stopped-time clock for startup and recovery. This pull request puts `turn.start` and its follow-up waits on the same clock, and adds the same rule to the Runner's sidecar response wait. > - The benefit is that a freeze during a turn start no longer fails the turn or closes the session. ## Linked Issues or Issue Description **What happened?** Restart-chaos wave `w-20261111T011704-s9107`, task t05 (local, claude, workload C1, fault TM2). A follow-up run sent `turn.start` at 01:22:21. The harness then stopped the server, Runner, sidecar and Claude twice: 28 s, then 33 s after a 1 s thaw. At 01:23:25 the control plane reported `provider_transport_failed: PRP command turn.start timed out`. Three same-run resumes then failed with `ACPX session is not open`, recovery stopped with `native_session_retry_exhausted`, and the task needed a manual Retry. The Retry run succeeded. **Expected behavior** Time that the processes spend stopped does not count against the turn-start bound or the sidecar request bound. A real timeout still fires while the processes run. **Steps to reproduce** 1. `cd packages/paperclip-runner && npx vitest run src/live/runnerd-codex-transport-stall.test.ts`. On master it fails with `provider_transport_failed: PRP command turn.start timed out`. 2. `cargo test --manifest-path packages/paperclip-runner/runner/Cargo.toml -p paperclip-runner-core --test acpx_sidecar_stopped_time`. On master it fails with `ACPX sidecar request timed out at initialize`. It stops the process early in the wait and again in its last half second. Note on the repeated `ACPX session is not open`: the wave ran `eafd5853d9`, which does not contain #20675. On master, #20675 settles a cut-off start from the sidecar's dispatch journal. If the prompt never left, the Runner reopens the session and sends it once. If the journal shows the prompt left, or cannot prove it, the session stays closed and the run ends with a working Retry, as the class rule requires. This pull request stops the freeze from cutting off the start in the first place. Refs #20704, #20675 ## What Changed - `packages/paperclip-runner/src/live/runnerd-codex-transport.ts`: `#startTurn` runs under `#withAdmissionClock`. The turn-start deadline, the held-tool-call wait, the start-event wait, the adoption check time and the `session.snapshot` wait all read `#waitNow()`, so they share one stopped-time credit. - `packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs`: `receive_response` blocks in 1 s slices. `credit_stopped_time` treats a slice overshoot beyond 2 s as a stop. It moves the deadline by the overshoot, and to at least 5 s after the thaw, so a stop in the last slice still leaves the sidecar time to answer. Total credit per request is capped at 15 min. - The control-plane clock (`RunnerStallLedger`) now uses the same rule: a stop is credited in full plus a 5 s grace, capped at 15 min per admission. - `packages/paperclip-runner/src/live/runnerd-codex-transport-stall.test.ts` (new): drives the real transport and Runner. It SIGSTOPs the Runner tree, jumps `Date.now` by 40 s mid-wait, then resumes the Runner. It fails if the turn start leaves the clock, or if the command wait stops reading it (checked by removing `clock: this.#admissionClock`). This is the transport-level test requested in the #20704 review. - `packages/paperclip-runner/runner/crates/runner-core/tests/acpx_sidecar_stopped_time.rs` (new, its own test binary): a sidecar stops the test process for 6 s against a 3 s bound and answers after the thaw. - Unit test for `credit_stopped_time`. ## Verification - Red on master, green here: both commands in "Steps to reproduce". - `npx vitest run src/live/runnerd-codex-transport.test.ts src/live/runnerd-codex-transport-stall.test.ts src/live/runnerd-acpx-source-reconciliation.test.ts src/live/runnerd-codex-transport-adoption.test.ts`: 342/342 pass. - `cargo test -p paperclip-runner-core --lib acpx_sidecar_transport` (12 pass), `--test acpx_sidecar_transport --test acpx_park_preparation --test acpx_provider_turns` (all pass), `cargo fmt --check` clean. - `npx tsc --noEmit -p tsconfig.json` and `-p tsconfig.test.json`: clean. - Not run: a new chaos wave. ## Risks - A real stall longer than 2 s in the Runner (or 5 s in the control plane) during a turn start or a sidecar request now extends that wait by the stall plus 5 s. The waited-on process could not be observed during the stall either. The 15 min cap bounds a process that keeps stalling. - The Rust wait now wakes once per second while it waits for a sidecar reply. This is an active request with no I/O per wake. - The 1 s control-plane ticker from #20704 now also runs during a turn start, and stops when the start returns. - No persisted state, launch identity or saved-session shape changes. Old saved runs resume through the same code, and an older Runner keeps its old wait. Nothing new runs before `turn.start`, and no wait is added on the normal path. > 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 (Anthropic), model ID `claude-opus-5-5`, run in Claude Code with tool use (shell, file edit) and extended reasoning. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- .../runner-core/src/acpx_sidecar_transport.rs | 114 +++++++++++++++++- .../tests/acpx_sidecar_stopped_time.rs | 55 +++++++++ .../runnerd-codex-transport-stall.test.ts | 55 +++++++++ .../src/live/runnerd-codex-transport.test.ts | 32 ++++- .../src/live/runnerd-codex-transport.ts | 50 +++++--- 5 files changed, 279 insertions(+), 27 deletions(-) create mode 100644 packages/paperclip-runner/runner/crates/runner-core/tests/acpx_sidecar_stopped_time.rs create mode 100644 packages/paperclip-runner/src/live/runnerd-codex-transport-stall.test.ts diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs index fc2ff4f575f..6ed53c42917 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs @@ -21,6 +21,46 @@ pub const ACPX_SIDECAR_MAX_FRAME_BYTES: usize = 1024 * 1024; const MAX_BUFFERED_EVENTS: usize = 512; const MAX_EVENT_POLL_TIMEOUT: Duration = Duration::from_secs(120); const MAX_JSON_SAFE_INTEGER: u64 = 9_007_199_254_740_991; +/// A response wait blocks in slices of at most this long. +const RESPONSE_WAIT_SLICE: Duration = Duration::from_secs(1); +/// A slice that returns this much later than it asked was not waiting: this +/// process was stopped (SIGSTOP, a frozen container, a whole-process stall). +const STOPPED_TIME_THRESHOLD: Duration = Duration::from_secs(2); +/// After a stop, the thawed sidecar keeps at least this long to answer. +const POST_STOP_GRACE: Duration = Duration::from_secs(5); +/// One request never credits more stopped time than this in total. +const MAX_STOPPED_CREDIT: Duration = Duration::from_secs(15 * 60); + +/// Moves `deadline` later after a wait slice that this process spent stopped. +/// +/// The sidecar is a child of this process and is normally stopped with it, so +/// it could not answer either. Without this, a thaw found the deadline already +/// past and failed the request before either process ran (chaos t05: a 61 s +/// freeze failed a turn start against its 30 s bound). The slice overshoot is +/// credited, and the deadline is at least `POST_STOP_GRACE` after the thaw, so +/// a stop in the last slice still leaves the sidecar time to answer. Total +/// credit is capped, so a process that never runs normally still times out. +/// `credited` carries the request's total credit between slices. +pub(crate) fn credit_stopped_time( + deadline: Instant, + slice: Duration, + slice_ended: Instant, + elapsed: Duration, + credited: &mut Duration, +) -> Instant { + let Some(stopped) = elapsed.checked_sub(slice) else { + return deadline; + }; + if stopped <= STOPPED_TIME_THRESHOLD || *credited >= MAX_STOPPED_CREDIT { + return deadline; + } + let extended = (deadline + stopped).max(slice_ended + POST_STOP_GRACE); + let credit = extended + .saturating_duration_since(deadline) + .min(MAX_STOPPED_CREDIT - *credited); + *credited += credit; + deadline + credit +} #[derive(Clone, Debug)] pub struct AcpxSidecarTransportConfig { @@ -710,13 +750,26 @@ impl AcpxSidecarTransport { request_id: u64, deadline: Instant, ) -> Result, LocalRunnerError> { + let mut deadline = deadline; + let mut credited = Duration::ZERO; loop { - let remaining = deadline.saturating_duration_since(Instant::now()); + let slice_started = Instant::now(); + let remaining = deadline.saturating_duration_since(slice_started); if remaining.is_zero() { return Ok(None); } - let Some(line) = self.receive_stdout_line(remaining, command.as_str())? else { - return Ok(None); + let slice = remaining.min(RESPONSE_WAIT_SLICE); + let received = self.receive_stdout_line(slice, command.as_str())?; + let slice_ended = Instant::now(); + deadline = credit_stopped_time( + deadline, + slice, + slice_ended, + slice_ended.saturating_duration_since(slice_started), + &mut credited, + ); + let Some(line) = received else { + continue; }; match parse_frame(&line)? { ParsedFrame::Event(event) => self.buffer_event(event)?, @@ -1287,6 +1340,61 @@ fn response_error_classification(error: &ResponseError) -> &'static str { #[cfg(test)] mod tests { + #[test] + fn credits_a_stop_and_leaves_the_sidecar_time_to_answer() { + let start = Instant::now(); + let deadline = start + Duration::from_secs(30); + let slice = Duration::from_secs(1); + let mut credited = Duration::ZERO; + // A slice that returned on time, or a little late on a loaded host. + for elapsed in [Duration::from_millis(400), Duration::from_millis(2_900)] { + assert_eq!( + credit_stopped_time(deadline, slice, start + elapsed, elapsed, &mut credited), + deadline + ); + } + assert_eq!(credited, Duration::ZERO); + // A 61 s freeze inside a 1 s slice early in the wait: 60 s are credited. + let ended = start + Duration::from_secs(61); + assert_eq!( + credit_stopped_time( + deadline, + slice, + ended, + Duration::from_secs(61), + &mut credited + ), + deadline + Duration::from_secs(60) + ); + // A freeze in the last 0.5 s slice still leaves the grace after thaw. + let mut credited = Duration::ZERO; + let last = start + Duration::from_millis(29_500); + let half = Duration::from_millis(500); + let ended = last + Duration::from_secs(60); + assert_eq!( + credit_stopped_time( + deadline, + half, + ended, + Duration::from_secs(60), + &mut credited + ), + ended + POST_STOP_GRACE + ); + // Total credit is capped. + let mut credited = MAX_STOPPED_CREDIT; + assert_eq!( + credit_stopped_time( + deadline, + slice, + ended, + Duration::from_secs(61), + &mut credited + ), + deadline + ); + } + #[test] #[cfg(unix)] fn a_timed_out_turn_start_never_establishes_a_resumable_rejection() { diff --git a/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_sidecar_stopped_time.rs b/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_sidecar_stopped_time.rs new file mode 100644 index 00000000000..039cf654d64 --- /dev/null +++ b/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_sidecar_stopped_time.rs @@ -0,0 +1,55 @@ +//! Runs alone in its own test binary: it stops this whole test process. +#![cfg(unix)] + +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use paperclip_runner_core::acpx_sidecar_transport::{ + AcpxSidecarTransport, AcpxSidecarTransportConfig, +}; +use paperclip_runner_core::generated_acpx_sidecar_contract::{ + GeneratedAcpxSidecarCommand, GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION, +}; +use serde_json::json; + +/// Chaos w-20261111T011704-s9107/t05: the Runner and its ACPX sidecar were +/// stopped together (SIGSTOP, a host-sleep stand-in) past the sidecar request +/// bound. On thaw the bound had already passed, so the Runner failed the turn +/// start before the sidecar could answer. Here the sidecar stops this process +/// for 6 s against a 3 s bound and answers 0.5 s after the thaw: once early in +/// the wait, and once in its last half second. Both cases share one test so +/// no other test thread runs while this process is stopped. +#[test] +fn a_request_answered_after_this_process_was_stopped_past_its_bound_succeeds() { + for stop_after in ["0", "2.5"] { + answered_after_stop(stop_after); + } +} + +fn answered_after_stop(stop_after: &str) { + let response = json!({ + "protocolVersion": GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION, + "id": 1, "ok": true, "result": { "answered": true }, + }); + let runner = std::process::id(); + let script = format!( + "IFS= read -r request; sleep {stop_after}; \ + (sleep 6; kill -CONT {runner}; sleep 0.5; printf '%s\\n' '{response}') & \ + kill -STOP {runner}; wait; IFS= read -r next" + ); + let mut transport = AcpxSidecarTransport::start(&AcpxSidecarTransportConfig { + command: PathBuf::from("/bin/sh"), + args: vec!["-c".to_owned(), script], + verified_launch: None, + request_timeout: Duration::from_secs(3), + shutdown_grace: Duration::from_millis(100), + }) + .expect("sidecar should start"); + let started = Instant::now(); + let result = transport + .request(GeneratedAcpxSidecarCommand::Initialize, json!({})) + .expect("stopped time must not count against the request bound"); + assert_eq!(result["answered"], true); + assert!(started.elapsed() >= Duration::from_secs(6)); + transport.shutdown().expect("sidecar should stop"); +} diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport-stall.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport-stall.test.ts new file mode 100644 index 00000000000..7489002b66a --- /dev/null +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport-stall.test.ts @@ -0,0 +1,55 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, it, vi } from "vitest"; +import { createCapabilityRunnerdCodexTransport } from "./runnerd-codex-transport.js"; +import { defaultCapabilityRunnerdBinary, fakeCodex, fakeCodexArgs } from "../../test/support/runnerd-transport.js"; + +const signalGroup = (pid: number, signal: NodeJS.Signals) => { + try { process.kill(-pid, signal); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; } +}; + +// Chaos w-20261111T011704-s9107/t05: the control plane and its Runner tree were +// stopped (SIGSTOP, a host-sleep stand-in) for 61 s while turn.start waited on its +// 30 s deadline. On thaw the wall clock had passed the deadline before either +// process could act, and the run reported "PRP command turn.start timed out". +// This drives the real transport and Runner: it fails if turn start does not run +// on the stopped-time clock, or if its waits do not read that clock. +it("starts a turn whose Runner and control plane were stopped past the turn-start deadline", async () => { + const root = await mkdtemp(join(tmpdir(), "runnerd-turn-start-stall-")); + const bundle = createCapabilityRunnerdCodexTransport({ + runnerBinary: defaultCapabilityRunnerdBinary(), + codexCommand: fakeCodex, + codexArgs: fakeCodexArgs(root), + stateDirectory: root, + turnStartTimeoutMs: 30_000, + prpIdentity: { + runnerInstanceId: "stall-runner", environmentLeaseId: "stall-lease", runId: "stall-run", + normalizedSessionId: "stall-session", turnId: "stall-turn", itemId: "stall-item", + }, + }); + const realNow = Date.now.bind(Date); + let stoppedMs = 0; + let runnerPid: number | null = null; + try { + await bundle.transport.request("thread/start", { cwd: tmpdir(), dynamicTools: [] }); + runnerPid = bundle.evidence().runnerPid; + expect(runnerPid).toEqual(expect.any(Number)); + // Stop the Runner tree, then let this process "sleep" 40 s: the wall clock + // jumps while no timer of this process runs. + signalGroup(runnerPid!, "SIGSTOP"); + vi.spyOn(Date, "now").mockImplementation(() => realNow() + stoppedMs); + const started = bundle.transport.request("turn/start", { input: [{ type: "text", text: "Continue after the freeze." }] }); + await new Promise(resolve => setTimeout(resolve, 300)); + stoppedMs = 40_000; + await new Promise(resolve => setTimeout(resolve, 300)); + signalGroup(runnerPid!, "SIGCONT"); + await expect(started).resolves.toMatchObject({ turn: { status: "inProgress" } }); + } finally { + vi.restoreAllMocks(); + if (runnerPid !== null) signalGroup(runnerPid, "SIGCONT"); + await bundle.transport.close().catch(() => undefined); + if (runnerPid !== null) signalGroup(runnerPid, "SIGKILL"); + await rm(root, { recursive: true, force: true }); + } +}, 30_000); diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts index ab762e4d317..49fa481f4eb 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts @@ -4,7 +4,7 @@ import { runnerLaunchRequirementsDigest, type RunnerProviderLaunchRequirements, } from "./runner-provider-launch.js"; -import { coldAdmissionTimeoutMs, RUNNER_STALL_THRESHOLD_MS, RunnerStallLedger, waitForRunnerCommand } from "./runnerd-codex-transport.js"; +import { coldAdmissionTimeoutMs, RUNNER_MAX_STOPPED_CREDIT_MS, RUNNER_POST_STOP_GRACE_MS, RunnerStallLedger, waitForRunnerCommand } from "./runnerd-codex-transport.js"; import { configuredEnvironmentProjection } from "../configured-environment.js"; import { chmod, cp, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, stat, truncate, writeFile } from "node:fs/promises"; import { createHash } from "node:crypto"; @@ -6753,13 +6753,29 @@ describe("admission waits do not count time this process was stopped", () => { const rejection = expect(drain).rejects.toThrow("runner_local_connect_failed: PRP command runner.drain timed out"); await vi.advanceTimersByTimeAsync(1_000); vi.setSystemTime(Date.now() + 44_000); - // Running time reaches the deadline: 1 s before, the uncredited 5 s of the - // gap, then the rest of the 30 s budget. - await vi.advanceTimersByTimeAsync(30_000); + // Running time reaches the deadline: 1 s before, then the rest of the + // 30 s budget plus the 5 s post-stop grace. + await vi.advanceTimersByTimeAsync(40_000); await rejection; } finally { stop(); vi.useRealTimers(); } }); + it("leaves the Runner time to answer after a freeze in a wait's last half second", async () => { + vi.useFakeTimers(); + const clock = new RunnerStallLedger(); + const stop = clock.watch(); + try { + let status = "pending"; + const drain = pending(clock, clock.now() + 30_000, () => status); + await vi.advanceTimersByTimeAsync(29_500); + vi.setSystemTime(Date.now() + 60_000); + await vi.advanceTimersByTimeAsync(2_000); + status = "completed"; + await vi.advanceTimersByTimeAsync(10); + await expect(drain).resolves.toBeUndefined(); + } finally { stop(); vi.useRealTimers(); } + }); + it("credits a freeze outside any poll loop to the next barrier on the same deadline", async () => { vi.useFakeTimers(); const clock = new RunnerStallLedger(); @@ -6793,11 +6809,15 @@ describe("admission waits do not count time this process was stopped", () => { expect(wall).toBeGreaterThanOrEqual(30_000); expect(wall).toBeLessThan(35_000); expect(clock.creditedMs).toBe(0); - // A 6 s gap is credited only beyond the stall threshold, and only once. + // A 6 s gap is a stop: credited in full plus the post-stop grace, and only once. wall += 6_000; clock.now(); clock.now(); - expect(clock.creditedMs).toBe(6_000 - RUNNER_STALL_THRESHOLD_MS); + expect(clock.creditedMs).toBe(6_000 + RUNNER_POST_STOP_GRACE_MS); + // Total credit is capped, so a process that never runs normally still times out. + wall += 2 * RUNNER_MAX_STOPPED_CREDIT_MS; + clock.now(); + expect(clock.creditedMs).toBe(RUNNER_MAX_STOPPED_CREDIT_MS); // A wall-clock grace taken now moves onto the clock without the earlier // credit, so it keeps exactly its own running-time budget. const wallGrace = wall + 5_000; diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index b5ce4030a0c..e3e972a6a05 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -4071,7 +4071,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { #nextTraceDebugSequence = 1; #traceRehydrationSpoolOverflow = false; readonly #traceFrameIndex = new RunnerdTraceFrameIndex(); - /** Clock of the startup or recovery admission in progress, if any. */ + /** Clock of the startup, recovery, or turn-start admission in progress, if any. */ #admissionClock: RunnerStallLedger | null = null; #startupSteps: { begin(name: RunnerdStartupStep["name"]): void; @@ -6234,10 +6234,11 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { } /** - * One stopped-time clock per admission; a nested startup keeps the outer one. - * It covers the Runner command barriers and the provider-identity wait. The - * warm-transition and source-attachment reconnect polls keep their own - * wall-clock grace deadlines. + * One stopped-time clock per admission (startup, recovery, or a turn start); + * a nested admission keeps the outer one. It covers the Runner command + * barriers, the provider-identity wait, and turn.start with its start-event + * and snapshot waits. The warm-transition and source-attachment reconnect + * polls keep their own wall-clock grace deadlines. */ async #withAdmissionClock(work: () => Promise): Promise { if (this.#admissionClock !== null) return work(); @@ -6252,7 +6253,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { } } - /** Wall time, or the admission clock while a startup or recovery runs. */ + /** Wall time, or the admission clock while a startup, recovery, or turn start runs. */ #waitNow(): number { return this.#admissionClock?.now() ?? Date.now(); } @@ -7348,7 +7349,11 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { async #startTurn( params: Record, ): Promise> { - return this.options.measureOperation ? this.options.measureOperation("runner.transport.turn_start", () => this.#startTurnWork(params), {inputBytes:Buffer.byteLength(JSON.stringify(params)), tokenDataAvailable:false}) : this.#startTurnWork(params); + // turn.start and its start-event and snapshot waits share one deadline, so + // they share one stopped-time clock (chaos t05: a 61 s freeze failed a + // 30 s turn.start before the Runner or its sidecar could answer). + const work = () => this.#withAdmissionClock(() => this.#startTurnWork(params)); + return this.options.measureOperation ? this.options.measureOperation("runner.transport.turn_start", work, {inputBytes:Buffer.byteLength(JSON.stringify(params)), tokenDataAvailable:false}) : work(); } /** @@ -7390,14 +7395,14 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { if (!Number.isSafeInteger(turnStartTimeoutMs) || turnStartTimeoutMs <= 0) { throw new Error("turnStartTimeoutMs must be a positive safe integer"); } - let commandDeadline = Date.now() + turnStartTimeoutMs; + let commandDeadline = this.#waitNow() + turnStartTimeoutMs; const heldCalls = this.#core; if (typeof heldCalls?.semanticToolResultsSettled === "function" && !heldCalls.semanticToolResultsSettled()) { let recovering = true; void Promise.resolve(heldCalls.recoverPendingSemanticInputs()) .catch(error => this.#failTransport(error instanceof Error ? error : new Error(String(error)))) .finally(() => { recovering = false; }); - while (recovering && Date.now() < commandDeadline) { + while (recovering && this.#waitNow() < commandDeadline) { this.#assertStartupOpen(); this.#throwIfFailed(); await new Promise((resolveWait) => setTimeout(resolveWait, 10)); @@ -7405,7 +7410,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { this.#assertStartupOpen(); this.#throwIfFailed(); if (recovering) throw new Error("native_turn_start_held_tool_calls_unresolved: recovering an earlier turn's held Paperclip tool calls did not finish before the turn-start deadline"); - commandDeadline = Date.now() + turnStartTimeoutMs; + commandDeadline = this.#waitNow() + turnStartTimeoutMs; } const compactionTurn = params[COMPACTION_TURN] === true; const compactionPayload = compactionTurn ? runnerdCompactionTurnPayload(this.options.provider ?? "codex") : null; @@ -7507,7 +7512,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { // Codex and OpenCode return their provider-assigned identity. const deadline = this.options.turnStartTimeoutMs === undefined - ? Date.now() + 30_000 + ? this.#waitNow() + 30_000 : commandDeadline; const providerTurnStarted = () => turnStartResponseReady({ @@ -7520,7 +7525,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { // the start event early enough to read the runner's snapshot before it. const adoptionCheckAt = deadline - Math.min( TURN_START_ADOPTION_CHECK_RESERVE_MS, - Math.floor(Math.max(0, deadline - Date.now()) / 4), + Math.floor(Math.max(0, deadline - this.#waitNow()) / 4), ); // The runner can end the accepted turn before it starts. Its terminal is // held for the pending start, so report that real cause at once. @@ -7535,7 +7540,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { throw new Error(`runnerd failed the provider turn before it started: ${failure}`); }; const waitForStarted = async () => { - while (!providerTurnStarted() && Date.now() < adoptionCheckAt) { + while (!providerTurnStarted() && this.#waitNow() < adoptionCheckAt) { this.#throwIfFailed(); this.#pumpEvents(); if (providerTurnStarted()) break; @@ -7576,7 +7581,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { } // Not provably live: keep the original contract and wait for the // start event until the configured bound, then fail as before. - while (!providerTurnStarted() && Date.now() < deadline) { + while (!providerTurnStarted() && this.#waitNow() < deadline) { this.#throwIfFailed(); this.#pumpEvents(); if (providerTurnStarted()) break; @@ -9295,6 +9300,10 @@ function closedAcpxRejection(message: unknown): string | null { */ export const RUNNER_STALL_THRESHOLD_MS = 5_000; const RUNNER_STALL_TICK_MS = 1_000; +/** After a stop, the thawed Runner keeps at least this long to answer. */ +export const RUNNER_POST_STOP_GRACE_MS = 5_000; +/** One admission never credits more stopped time than this in total. */ +export const RUNNER_MAX_STOPPED_CREDIT_MS = 15 * 60_000; /** * The clock for one startup or recovery admission. Time this process spends @@ -9307,9 +9316,11 @@ const RUNNER_STALL_TICK_MS = 1_000; * `now()` is wall time minus the stopped time observed since the ledger * started. Poll loops and a 1 s ticker share one last-observation time, so a * stop is credited once, wherever the process was when it stopped (a poll - * loop, a checkpoint flush, a spawn). Only the part of a gap beyond the - * threshold is credited, so a slow but running process still reaches its - * deadlines. Deadlines compared with `now()` must be taken from `now()`. + * loop, a checkpoint flush, a spawn). A stop is credited in full plus a + * grace, so a stop near a deadline still leaves the Runner time to answer + * after the thaw. Gaps below the threshold are running time, and total credit + * is capped, so a slow process still reaches its deadlines. Deadlines + * compared with `now()` must be taken from `now()`. */ export class RunnerStallLedger { #creditedMs = 0; @@ -9324,7 +9335,10 @@ export class RunnerStallLedger { now(): number { const at = this.wallNow(); - if (at - this.#last > RUNNER_STALL_THRESHOLD_MS) this.#creditedMs += at - this.#last - RUNNER_STALL_THRESHOLD_MS; + if (at - this.#last > RUNNER_STALL_THRESHOLD_MS) { + this.#creditedMs = Math.min(RUNNER_MAX_STOPPED_CREDIT_MS, + this.#creditedMs + at - this.#last + RUNNER_POST_STOP_GRACE_MS); + } this.#last = Math.max(this.#last, at); return at - this.#creditedMs; } From 16024ffa2aff449f2441fee7ffe9b57c899e3515 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:55:10 -0600 Subject: [PATCH 35/38] fix(native): a same-boot stall never leaves a run waiting on itself (#20721) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Native runs keep an execution lease. Restart recovery takes over a run only when it can prove that the recorded controller stopped. > - A stall (SIGSTOP) longer than the lease, with no restart, makes the executor lose its own lease. The executor then detaches for "the next controller" and exits. > - The next controller is this same process. Recovery asks the PID probe if the recorded controller is alive. The recorded controller is this process, so the answer is always "alive". > - The task then waits forever: `in_progress`, no Retry, an active run, and an active environment lease. > - A second gap: after back-to-back stalls mid-tool, the executor returns and nothing in this process ever looks at the run again. No terminal state, no recovery and no Retry. > - This pull request lets recovery recognise its own process. When this process no longer drives the run and its own lease lapsed, the prior owner is gone. The existing evidence checks then decide, as for any stopped controller. > - It also makes heartbeat schedule that recovery as soon as such an executor exits. > - The benefit is that a same-boot stall never needs a manual Retry. When provider work may have started, the run fails with a working Retry instead of a wait with no end. ## Linked Issues or Issue Description Refs #20694 (the same class of fix for legacy `preparing` runs), #20529, #20691. **What happened?** Chaos wave `w-20261111T034105-s9330`, task t02 (Daytona, OpenCode, fault TM1). The server process was frozen with SIGSTOP for about 84 s while run `89a3922b` prepared. After SIGCONT, `native.process_start_requested` was recorded and `native.session.execute` failed after 118 ms: the lease renewal found the lease lapsed, and the executor detached and exited. From then on, recovery recorded `native.recovery.transition` "waiting for safe ownership evidence" with reason `controller_still_alive` every 30 s for more than 20 minutes. The run stayed `running`, the issue stayed `in_progress`, no Retry was shown, and the environment lease stayed `active`. Chaos wave `w-20261111T040439-s9331` (Daytona, codex/claude/opencode, T1, TM1). Three stalls of about 90 s came back to back, with less than 1 s between them. Each run was in a tool call. After the second thaw, `native.session.execute` failed for all three runs (lease lost, executor detached). After that, no run had any event: no terminal state, no `native.recovery.transition` and no Retry, for 20 minutes. The in-sandbox turns kept going. A single 90 s stall (wave s9340) stays green, because a later recovery signal happens to find the run. With stacked stalls, that signal can land while the executor is still tearing down, so it skips the run and sets no deadline. **Expected behavior** When this process no longer drives a run that it recorded as its own, recovery takes the run back. No turn reached the runner here, so the bootstrap restarts on the same run. When a turn or runner work may have started, the run fails and shows a working Retry. **Steps to reproduce** 1. Start a native remote (Daytona) run. 2. Send SIGSTOP to the server during preparation, and hold it longer than the execution lease. 3. Send SIGCONT. The executor loses its lease, detaches and exits. 4. See that every recovery scan waits with `controller_still_alive`, and the run never settles. The new tests in `native-runner-restart-recovery.integration.test.ts` ("same-boot controller whose own lease lapsed") reproduce this at the recovery layer. ## What Changed - `claimNativeRestartRecoveries`: when the recorded controller is this exact process (same boot ID and PID): - If this process still drives the run (heartbeat execution or native executor registered), recovery leaves the run to it (`current_controller_preparing`). - If neither drives it and the self lease lapsed, the takeover is allowed (`current_controller_released`). The existing evidence checks then choose the outcome: bootstrap again on the same run when a durable record proves no command reached the runner, or fail with a Retry (`blocked`) when runner or provider work may have started. - An unexpired self lease still waits. A claim that has not reached its executor holds it, and it lapses by itself. - A run that this process handed to the next server (graceful drain `restart_suspended` record, or the in-process hot-restart handoff marker) stays with the next server. - `heartbeat.ts`: when the executor ends with `NativeControllerDetachedForRestartError`, there was no shutdown or hot-restart handoff, and this process's own lease lapsed (`ownNativeExecutionLeaseLapsed`), heartbeat schedules restart recovery for the run when the executor exits. Recovery then reattaches the remote runner whose turn is still running, restarts an unstarted bootstrap, or fails the run with a working Retry. - `claimNativeRestartRecoveries`: a self-owned lease that is still live, with no driver here, now returns a `retryAt` at its expiry, so the wait is bounded. - `heartbeat/shutdown-handoff.ts`: add `isRunHandedOffForShutdown`. Heartbeat recovery passes it to the claim. - `suspendedByCleanDrain` now uses the shared `handedToNextControllerSinceClaim` helper. Behavior is the same. - Heartbeat test: an executor detaches after its own lease lapsed, with no restart. The same process must take the run back. Red before (timed out, the run stayed `running`), green after. - Tests: five cases for the same-boot lapsed lease: bootstrap again with no runner command; fail with a working Retry when a runner identity was recorded; leave the run to a live in-process executor; leave a handed-off run to the next server; still wait for a different live controller. ## Verification - Red before the fix: the three same-boot cases returned `awaiting_evidence` / `controller_still_alive`. - Green after the fix: - `pnpm --dir server exec vitest run src/services/native-runtime/native-runner-restart-recovery.integration.test.ts src/services/native-runtime/native-restart-recovery.test.ts src/__tests__/heartbeat-native-restart-suspension.test.ts` - Daytona wave `w-20261111T050504-s9331` from this branch (same seed and shape as s9331: 3 tasks, concurrency 3, three 90 s TM1 stalls with about 1 s between them). All 3 tasks reached `done` with no Retry. Run `632f0564` (claude) shows the exact s9331 sequence: `native.session.execute` failed after 216 s, then `reattach_remote_runner` 0.4 s later (before the third stall), then a second reattach after it, and the turn completed. Two tasks are graded FAIL only on the T1 crossing check: their own fault landed after their tool loop ended (for example loop ended 05:11:26, fault 05:11:44). Their status is `done`, with no Retry. - `tsc --noEmit -p server` is clean. ## Risks - A same-process recovery scan can now claim a run that this process recorded as its own. The guard needs all of these: the self lease lapsed, no in-process execution of the run, and no handoff to the next server. A claim that is still on its way to its executor holds a live lease, so it is not taken twice. - Upgrade safety: the decision uses only the coordinator row and in-process state. Old saved rows are judged by the same rules. A new process never matches an old boot ID, so deploys keep the existing proof path. - No new waits or file operations run before `turn.start`. - There is still no ceiling on `awaiting_evidence` for a genuinely different live controller (case c). This PR does not change that policy. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code, with tool use (shell, file edit) and extended reasoning. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- ...eartbeat-native-restart-suspension.test.ts | 53 +++++++++++- server/src/services/heartbeat.ts | 11 ++- server/src/services/heartbeat/recovery.ts | 3 +- .../services/heartbeat/shutdown-handoff.ts | 5 ++ .../native-runtime/native-execution-lease.ts | 17 ++++ .../native-failed-workspace-recovery.test.ts | 4 +- .../native-runtime/native-restart-recovery.ts | 35 +++++++- ...unner-restart-recovery.integration.test.ts | 83 ++++++++++++++++++- 8 files changed, 202 insertions(+), 9 deletions(-) diff --git a/server/src/__tests__/heartbeat-native-restart-suspension.test.ts b/server/src/__tests__/heartbeat-native-restart-suspension.test.ts index 0ce76469c5f..b32671995b8 100644 --- a/server/src/__tests__/heartbeat-native-restart-suspension.test.ts +++ b/server/src/__tests__/heartbeat-native-restart-suspension.test.ts @@ -384,6 +384,55 @@ describeEmbeddedPostgres("heartbeat native recovery interrupted by graceful shut expect(reached).toHaveBeenCalled(); }, 60_000); + // Daytona waves s9330 and s9331 (TM1): stalls of the same server outlived + // the execution lease. Renewal found the lease lapsed and detached the + // executor for "the next controller" with no shutdown handoff, and the + // executor returned with the run still running. The next controller is this + // same process; nothing may leave the run running with no recovery. + it("recovers a run whose executor detached after its own lease lapsed, with no restart", async () => { + const f = await seedRecoverableRun("SELF-DETACHED-LAPSED"); + let opened = 0; + const reachedAgain = vi.fn(); + const backend = vi.fn((): NativeSessionBackend => { + opened += 1; + const first = opened === 1; + const open = async () => { + if (first) { + // What the remote renewal's loss does: the lease lapsed during the + // stall, and the executor is detached for the next controller. + await f.db.update(nativeRunFinalizations).set({ leaseExpiresAt: new Date(Date.now() - 1_000) }) + .where(eq(nativeRunFinalizations.runId, f.runId)); + void detachNativeSessionsForRestart([f.runId]); + throw new Error("runner stream lost while the controller was stopped"); + } + reachedAgain(); + throw new Error("stop at provider dispatch"); + }; + return { + async descriptor() { + return { kind: "mock", name: "self-detached", version: "1", capabilities: { + resume: true, typedEvents: true, steering: false, interruption: true, structuredResult: true }, + runtimeContextCapabilities: { instructions: "native", skills: "native", mcp: "native" } }; + }, + openSession: open, + recoverSession: open, + } as unknown as NativeSessionBackend; + }); + const heartbeat = heartbeatService(f.db, { nativeSessionBackendFactory: backend }); + try { + const { claims } = await heartbeat.recoverNativeRunsAfterRestart(new Date(), [f.runId]); + expect(claims).toEqual([expect.objectContaining({ runId: f.runId })]); + await heartbeat.drainActiveRunExecutions(); + // The same process takes the run back on its own, without a restart. + await waitForCondition("the same process to take the run back", () => reachedAgain.mock.calls.length > 0, 15_000); + } finally { await heartbeat.drainActiveRunExecutions(); } + expect(reachedAgain).toHaveBeenCalled(); + const transitions = await f.db.select().from(heartbeatRunEvents).where(and(eq(heartbeatRunEvents.runId, f.runId), + eq(heartbeatRunEvents.eventType, "native.recovery.transition"))); + expect(transitions.map(event => (event.payload as Record).reason)) + .not.toContain("controller_still_alive"); + }, 60_000); + async function shutdownDispositions(db: Awaited>["db"], runId: string) { const events = await db.select().from(heartbeatRunEvents).where(and(eq(heartbeatRunEvents.runId, runId), @@ -832,7 +881,9 @@ describeEmbeddedPostgres("heartbeat native recovery interrupted by graceful shut .where(eq(nativeRunFinalizations.runId, f.runId)); const onClaim = vi.fn(); expect(await claimNativeRestartRecoveries({ db: f.db, restartKind: "hard", runIds: [f.runId], onClaim })) - .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_still_alive" }]); + .toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_still_alive", + // This process's own live lease lapses by itself; recovery looks again then. + retryAt: expect.any(Date) }]); expect(onClaim).not.toHaveBeenCalled(); }, 60_000); diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index baaaace2ea1..72916c807b0 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -55,7 +55,7 @@ import { prepareHeartbeatTaskContext } from "./heartbeat/task-context.js"; import { selectHeartbeatEnvironment } from "./heartbeat/environment-selection.js"; import { reconcileMuseNativeTerminalRun } from "./native-runtime/muse-terminal-reconciliation.js"; import { prepareHeartbeatWorkspace } from "./heartbeat/workspace-preparation.js"; -import { nativeRecoveryClaimRelinquished, releaseLapsedNativeRestartClaim } from "./native-runtime/native-execution-lease.js"; +import { nativeRecoveryClaimRelinquished, ownNativeExecutionLeaseLapsed, releaseLapsedNativeRestartClaim } from "./native-runtime/native-execution-lease.js"; import { executeHeartbeatRuntime, NativeSessionResumeScheduledError, NativeWorkspaceFinalizeScheduledError } from "./heartbeat/runtime-execution.js"; import { preserveNativeFailedWorkspace } from "./native-runtime/native-failed-workspace-recovery.js"; import { nativeRunHasNoWorkspaceAccess } from "./workspace-restore-recovery-state.js"; @@ -2041,6 +2041,11 @@ export function heartbeatService( Parameters[0] | null = null; let nativeSessionResumeScheduled = false; let restartClaimLapsed = false; + // The executor detached for "the next controller" because its own lease + // lapsed (for example after a stall), with no shutdown or hot-restart + // handoff. The next controller is this process: recover the run here once + // the executor has exited. A shutdown detach leaves it to the next server. + let detachedWithoutHandoff = false; const shutdownHandedOff = watchShutdownHandoff(run.id); let nativeOwnershipHeld = false; let nativeStartupCleanupScheduled = false; @@ -3707,6 +3712,8 @@ export function heartbeatService( } if (err instanceof NativeControllerDetachedForRestartError) { nativeSessionResumeScheduled = true; + detachedWithoutHandoff = !shutdownHandedOff() && await ownNativeExecutionLeaseLapsed(db, run) + .catch(() => false); return; } if (err instanceof NativeRunnerOwnershipUnverifiedError) { @@ -4168,7 +4175,7 @@ export function heartbeatService( } finally { controllerLease.stop(); activeRunExecutions.delete(run.id); - if (restartClaimLapsed) scheduleNativeSessionResumeDispatch(run.id, new Date(), "restart"); + if (restartClaimLapsed || detachedWithoutHandoff) scheduleNativeSessionResumeDispatch(run.id, new Date(), "restart"); // A failed owned Stop remains visible until this exact executor settles, // including a graceful exit result arriving after the cancellation error. // It is never retained beyond the active execution's cleanup. diff --git a/server/src/services/heartbeat/recovery.ts b/server/src/services/heartbeat/recovery.ts index f6ea8aa8dae..88914e28336 100644 --- a/server/src/services/heartbeat/recovery.ts +++ b/server/src/services/heartbeat/recovery.ts @@ -1,5 +1,5 @@ import { settleOwnableKind } from "../recovery/ownership-invariant-report.js"; -import { markRunHandedOffForShutdown } from "./shutdown-handoff.js"; +import { isRunHandedOffForShutdown, markRunHandedOffForShutdown } from "./shutdown-handoff.js"; import { ORPHANED_RUN_LEASE_FAILURE_REASON } from "../environment-run-lease-settlement.js"; import { ENVIRONMENT_LEASE_CONTROLLER_KEY } from "../environment-lease-controller.js"; import { readNativeStartupCleanup, readNativeStartupContext } from "../native-runtime/native-startup-cleanup.js"; @@ -1009,6 +1009,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD }, db, liveRunExecutions: activeRunExecutions, + handedOffForShutdown: isRunHandedOffForShutdown, runIds, restartKind, recoveryRequestId: intent?.recoveryRequestId ?? null, diff --git a/server/src/services/heartbeat/shutdown-handoff.ts b/server/src/services/heartbeat/shutdown-handoff.ts index 57df43b2cef..0d84fcdd18c 100644 --- a/server/src/services/heartbeat/shutdown-handoff.ts +++ b/server/src/services/heartbeat/shutdown-handoff.ts @@ -11,3 +11,8 @@ export function watchShutdownHandoff(runId: string): () => boolean { return current !== undefined && current !== atStart; }; } + +/** This process handed the run to the next server (graceful drain or hot restart). */ +export function isRunHandedOffForShutdown(runId: string): boolean { + return runsHandedOffForShutdown.has(runId); +} diff --git a/server/src/services/native-runtime/native-execution-lease.ts b/server/src/services/native-runtime/native-execution-lease.ts index b63b7e1398f..626fe99ed33 100644 --- a/server/src/services/native-runtime/native-execution-lease.ts +++ b/server/src/services/native-runtime/native-execution-lease.ts @@ -220,6 +220,23 @@ export async function nativeRecoveryClaimRelinquished(input: { && row.lastDisposition === "restart_suspended"; } +/** + * The run's controller is this process and its execution lease has lapsed + * (or was released): the executor that held it detached because of that loss, + * not because a shutdown or hot restart handed the run on. + */ +export async function ownNativeExecutionLeaseLapsed(db: Db, input: { companyId: string; id: string }): Promise { + const controller = await currentNativeControllerIdentity(); + const [row] = await db.select({ runId: nativeRunFinalizations.runId }).from(nativeRunFinalizations) + .innerJoin(heartbeatRuns, eq(heartbeatRuns.id, nativeRunFinalizations.runId)) + .where(and(eq(nativeRunFinalizations.companyId, input.companyId), eq(nativeRunFinalizations.runId, input.id), + eq(heartbeatRuns.status, "running"), isNull(nativeRunFinalizations.resultId), + eq(nativeRunFinalizations.controllerBootId, controller.bootId), eq(nativeRunFinalizations.controllerPid, controller.pid), + or(isNull(nativeRunFinalizations.leaseExpiresAt), sql`${nativeRunFinalizations.leaseExpiresAt} <= clock_timestamp()`))) + .limit(1); + return Boolean(row); +} + export async function releaseLapsedNativeRestartClaim(input: { db: Db; companyId: string; runId: string; leaseOwner: string; controllerGeneration: number; providerAttempt: number; }): Promise { diff --git a/server/src/services/native-runtime/native-failed-workspace-recovery.test.ts b/server/src/services/native-runtime/native-failed-workspace-recovery.test.ts index e00347330c5..ecc80c19754 100644 --- a/server/src/services/native-runtime/native-failed-workspace-recovery.test.ts +++ b/server/src/services/native-runtime/native-failed-workspace-recovery.test.ts @@ -87,7 +87,9 @@ const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTes expect(await claimNativeRestartRecoveries({ db, restartKind: "hard", runIds: [f.runId] })).toEqual([ { kind: kind === "owned" ? "awaiting_evidence" : "blocked", runId: f.runId, - reason: kind === "owned" ? "controller_still_alive" : "provider_checkpoint_permanently_failed" }, + reason: kind === "owned" ? "controller_still_alive" : "provider_checkpoint_permanently_failed", + // This process's own live lease lapses by itself; recovery looks again then. + ...(kind === "owned" ? { retryAt: expect.any(Date) } : {}) }, ]); const current = await readRun(f.runId); expect(current.status).toBe(kind === "owned" ? "running" : "failed"); diff --git a/server/src/services/native-runtime/native-restart-recovery.ts b/server/src/services/native-runtime/native-restart-recovery.ts index ec0bce99dbd..bd81b559f24 100644 --- a/server/src/services/native-runtime/native-restart-recovery.ts +++ b/server/src/services/native-runtime/native-restart-recovery.ts @@ -164,9 +164,13 @@ export function suspendedByCleanDrain(coordinator: { }): boolean { // Attempt 0 means no execution has claimed the run yet. Its first provider // start must still be counted, whatever interrupted preparation. - if (coordinator.attempt <= 0) return false; - for (let index = coordinator.recoveryHistory.length - 1; index >= 0; index -= 1) { - const disposition = coordinator.recoveryHistory[index]?.disposition; + return coordinator.attempt > 0 && handedToNextControllerSinceClaim(coordinator.recoveryHistory); +} + +/** The latest record since the last claim hands the run to the next server. */ +function handedToNextControllerSinceClaim(history: ReadonlyArray<{ disposition?: unknown }>): boolean { + for (let index = history.length - 1; index >= 0; index -= 1) { + const disposition = history[index]?.disposition; if (disposition === "restart_suspended") return true; if (RECOVERY_CLAIM_DISPOSITIONS.has(disposition)) return false; } @@ -1029,6 +1033,8 @@ export async function claimNativeRestartRecoveries(input: { recoveryRequestId?: string | null; runIds?: string[]; liveRunExecutions?: Pick, "has">; + /** Runs this process handed to the next server (graceful drain or hot restart). */ + handedOffForShutdown?: (runId: string) => boolean; now?: Date; limit?: number; /** Called after each committed claim, before scanning the next candidate. */ @@ -1306,8 +1312,27 @@ export async function claimNativeRestartRecoveries(input: { && (controllerHostHash === "unknown" || row.coordinator.controllerHostHash !== controllerHostHash); const nonExecutionOwner = row.coordinator.leaseOwner?.startsWith("native-finalizer:") || row.coordinator.leaseOwner?.startsWith("native-cleanup:"); + // The recorded controller is this exact process (same boot and PID), so + // a PID probe can only ever answer "alive" and the wait would never end. + // This process knows whether it still drives the run: its executor is + // registered for the whole execution. While it is, leave the run to it. + // Once it has exited (for example after a stall outlived its lease and + // renewal detached it for "the next controller"), the prior owner is + // provably gone, and the evidence checks below decide as for any + // stopped controller. An unexpired self lease still waits: a claim that + // has not reached its executor yet holds it, and it lapses on its own. + // A run this process handed to the next server (graceful drain or hot + // restart) stays with that server: this process is about to exit. + const ownControllerProcess = !nonExecutionOwner && isCurrentNativeControllerProcess(row.coordinator); + if (ownControllerProcess && activeNativeExecutionRunIds.has(row.run.id)) { + return { kind: "awaiting_evidence", runId: row.run.id, reason: "current_controller_preparing" } as const; + } + const ownLeaseLapsed = ownControllerProcess && row.coordinator.leaseExpiresAt !== null + && row.coordinator.leaseExpiresAt <= now && !input.handedOffForShutdown?.(row.run.id) + && !handedToNextControllerSinceClaim(row.coordinator.recoveryHistory); const evaluatedTakeover = nonExecutionOwner ? { allowed: false, reason: "native_finalization_or_cleanup_owner" } + : ownLeaseLapsed ? { allowed: true, reason: "current_controller_released" } : await evaluateNativeControllerTakeover({ owner: row.coordinator, now, @@ -1379,6 +1404,10 @@ export async function claimNativeRestartRecoveries(input: { runId: row.run.id, reason: takeover.reason, ...(durableAuthority && row.coordinator.leaseExpiresAt ? { retryAt: row.coordinator.leaseExpiresAt } + // This process's own unexpired lease with no driver here lapses by + // itself; look again then instead of waiting for another signal. + : 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) } : {}), } as const; 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 0e401700d39..348fcb7c29c 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 @@ -38,7 +38,7 @@ import { nativeRunnerCheckpoints, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, } from "@paperclipai/db"; -import { beforeAll, expect, it, vi } from "vitest"; +import { beforeAll, describe, expect, it, vi } from "vitest"; import { heartbeatService } from "../heartbeat.js"; import { @@ -79,6 +79,7 @@ import { restoreNativeRunnerCheckpoint, } from "./native-runner-checkpoint.js"; import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js"; +import { setNativeExecutionActive } from "./native-active-runs.js"; import { RUNNER_BRIDGE_READ_OPERATIONS, RUNNER_BRIDGE_SCHEMAS } from "./runner-bridge-tools.js"; import { HttpError } from "../../errors.js"; import { legacyControllerBootId } from "../legacy-controller-lease.js"; @@ -3297,6 +3298,86 @@ process.on("SIGTERM", () => child.kill("SIGTERM")); restartKind: "hard", runIds: [fixture.runId] })).toEqual([expect.objectContaining({ runId: fixture.runId, ...expected })]); }); + // Daytona wave s9330 t02 (TM1): SIGSTOP held this same server past its + // execution lease while the executor was starting the native process. On + // SIGCONT the lease renewal found the lease lapsed, the executor detached for + // "the next controller" and exited, and every recovery scan then waited on + // the recorded controller: this same live PID and boot. Nothing else can hold + // a lease that names this process, and nothing in it drives the run any more. + describe("same-boot controller whose own lease lapsed", () => { + it("restarts the bootstrap instead of waiting on itself when no turn reached the runner", async () => { + const fixture = await seedUnlaunchedRemoteClaim("SELF-LAPSED-UNCOMMANDED", + { liveController: true, leaseExpired: true, event: { eventType: "native.process_start_requested" } }); + const [claim] = await claimNativeRestartRecoveries({ db: fixture.db, controller: await currentNativeControllerIdentity(), + restartKind: "hard", runIds: [fixture.runId], liveRunExecutions: new Set() }); + expect(claim).toMatchObject({ kind: "bootstrap_incomplete", runId: fixture.runId, controllerGeneration: 2 }); + const [coordinator] = await fixture.db.select().from(nativeRunFinalizations) + .where(eq(nativeRunFinalizations.runId, fixture.runId)); + expect(coordinator.recoveryHistory.at(-1)).toMatchObject({ reason: "remote_runner_never_received_commands" }); + }); + + it("fails with a Retry instead of waiting on itself when the runner may have started", async () => { + const fixture = await seedUnlaunchedRemoteClaim("SELF-LAPSED-IDENTITY", + { liveController: true, leaseExpired: true, event: { eventType: "native.process_identity_recorded" } }); + expect(await claimNativeRestartRecoveries({ db: fixture.db, controller: await currentNativeControllerIdentity(), + restartKind: "hard", runIds: [fixture.runId], liveRunExecutions: new Set() })) + .toEqual([expect.objectContaining({ kind: "blocked", runId: fixture.runId, reason: "ambiguous_remote_recovery_evidence" })]); + const [coordinator] = await fixture.db.select().from(nativeRunFinalizations) + .where(eq(nativeRunFinalizations.runId, fixture.runId)); + expect(coordinator).toMatchObject({ phase: "terminal_failure", leaseOwner: null, failureCode: "native_restart_recovery_blocked" }); + const [run] = await fixture.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId)); + expect(run.status).toBe("failed"); + const [issue] = await fixture.db.select().from(issues).where(eq(issues.id, fixture.issueId)); + expect(await taskInterruptionPresentation(fixture.db, issue)).toMatchObject({ + state: "failed", canRetry: true, observedRunId: fixture.runId }); + const personId = randomUUID(); + await fixture.db.insert(authUsers).values({ id: personId, name: "Retry person", email: `${personId}@fixture.invalid`, + emailVerified: true, createdAt: new Date(), updatedAt: new Date() }); + await fixture.db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: personId, + status: "active", membershipRole: "member" }); + expect(await requestTaskRetry({ db: fixture.db, companyId, issueId: fixture.issueId, actorId: personId, + actorSource: "session", idempotencyKey: `self-lapsed-${fixture.runId}`, observedRunId: fixture.runId })) + .toMatchObject({ accepted: true }); + }); + + it("leaves the run to this process's executor while it still drives the run", async () => { + const fixture = await seedUnlaunchedRemoteClaim("SELF-LAPSED-EXECUTING", + { liveController: true, leaseExpired: true, event: { eventType: "native.process_start_requested" } }); + expect(await claimNativeRestartRecoveries({ db: fixture.db, controller: await currentNativeControllerIdentity(), + restartKind: "hard", runIds: [fixture.runId], liveRunExecutions: new Set([fixture.runId]) })) + .toEqual([expect.objectContaining({ kind: "awaiting_evidence", reason: "current_controller_preparing" })]); + setNativeExecutionActive(fixture.runId, true); + try { + expect(await claimNativeRestartRecoveries({ db: fixture.db, controller: await currentNativeControllerIdentity(), + restartKind: "hard", runIds: [fixture.runId], liveRunExecutions: new Set() })) + .toEqual([expect.objectContaining({ kind: "awaiting_evidence", reason: "current_controller_preparing" })]); + } finally { + setNativeExecutionActive(fixture.runId, false); + } + }); + + it("leaves a run this process handed to the next server for that server", async () => { + const fixture = await seedUnlaunchedRemoteClaim("SELF-LAPSED-HANDED-OFF", + { liveController: true, leaseExpired: true, event: { eventType: "native.process_start_requested" } }); + expect(await claimNativeRestartRecoveries({ db: fixture.db, controller: await currentNativeControllerIdentity(), + restartKind: "hard", runIds: [fixture.runId], liveRunExecutions: new Set(), + handedOffForShutdown: runId => runId === fixture.runId })) + .toEqual([expect.objectContaining({ kind: "awaiting_evidence", reason: "controller_still_alive" })]); + }); + + it("keeps waiting for a different live controller in this process space", async () => { + const fixture = await seedUnlaunchedRemoteClaim("OTHER-LIVE-LAPSED", + { leaseExpired: true, event: { eventType: "native.process_start_requested" } }); + // Another live process (the test runner's parent) recorded as controller. + const parentStartedAt = new Date((await readProcessStartedAt(process.ppid))!); + await fixture.db.update(nativeRunFinalizations).set({ controllerPid: process.ppid, + controllerProcessStartedAt: parentStartedAt }).where(eq(nativeRunFinalizations.runId, fixture.runId)); + expect(await claimNativeRestartRecoveries({ db: fixture.db, controller: await currentNativeControllerIdentity(), + restartKind: "hard", runIds: [fixture.runId], liveRunExecutions: new Set() })) + .toEqual([expect.objectContaining({ kind: "awaiting_evidence", reason: "controller_still_alive" })]); + }); + }); + it.each([ { attempt: 2, driverKind: "codex_app_server" }, { attempt: 3, driverKind: "codex_app_server" }, From 1143abaf92221121b708f0520f0e9df99f2038dd Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 10 Nov 2026 23:59:01 -0600 Subject: [PATCH 36/38] fix(recovery): give due exhausted holds their own fair lane in the recovery worker (#20725) 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 > - The workspace recovery worker saves the files of failed runs. It also re-arms exhausted holds under the rules of #20295, #20569, #20641 and #20648 > - After #20680 and #20661 were deployed to staging, the worker still re-armed none of 29 exhausted holds in 36 minutes. One hold's id sorts in the first percent of all candidates, so the restart starvation that #20680 fixed was not the only cause > - The worker skipped every obligation while any unfinished save was selectable. Discovery is instance-wide. A save that another server owns stays unfinished on every run, so obligations never ran. The obligation pass also put due holds behind hundreds of settled holds whose saved input waits, at two per run. A completed pass never revisited a hold that became due by time alone > - This pull request gives due exhausted holds their own lane, and it shares the worker's slots fairly between unfinished saves, due holds and the obligation pass > - The benefit is that every due hold is reached within a few runs of the worker, whatever its other load. The holds save their files and free their tasks without a person ## Linked Issues or Issue Description Refs #20680 Refs #20661 Refs #20648 Refs #20641 Refs #20569 Refs #20295 **What happened?** On staging, 36 minutes after a deploy that included #20680 and #20661, the workspace recovery worker had touched none of the 29 exhausted holds of the company (22 capture-policy holds and 7 stop-proof or fallback holds). They had no `stopProofRecovery` or `capturePolicyRecovery` marker, no re-arm activity, and `updatedAt` from Nov 2 to Nov 10. The worker did run manual "Recover saved files" requests: one stop-proof hold saved its files 57 seconds after the request. So the worker was alive and the stop proof was available. The holds were not reached. **What did you expect to happen?** The worker reaches each exhausted hold whose re-arm or fallback is due, re-arms it, and saves the files, within a bounded time. **Steps to reproduce** 1. Create a scheduled save whose run's finalization lock another database session holds (another server owns the run). 2. Create an exhausted stop-proof hold and an exhausted capture-policy hold, in the evidence shape that the Nov 4 and Nov 10 releases saved. 3. Start the real workspace recovery worker. 4. The worker retries the busy save on every run and never re-arms either hold. ## What Changed - `server/src/services/workspace-recovery.ts`: `reconcileRetainedWorkspaces` draws candidates from lanes. Each lane is a page that its own cursor advances: unfinished saves; for the worker, exhausted holds whose re-arm or fallback is due; and the obligation pass. Before, the obligation pass ran only when no unfinished save was selectable (the gate at `const unfinished = rows.length > 0; if (!rows.length) { ... }`). - Each lane with work takes one free slot before any lane takes a second. The lane that goes first rotates on each run, so with one free slot (a long local export holds the other) each lane still gets it in one run of three. Actions of a run that one lane took join that run's job without another slot. - The due lane wraps at its tail. A hold that becomes due by time alone (a lease expiry or a re-arm backoff) is reached after the obligation pass completed with no committed change. - `retainedWorkspaceCandidates` takes a `dueOnly` filter (due re-arm or fallback of an exhausted hold). The obligation filter uses the same condition. One `now` is used for the whole query. - The startup sweep (no worker sweep state) also shares its slots between unfinished saves and its general pass. - `doc/execution-semantics.md`: document the lanes and the fairness rule. - New `workspace-recovery-passive-fairness.test.ts` with four real-Postgres regressions. ## Verification - Red on `origin/master` (156212cfd5), green with this change: - "re-arms both staging holds while a save that another server owns stays unfinished": the real worker, a busy unfinished save, and the two staging hold shapes. On master neither hold is re-armed in 20 s. - "reaches due holds within two runs however many settled holds with waiting input sort before them": ten settled holds with waiting user input sort before the two holds. On master the capture-policy hold is not re-armed after two runs. - "re-arms a hold that becomes due after its pass completed, with no committed change": on master the hold is never re-armed. - "re-arms the holds with one free slot while a long local job holds the other and a busy save stays unfinished" (from the Greptile review): red on this PR's first revision (05b261e5fe), green with the lane rotation. - `npx vitest run` of the twelve suites that use discovery or the worker (`heartbeat-observed-workspace-preservation`, `server-startup-feedback-export`, `execution-control-work`, `workspace-recovery-preparation-dispatch`, `-retry-copyback`, `-fallback`, `-warm-handoff`, `-preparation-gates`, `-capture-policy`, `-preparation`, `-stop-proof`, `-admission`) plus the new suite: 646 passed. - `npx tsc --noEmit -p server/tsconfig.json`: clean. - `pnpm verify` exits 2 because `doc/execution-semantics.md` is a global CI input. Required CI supplies the broad coverage. - Staging (read-only GET requests): the 29 exhausted holds, their saved shapes, and the manual Retry timeline. Staging exposes only one company to this account and no worker logs, so the exact unfinished row that starved the pass on staging is not named. The fix removes the whole class: no lane can starve another. ## Risks - Previous-release story: no persisted state changes. Lane positions stay in memory, as the existing cursors did. Holds saved by earlier releases (no marker, no capture policy version) are due at once and are reached in the first runs after deploy, with no migration. A deploy that lands mid-run only resets the in-memory cursors. - Behavior shift: obligations now share the two slots with unfinished saves. With two free slots, a new save or a manual Retry gets one in two runs of three. With one free slot, it gets it in one run of three. - A due hold that its re-arm refuses again is revisited once per due-lane pass. The worker already ran every interval while such a hold was due, so this adds no new wakeups. - One more bounded query per worker run (the due lane, 5 rows). ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell, code editing, browser GET reads) in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/execution-semantics.md | 10 + ...orkspace-recovery-passive-fairness.test.ts | 186 ++++++++++++++++++ server/src/services/workspace-recovery.ts | 114 ++++++++--- 3 files changed, 279 insertions(+), 31 deletions(-) create mode 100644 server/src/services/workspace-recovery-passive-fairness.test.ts diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index b788e06ff84..5a2f0494b60 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -3829,6 +3829,16 @@ input does not keep the worker active; a committed change starts a fresh pass once the current pass reaches its tail. A pass is never restarted midway, so on a busy instance, where changes commit continuously, every candidate is still visited: the due re-arms and fallbacks of older exhausted holds included. +Discovery is instance-wide and draws from separate lanes, each paged by its own +cursor: unfinished saves, exhausted holds whose re-arm or fallback is due, and +this pass. Each lane with work takes one free slot before any lane takes a +second, and the lane that goes first rotates on each run. A save that another +server owns, a long local export, or hundreds of holds whose saved input waits +therefore cannot starve a due hold: it is reached within a few runs of the +worker. The due lane wraps at its tail, so a hold that becomes due +by time alone (a lease expiry or a re-arm backoff) is reached even after the +pass completed with no committed change. Lane positions are kept in memory; a +restart starts each lane from its first candidate, with no migration. Shutdown joins this worker's exports before closing the database. Repeated Retry during physical preservation binds the canonical intent without changing the attempt's generation or revision. Progress writes preserve diff --git a/server/src/services/workspace-recovery-passive-fairness.test.ts b/server/src/services/workspace-recovery-passive-fairness.test.ts new file mode 100644 index 00000000000..05db5e16294 --- /dev/null +++ b/server/src/services/workspace-recovery-passive-fairness.test.ts @@ -0,0 +1,186 @@ +import { randomUUID } from "node:crypto"; +import { eq, sql } from "drizzle-orm"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { agentWakeupRequests, createDb, issueRecoveryActions, nativeRunFinalizations } from "@paperclipai/db"; +import type { AdapterSandboxExecutionTarget } from "@paperclipai/adapter-utils/execution-target"; +import { nativeWorkspaceFinalizationLockKey } from "./native-runtime/native-workspace-finalization-ownership.js"; +import { readSystemRecovery } from "./system-recovery-state.js"; +import { adoptSystemRecovery } from "./system-recovery.js"; +import { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; +import { registerWorkspaceRecoveryWork } from "./workspace-recovery-work.js"; +import { reconcileRetainedWorkspaces, retainedWorkspaceCandidates, type PassiveSweep } from "./workspace-recovery.js"; +import { acceptedRemoteExport, action, connectionString, db, run, seed, useWorkspaceRecoveryFixture } from "./__tests__/workspace-recovery-fixture.js"; + +const targets = vi.hoisted(() => new Map()); +vi.mock("./execution-control-deadline.js", async importOriginal => ({ + ...await importOriginal(), EXECUTION_RECONCILIATION_INTERVAL_MS: 200 })); +vi.mock("./environment-execution-target.js", async importOriginal => { + const actual = await importOriginal(); + return { ...actual, resolveEnvironmentExecutionTarget: async (input: Parameters[0]) => + (input.leaseId ? targets.get(input.leaseId) : undefined) ?? actual.resolveEnvironmentExecutionTarget(input) }; +}); + +/** + * Staging (Nov 11): 36 minutes after #20680 shipped, the + * worker had still re-armed none of the company's 29 exhausted holds, not even + * one whose id sorts in the first percent. It did run manual Retries, which + * its unfinished lane selects. Discovery is instance-wide: unfinished work + * had strict priority over every obligation, and the obligation pass mixed due + * holds with hundreds of settled holds whose saved user input waits, two per + * run. Either kind of load kept the due holds from being reached. + */ +describe("the workspace recovery worker reaches every due hold whatever its other load", () => { + useWorkspaceRecoveryFixture(targets); + beforeEach(() => { + vi.stubEnv("DATABASE_URL", connectionString); + vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", "63".repeat(32)); + }); + afterEach(() => { vi.unstubAllEnvs(); }); + + /** An export hold of Nov 4, exhausted waiting for stop proof: the exact evidence that release saved. */ + async function stopProofHold(id: string) { + const f = await acceptedRemoteExport("retained"); + const firstFailureAt = Date.parse("2026-11-04T23:58:14Z"); + await db.update(issueRecoveryActions).set({ id, ownerType: "system", evidence: { ...(await action(f.actionId)).evidence, + systemRecovery: { ...readSystemRecovery((await action(f.actionId)).evidence)!, revision: 3, phase: "verify_execution", state: "exhausted", + attempts: 1, retriesUsed: 0, attemptId: randomUUID(), firstFailureAt, deadlineAt: firstFailureAt + 30 * 60_000, nextAttemptAt: null, + failure: { code: "agent_stop_unconfirmed", retryClass: "recheck_evidence", evidenceFingerprint: "9615".repeat(16) } }, + workspaceRecovery: { schema: "paperclip.workspace-recovery.v1", runId: f.runId, status: "blocked", stage: "verifying_stop", + attempt: 1, attemptLimit: 6, retryable: true, requestIds: [] } } }).where(eq(issueRecoveryActions.id, f.actionId)); + return { ...f, actionId: id }; + } + + /** A board-owned save of Nov 10, exhausted after 6 attempts under capture policy 1 (no version saved). */ + async function capturePolicyHold(id: string) { + const f = await acceptedRemoteExport("retained"); + const prior = await action(f.actionId); + const { capturePolicyVersion: _omitted, ...saved } = readSystemRecovery(prior.evidence)! as ReturnType & { capturePolicyVersion?: number }; + const firstFailureAt = Date.parse("2026-11-10T13:58:11Z"); + await db.update(issueRecoveryActions).set({ id, ownerType: "board", evidence: { ...prior.evidence, + systemRecovery: { ...saved, revision: 18, phase: "preserve_files", state: "exhausted", attempts: 6, retriesUsed: 5, + attemptId: randomUUID(), firstFailureAt, deadlineAt: firstFailureAt + 30 * 60_000, nextAttemptAt: null, + failure: { code: "export_interrupted", retryClass: "retry_transient", evidenceFingerprint: "9483".repeat(16), + cause: { code: null, label: "provider_error", status: null } } }, + workspaceRecovery: { schema: "paperclip.workspace-recovery.v1", runId: f.runId, status: "blocked", stage: "restoring_files", + attempt: 6, attemptLimit: 6, retryable: true, requestIds: [] } } }).where(eq(issueRecoveryActions.id, f.actionId)); + return { ...f, actionId: id }; + } + + /** A settled no-replay hold (active or resolved-but-blocked) whose task has saved user input waiting: selectable on every pass. */ + async function waitingSettledHold(id: string, status: "active" | "resolved") { + const f = await seed("native", true); + await adoptSystemRecovery(db, f); + const prior = await action(f.actionId); + await db.update(issueRecoveryActions).set({ id, status, outcome: status === "resolved" ? "blocked" : null, ownerType: "system", + evidence: { ...prior.evidence, + systemRecovery: { ...readSystemRecovery(prior.evidence)!, state: "complete", phase: "reconcile_effects", attempts: 1 }, + workspaceRecovery: { schema: "paperclip.workspace-recovery.v1", runId: f.runId, status: "recovered", stage: "saving_receipts", + attempt: 1, attemptLimit: 6, retryable: false, requestIds: [] }, + automaticRecovery: { runId: f.runId, policy: "preserve_without_replay_v1", replay: "blocked" } } }) + .where(eq(issueRecoveryActions.id, f.actionId)); + await db.insert(agentWakeupRequests).values({ companyId: f.companyId, agentId: (await run(f.runId)).agentId, source: "on_demand", + reason: "issue_commented", status: "deferred_issue_execution", requestedByActorType: "user", requestedByActorId: "board", + payload: { issueId: f.issueId } }); + return f; + } + + const rearmed = async (id: string) => { + const evidence = (await action(id)).evidence; + return Boolean(evidence.stopProofRecovery || evidence.capturePolicyRecovery); + }; + + it("re-arms both staging holds while a save that another server owns stays unfinished", async () => { + // A scheduled save whose run another server is finalizing: every attempt + // here finds the run's finalization lock busy and leaves it scheduled. + const busy = await seed("native", true); + await adoptSystemRecovery(db, busy); + expect(readSystemRecovery((await action(busy.actionId)).evidence)?.state).toBe("scheduled"); + const owner = createDb(connectionString); + await owner.execute(sql`select pg_advisory_lock(hashtextextended(${nativeWorkspaceFinalizationLockKey(busy.companyId, busy.runId)}, 0))`); + const capture = await capturePolicyHold(randomUUID()); + const stop = await stopProofHold(randomUUID()); + const onError = vi.fn(); + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true, onError }); + const worker = registerWorkspaceRecoveryWork(db, coordinator, stop.environmentRuntime, async () => undefined); + try { + await worker.ready; + await vi.waitFor(async () => { + expect(await rearmed(capture.actionId)).toBe(true); + expect(await rearmed(stop.actionId)).toBe(true); + }, { timeout: 20_000, interval: 250 }); + // The busy save is still retried; it is not dropped to make room. + expect(readSystemRecovery((await action(busy.actionId)).evidence)?.state).toBe("scheduled"); + expect(onError).not.toHaveBeenCalled(); + } finally { + await worker.stop(); + await coordinator.stop(); + await owner.$client.end(); + } + }, 90_000); + + it("re-arms the holds with one free slot while a long local job holds the other and a busy save stays unfinished", async () => { + // A local job holds one of the two slots for the whole test. + const long = await waitingSettledHold(randomUUID(), "resolved"); + let release!: () => void; + const held = new Promise(resolve => { release = resolve; }); + const onRecovered = async (source: { id: string }) => { if (source.id === long.runId) await held; }; + const sweep: PassiveSweep = {}; + const first = reconcileRetainedWorkspaces(db, long.environmentRuntime, onRecovered, true, undefined, sweep); + const holding = await first ?? []; + expect(holding).toHaveLength(1); + + const busy = await seed("native", true); + await adoptSystemRecovery(db, busy); + const owner = createDb(connectionString); + await owner.execute(sql`select pg_advisory_lock(hashtextextended(${nativeWorkspaceFinalizationLockKey(busy.companyId, busy.runId)}, 0))`); + const capture = await capturePolicyHold(randomUUID()); + const stop = await stopProofHold(randomUUID()); + try { + // One free slot per run: each lane has priority in one run of three. + for (let pass = 0; pass < 6; pass += 1) + await Promise.all(await reconcileRetainedWorkspaces(db, stop.environmentRuntime, onRecovered, true, undefined, sweep) ?? []); + expect(await rearmed(capture.actionId)).toBe(true); + expect(await rearmed(stop.actionId)).toBe(true); + expect(readSystemRecovery((await action(busy.actionId)).evidence)?.state).toBe("scheduled"); + } finally { + release(); + await Promise.all(holding); + await owner.$client.end(); + } + }, 90_000); + + it("reaches due holds within two runs however many settled holds with waiting input sort before them", async () => { + for (let index = 1; index <= 10; index += 1) + await waitingSettledHold(`00000000-0000-4000-8000-${String(index).padStart(12, "0")}`, index % 3 ? "resolved" : "active"); + const capture = await capturePolicyHold("fffffffe-0000-4000-8000-000000000000"); + const stop = await stopProofHold("ffffffff-0000-4000-8000-000000000000"); + const passive = (await retainedWorkspaceCandidates(db, undefined, false, true)).map(row => row.action.id); + expect(passive.slice(0, 5).every(id => id.startsWith("00000000-"))).toBe(true); + + const sweep: PassiveSweep = {}; + for (let pass = 0; pass < 2; pass += 1) + await Promise.all(await reconcileRetainedWorkspaces(db, stop.environmentRuntime, async () => undefined, true, undefined, sweep) ?? []); + expect(await rearmed(capture.actionId)).toBe(true); + expect(await rearmed(stop.actionId)).toBe(true); + // The waiting input is still visited: the pass keeps advancing. + expect(sweep.cursor).toMatch(/^00000000-/); + }, 90_000); + + it("re-arms a hold that becomes due after its pass completed, with no committed change", async () => { + const stop = await stopProofHold("00000000-0000-4000-8000-000000000001"); + await waitingSettledHold("ffffffff-0000-4000-8000-000000000000", "resolved"); + // The finished coordinator's owner holds a live lease: not due yet. + await db.update(nativeRunFinalizations).set({ leaseOwner: `native-finalizer:${randomUUID()}`, leaseExpiresAt: new Date(Date.now() + 60_000) }) + .where(eq(nativeRunFinalizations.runId, stop.runId)); + const sweep: PassiveSweep = {}; + for (let pass = 0; pass < 3 && !sweep.complete; pass += 1) + await Promise.all(await reconcileRetainedWorkspaces(db, stop.environmentRuntime, async () => undefined, true, undefined, sweep) ?? []); + expect(sweep.complete).toBe(true); + expect(await rearmed(stop.actionId)).toBe(false); + + // The lease lapses. Time alone makes the re-arm due: nothing commits. + await db.update(nativeRunFinalizations).set({ leaseExpiresAt: new Date(Date.now() - 1_000) }).where(eq(nativeRunFinalizations.runId, stop.runId)); + await Promise.all(await reconcileRetainedWorkspaces(db, stop.environmentRuntime, async () => undefined, true, undefined, sweep) ?? []); + expect(await rearmed(stop.actionId)).toBe(true); + }, 90_000); +}); diff --git a/server/src/services/workspace-recovery.ts b/server/src/services/workspace-recovery.ts index 6c8712a031a..2bc45c172ab 100644 --- a/server/src/services/workspace-recovery.ts +++ b/server/src/services/workspace-recovery.ts @@ -587,7 +587,11 @@ export async function scheduleRecoveredWorkspaceCleanup(db: Db, run: typeof hear sql`${environmentLeases.metadata} = ${JSON.stringify(lease.metadata)}::jsonb`, sql`${environmentLeases.metadata}->>'workspaceRecoveryCleanup' is null`)), { companyId: run.companyId, runId: run.id }); } -export function retainedWorkspaceCandidates(db: Db, cursor?: string, unfinishedOnly = false, obligationsOnly = false, inFlightRunIds: string[] = []) { +/** `dueOnly` narrows the obligations to exhausted holds whose re-arm or + * fallback is due now. Cleanup, interrupted preparation and saved input that + * waits stay with the obligation pass. */ +export function retainedWorkspaceCandidates(db: Db, cursor?: string, unfinishedOnly = false, obligationsOnly = false, inFlightRunIds: string[] = [], + dueOnly = false) { const cleanup = sql`(((${heartbeatRuns.runnerProfileJson}#>>'{nativeWorkspaceSync,resourceDisposition}' = 'destroy' and ${heartbeatRuns.runnerProfileJson}#>>'{nativeWorkspaceSync,leaseId}' is not null) or (${heartbeatRuns.runnerProfileJson}->>'nativeResourceDisposition' = 'destroy' @@ -620,6 +624,8 @@ export function retainedWorkspaceCandidates(db: Db, cursor?: string, unfinishedO and ${issues.executionRunId} is null and ${issues.checkoutRunId} is null and (${issues.status} <> 'blocked' or ${issueRecoveryActions.evidence}#>>'{nativeBootstrapFailureBlock,statusVersion}' = ${issues.statusVersion}::text)))`; + const now = Date.now(); + const dueHold = sql`(${retainedSourceFallbackDueCondition(now)} or ${stopProofRearmDueCondition(now)} or ${capturePolicyRearmDueCondition(now)})`; return db.select({ action: issueRecoveryActions, run: heartbeatRuns }).from(issueRecoveryActions) .innerJoin(heartbeatRuns, and(eq(heartbeatRuns.companyId, issueRecoveryActions.companyId), eq(heartbeatRuns.id, sql`case when ${issueRecoveryActions.evidence}->>'runId' ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' @@ -632,11 +638,11 @@ export function retainedWorkspaceCandidates(db: Db, cursor?: string, unfinishedO and coalesce(${issueRecoveryActions.evidence}->>'bootstrapPreparationContinuation', 'pending') = 'pending'))` : undefined, obligationsOnly ? sql`(${issueRecoveryActions.evidence}#>>'{systemRecovery,state}' in ('scheduled', 'running', 'awaiting_evidence') or (${issueRecoveryActions.evidence}#>>'{systemRecovery,state}' = 'complete' and (${cleanup} or ${interruptedPreparation})) or ${waitingInput} - or ${retainedSourceFallbackDueCondition(Date.now())} or ${stopProofRearmDueCondition(Date.now())} - or ${capturePolicyRearmDueCondition(Date.now())})` : undefined, + or ${dueHold})` : undefined, + dueOnly ? dueHold : undefined, sql`(${issueRecoveryActions.evidence}#>>'{systemRecovery,state}' in ('scheduled', 'running', 'awaiting_evidence', 'complete', 'exhausted') and (${issueRecoveryActions.evidence}#>'{systemRecovery,nextAttemptAt}' = 'null'::jsonb - or ${issueRecoveryActions.evidence}#>'{systemRecovery,nextAttemptAt}' <= to_jsonb(${Date.now()}::bigint)))`, + or ${issueRecoveryActions.evidence}#>'{systemRecovery,nextAttemptAt}' <= to_jsonb(${now}::bigint)))`, sql`(${issueRecoveryActions.evidence}#>>'{workspaceRecovery,status}' is distinct from 'recovered' or ${cleanup} or ${waitingInput} or ${interruptedPreparation})`, cursor ? gt(issueRecoveryActions.id, cursor) : undefined, @@ -644,10 +650,27 @@ export function retainedWorkspaceCandidates(db: Db, cursor?: string, unfinishedO )).orderBy(asc(issueRecoveryActions.id)).limit(5); } -export type PassiveSweep = { cursor?: string; complete?: boolean; restart?: boolean }; +/** + * The worker's lane positions, kept in memory: a restart starts every lane + * from its first candidate, so no persisted state or migration is involved. + * `cursor`, `complete` and `restart` belong to the obligation pass; `dueCursor` + * to the due lane; `firstLane` names the lane that has priority in the next run. + */ +export type PassiveSweep = { cursor?: string; complete?: boolean; restart?: boolean; dueCursor?: string; firstLane?: number }; + +type CandidateRow = Awaited>[number]; +type CandidateLane = { rows: CandidateRow[]; index: number; advance: (actionId: string) => void }; /** Bounded discovery shares the periodic recovery lifecycle. A repaired source - * still owes cleanup even without saved input or after task reconciliation. */ + * still owes cleanup even without saved input or after task reconciliation. + * + * Candidates come from lanes, each an ordered page that a cursor advances: + * unfinished saves; for the worker, exhausted holds whose re-arm or fallback + * is due; and the obligation pass (cleanup, interrupted preparation, saved + * input that waits, and the same due holds). Each lane with work takes one + * free slot before any lane takes a second, and the worker rotates which lane + * goes first, so no kind of load (a save another server owns, a long local + * export, hundreds of waiting holds) starves another. */ export async function reconcileRetainedWorkspaces(db: Db, runtime: EnvironmentRuntimeService, onRecovered: (run: typeof heartbeatRuns.$inferSelect) => Promise, obligationsOnly = false, onFinished?: (continueSweep: boolean) => void, passiveSweep?: PassiveSweep) { @@ -658,39 +681,68 @@ export async function reconcileRetainedWorkspaces(db: Db, runtime: EnvironmentRu // Locally running exports already own their slot. Exclude them before // pagination so a page containing only held work cannot prevent wrapping. const inFlightRunIds = [...pending]; - let rows = await retainedWorkspaceCandidates(db, unfinishedCursors.get(db), true, false, inFlightRunIds); - if (!rows.length) rows = await retainedWorkspaceCandidates(db, undefined, true, false, inFlightRunIds); - const unfinished = rows.length > 0; - if (!rows.length) { - rows = await retainedWorkspaceCandidates(db, passiveSweep ? passiveSweep.cursor : cursors.get(db), false, obligationsOnly, inFlightRunIds); - if (passiveSweep && !rows.length && passiveSweep.restart) { - Object.assign(passiveSweep, { cursor: undefined, restart: false }); - rows = await retainedWorkspaceCandidates(db, undefined, false, obligationsOnly, inFlightRunIds); - } - if (passiveSweep) passiveSweep.complete = !rows.length; + let unfinishedRows = await retainedWorkspaceCandidates(db, unfinishedCursors.get(db), true, false, inFlightRunIds); + if (!unfinishedRows.length) unfinishedRows = await retainedWorkspaceCandidates(db, undefined, true, false, inFlightRunIds); + const unfinished: CandidateLane = { rows: unfinishedRows, index: 0, advance: id => unfinishedCursors.set(db, id) }; + let rows = await retainedWorkspaceCandidates(db, passiveSweep ? passiveSweep.cursor : cursors.get(db), false, obligationsOnly, inFlightRunIds); + if (passiveSweep && !rows.length && passiveSweep.restart) { + Object.assign(passiveSweep, { cursor: undefined, restart: false }); + rows = await retainedWorkspaceCandidates(db, undefined, false, obligationsOnly, inFlightRunIds); } - if (!rows.length && !passiveSweep) rows = await retainedWorkspaceCandidates(db, undefined, false, obligationsOnly, inFlightRunIds); + if (passiveSweep) passiveSweep.complete = !rows.length; + else if (!rows.length) rows = await retainedWorkspaceCandidates(db, undefined, false, obligationsOnly, inFlightRunIds); + const sweep: CandidateLane = { rows, index: 0, + advance: id => { if (passiveSweep) passiveSweep.cursor = id; else cursors.set(db, id); } }; + const lanes = [unfinished]; + if (passiveSweep) { + // The due lane wraps at its tail like the unfinished lane. A hold that + // becomes due by time alone (a lease expiry, a re-arm backoff) is reached + // even after the obligation pass completed with no committed change. + let dueRows = await retainedWorkspaceCandidates(db, passiveSweep.dueCursor, false, true, inFlightRunIds, true); + if (!dueRows.length && passiveSweep.dueCursor) + dueRows = await retainedWorkspaceCandidates(db, undefined, false, true, inFlightRunIds, true); + const due: CandidateLane = { rows: dueRows, index: 0, advance: id => { passiveSweep.dueCursor = id; } }; + lanes.push(due, sweep); + // Priority rotates across all three lanes, so each lane is first in one + // run of three. With one free slot (a long local export holds the other), + // a save that keeps finding its run's lock busy cannot take it every run. + const first = (passiveSweep.firstLane ?? 0) % lanes.length; + lanes.push(...lanes.splice(0, first)); + passiveSweep.firstLane = (first + 1) % lanes.length; + } else lanes.push(sweep); const work: Promise[] = []; - let hasUnvisited = false; - const advance = (actionId: string) => { - if (unfinished) unfinishedCursors.set(db, actionId); - else if (passiveSweep) passiveSweep.cursor = actionId; - else cursors.set(db, actionId); - }; // Several actions of one run (an export hold and a later no-replay hold) // run one after another in that run's job. Skipping the later one would // starve it while the earlier one stays selectable (for example while saved // input waits for the later one to settle). const groups = new Map(); - for (const { action, run } of rows) { - const group = groups.get(run.id); - if (group) { group.actions.push(action); advance(action.id); continue; } - if (pending.size >= 2) { hasUnvisited = true; break; } - advance(action.id); - if (pending.has(run.id)) continue; - pending.add(run.id); - groups.set(run.id, { run, actions: [action] }); + const join = (lane: CandidateLane) => { + for (; lane.index < lane.rows.length; lane.index += 1) { + const { action, run } = lane.rows[lane.index]!; + const group = groups.get(run.id); + if (!group) return lane.rows[lane.index]!; + if (!group.actions.some(item => item.id === action.id)) group.actions.push(action); + lane.advance(action.id); + } + return undefined; + }; + // Takes the lane's next run into a free slot. Actions of a run already taken + // (by any lane) join its job without a slot. + const take = (lane: CandidateLane) => { + const next = join(lane); + if (!next || pending.size >= 2) return false; + lane.index += 1; + lane.advance(next.action.id); + pending.add(next.run.id); + groups.set(next.run.id, { run: next.run, actions: [next.action] }); + return true; + }; + for (let taken = true; taken && pending.size < 2;) { + taken = false; + for (const lane of lanes) if (pending.size < 2 && take(lane)) taken = true; } + for (const lane of lanes) join(lane); + const hasUnvisited = lanes.some(lane => lane.index < lane.rows.length); for (const { run, actions } of groups.values()) { const finish = beginIdleTrackedWork(); const physical = actions.some(action => ["scheduled", "running", "awaiting_evidence"].includes(readSystemRecovery(action.evidence)?.state ?? "")); From 08ff0828d6e3b3ca7cee734e65976331d6e40562 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 11 Nov 2026 00:12:41 -0600 Subject: [PATCH 37/38] fix(native): offer Retry at once when the Runner refuses a turn start on a closed session (#20729) 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 > - A native ACPX run (for example Claude) starts each turn with `turn.start`. When a start is cut off, the Runner reads the sidecar's dispatch journal (#20675). > - If the prompt never left, the Runner keeps the session reopenable, and the same-run resume sends the prompt once. If the prompt may have left, the Runner closes the session, because a resend could duplicate it. > - A closed session cannot reopen for the same run. Every same-run resume got `ACPX session is not open`. The server treated that as a generic interruption and spent three attempts (about 95 s) before the board offered Retry. > - This pull request gives that refusal a closed class in the Runner and a permanent, named failure code in the server. > - The benefit is that the board offers a working Retry on the first refusal, while every recoverable case keeps recovering by itself. ## Linked Issues or Issue Description **What happened?** Restart-chaos wave `w-20261111T011704-s9107`, task t05 (local, claude, workload C1, fault TM2). A freeze cut off a turn start, and the Runner saved the session `closed`. Three same-run resumes each failed with `PRP command turn.start failed: … "message":"ACPX session is not open"`. Recovery stopped with `native_session_retry_exhausted` at 01:25:14, and the board then offered Retry. The Retry run succeeded. **Expected behavior** When the Runner proves the session is closed for this run, the run stops at the first refusal with a named failure, and the board offers a Retry that works. A start that the Runner proved never reached the provider still recovers by itself. **Steps to reproduce** 1. `cd server && npx vitest run src/services/native-runtime/native-closed-session-retry.integration.test.ts` 2. On master, "offers Retry on the first refusal, and Retry starts a new run" fails: the coordinator is `retryable_failure` / `native_session_interrupted` (a same-run retry in 30 s). Refs #20675, #20720 ## What Changed - Runner (`durable/mod.rs`, `acpx_provider_backend.rs`): new closed class `provider_session_closed`. The Runner sets it on these refusals: - a turn start that saves the session `closed` (`ACPX turn start failed closed: …`), but not the rejected-checkpoint case, which stays `prepared` and reopens; - `ACPX session is not open` when the saved lifecycle is `closed` for this run; - the saved turn-end-restart refusal for this run (asserted in `acpx_turn_end_restart`). A session that waits for provider-exit proof can reopen after a restart. Its refusal gets no class. - Server (`native-session-executor.ts`): a `turn.start` failure with that class maps to the new permanent code `native_provider_session_closed`. The server reads the class from the authenticated command result, and from the command-failure text if the error was rewrapped. `nativeSessionFailureDisposition` treats the code as permanent, so the first refusal ends the run as `terminal_failure` with a board owner and a plain next action. - Docs: `packages/paperclip-runner/docs/durable-recovery.md` states the class and the older-Runner behavior. - Tests: - `native-closed-session-retry.integration.test.ts` (new, embedded Postgres) drives `executePaperclipNativeSession` with the Runner refusal. On the first refusal, the board shows `canRetry: true`. `requestTaskRetry` is accepted, and `resumeTaskRetry` starts exactly one new run with a fresh provider session. A start proved undispatched stays `retryable_failure`. - Unit tests in `native-session-executor.test.ts`: both closed refusals, a rewrapped error, an undispatched start, an unclassified older-Runner refusal, and a class on another command. - Rust `acpx_cut_turn_start`: a start cut off before dispatch has no class. A start cut off after dispatch, and the later refusal, carry `provider_session_closed`. ## Verification - Red on master, green here: step 1 above. - `npx vitest run src/services/native-runtime/native-session-executor.test.ts`: 1358/1358 pass. - `cargo test -p paperclip-runner-core --test acpx_park_preparation` (26 pass), `--lib acpx` (94 pass), `--test acpx_provider_turns --test acpx_provider_session --test acpx_warm_attachment` (all pass), `cargo fmt --check` clean. - `npx tsc --noEmit -p server/tsconfig.json`: clean. - Not run: a chaos wave. ## Risks - This changes the Rust Runner. Daytona needs a new runner image before remote runs get the class. Until then, an older Runner sends the refusal without the class, and the server keeps today's bounded same-run retries. That path is unchanged and ends with a working Retry. The server does not trust the text alone, because an older Runner sends the same text for a session that can still reopen. - The class is set only where the Runner's saved state proves that no later start of this run can reopen the session. A false class would cost one automatic resume and show Retry earlier. It never replays provider work. - No persisted shape changes. The class is an optional field of a failed command result. Old saved state resumes unchanged. Nothing new runs before `turn.start`. > 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 (Anthropic), model ID `claude-opus-5-5`, run in Claude Code with tool use (shell, file edit) and extended reasoning. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude --- .../paperclip-runner/docs/durable-recovery.md | 8 ++ .../runner-core/src/acpx_provider_backend.rs | 31 ++++- .../crates/runner-core/src/durable/mod.rs | 6 + .../tests/support/acpx_cut_turn_start.rs | 31 +++-- .../tests/support/acpx_turn_end_restart.rs | 10 +- ...e-closed-session-retry.integration.test.ts | 106 ++++++++++++++++++ .../native-session-executor.test.ts | 47 ++++++++ .../native-runtime/native-session-executor.ts | 36 +++++- 8 files changed, 255 insertions(+), 20 deletions(-) create mode 100644 server/src/services/native-runtime/native-closed-session-retry.integration.test.ts diff --git a/packages/paperclip-runner/docs/durable-recovery.md b/packages/paperclip-runner/docs/durable-recovery.md index 9b43063fd5c..4de69c15a29 100644 --- a/packages/paperclip-runner/docs/durable-recovery.md +++ b/packages/paperclip-runner/docs/durable-recovery.md @@ -143,6 +143,14 @@ which proves that the sidecar and the provider are gone. no file (an older sidecar) proves nothing. The earlier behavior applies unchanged: a failed start closes the session, and a killed Runner uses lost-turn recovery. +- A session this run closed cannot reopen for the same run. The failed start, + and every later `turn.start` of the run, fail with the closed class + `provider_session_closed` in the command result. The controller records + `native_provider_session_closed`, stops same-run retries, and the board offers + Retry at once. Retry starts a new run with a fresh provider conversation and + the saved task context. An older Runner sends the same text without the class; the + controller then keeps its bounded same-run retries, because the same text + also covers a session that can reopen after a restart. Until a proof settles it, the saved session stays `turn_starting`, so a Runner killed during the proof restores through the same check. The cut-off command is diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs index f15147c4664..7b610e1572f 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs @@ -28,7 +28,8 @@ use crate::durable::QualifiedLaunchArtifact; use crate::durable::{ create_private_temporary_file, open_private_regular_file, verify_private_directory, AcpxLaunchProfile, Command, CommandExecution, CommandExecutor, DurableRunnerConfig, - DurableRunnerError, EventPriority, PolledEvent, PROVIDER_STATE_INCOMPATIBLE, + DurableRunnerError, EventPriority, PolledEvent, PROVIDER_SESSION_CLOSED, + PROVIDER_STATE_INCOMPATIBLE, }; use crate::generated_acpx_sidecar_contract::GeneratedAcpxSidecarCommand; use crate::process_supervisor::{VerifiedProcessArgument, VerifiedProcessLaunch}; @@ -2061,7 +2062,8 @@ impl AcpxCommandExecutor { DurableRunnerError::invalid(format!("ACPX turn start failed closed: {error}")) } None => DurableRunnerError::invalid("ACPX session is not open"), - }); + } + .with_classification(PROVIDER_SESSION_CLOSED)); } let reopenable = self.session.is_none() && self.state.as_ref().is_some_and(|state| { @@ -2128,7 +2130,17 @@ impl AcpxCommandExecutor { self.retain_buffered_provider_events()?; } if self.session.is_none() { - return Err(DurableRunnerError::invalid("ACPX session is not open")); + let error = DurableRunnerError::invalid("ACPX session is not open"); + // Only a session this run closed is permanently closed for it. A + // session awaiting provider-exit proof can reopen after a restart. + let closed_for_run = self.state.as_ref().is_some_and(|state| { + state.lifecycle == "closed" && state.descriptor.run_id == self.context.run_id + }); + return Err(if closed_for_run { + error.with_classification(PROVIDER_SESSION_CLOSED) + } else { + error + }); } let (provider_process_will_be_replaced, previous_process_id) = self .session @@ -2206,6 +2218,7 @@ impl AcpxCommandExecutor { } .to_owned(); state.provider_exit_unconfirmed = rejected_checkpoint.is_some(); + let rejected_checkpoint_reopenable = rejected_checkpoint.is_some(); state.active_turn_id = None; self.context.provider_turn_id = None; self.session = None; @@ -2225,9 +2238,15 @@ impl AcpxCommandExecutor { return Err(error); } } - return Err(DurableRunnerError::invalid(format!( - "ACPX turn start failed closed: {error}" - ))); + let failure = + DurableRunnerError::invalid(format!("ACPX turn start failed closed: {error}")); + // A rejected checkpoint stays `prepared` and reopens on the next + // start. A `closed` session cannot reopen for this run. + return Err(if rejected_checkpoint_reopenable { + failure + } else { + failure.with_classification(PROVIDER_SESSION_CLOSED) + }); } // Copy numeric timing fields only. Sidecar contents never enter the receipt. let timing = if measure { diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/durable/mod.rs b/packages/paperclip-runner/runner/crates/runner-core/src/durable/mod.rs index b58e953a2a4..adaca2067c3 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/durable/mod.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/durable/mod.rs @@ -51,6 +51,12 @@ pub const PROVIDER_ATTACH_REFUSED: &str = "provider_attach_refused"; /// recorded result. Replacing the session could repeat or lose that action. pub const PROVIDER_SIDE_EFFECT_PENDING: &str = "provider_side_effect_pending"; +/// The runner closed this run's provider session after a turn start whose +/// prompt may have reached the provider. No later `turn.start` of the same run +/// can reopen it; only a new run's attachment can. Resending could duplicate +/// the prompt, so the controller stops same-run retries and offers Retry. +pub const PROVIDER_SESSION_CLOSED: &str = "provider_session_closed"; + #[derive(Clone, Debug, PartialEq, Eq)] pub struct DurableRunnerError(String, Option, Option<&'static str>); diff --git a/packages/paperclip-runner/runner/crates/runner-core/tests/support/acpx_cut_turn_start.rs b/packages/paperclip-runner/runner/crates/runner-core/tests/support/acpx_cut_turn_start.rs index 98de3ed7735..5c0f5dccb8f 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/tests/support/acpx_cut_turn_start.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/tests/support/acpx_cut_turn_start.rs @@ -3,6 +3,7 @@ //! journal decides whether the prompt could have reached the provider. use super::*; +use paperclip_runner_core::durable::PROVIDER_SESSION_CLOSED; const JOURNAL: &str = "paperclip-turn-dispatch.jsonl"; @@ -27,8 +28,14 @@ fn kill(pid: &Value) { } /// Starts `turn` against a sidecar that freezes at `fault`, then kills the -/// sidecar once the journal shows `phases`, and returns the start's error. -fn cut_turn_start(harness: &mut Harness, turn: &str, fault: &str, phases: &[&str]) -> String { +/// sidecar once the journal shows `phases`, and returns the start's error and +/// its closed classification. +fn cut_turn_start( + harness: &mut Harness, + turn: &str, + fault: &str, + phases: &[&str], +) -> (String, Option<&'static str>) { harness.fixture.fault(fault); let sidecar = harness.fixture.process_starts().last().unwrap()["processStart"].clone(); let root = harness.fixture.0.clone(); @@ -68,21 +75,23 @@ fn cut_turn_start(harness: &mut Harness, turn: &str, fault: &str, phases: &[&str "turn.start", json!({"turnId": turn, "text": "Write the brief."}), )) - .unwrap_err() - .to_string(); + .unwrap_err(); killer.join().unwrap(); harness.fixture.fault(""); - error + (error.to_string(), error.classification()) } #[test] fn a_start_cut_off_before_the_prompt_left_reopens_and_sends_the_prompt_once() { let mut harness = Harness::new(); - let error = cut_turn_start(&mut harness, "cut", "hang-before-dispatch", &["received"]); + let (error, classification) = + cut_turn_start(&mut harness, "cut", "hang-before-dispatch", &["received"]); assert!( error.contains("before its prompt reached the provider"), "{error}" ); + // The run recovers by itself: the controller must keep retrying it. + assert_eq!(classification, None); let saved = harness.fixture.state(); assert_eq!(saved["lifecycle"], "prepared", "{saved}"); assert_eq!(saved["activeTurnId"], Value::Null); @@ -107,13 +116,15 @@ fn a_start_cut_off_before_the_prompt_left_reopens_and_sends_the_prompt_once() { #[test] fn a_start_cut_off_after_the_prompt_left_stays_closed_and_never_resends() { let mut harness = Harness::new(); - let error = cut_turn_start( + let (error, classification) = cut_turn_start( &mut harness, "cut", "hang-after-dispatch", &["received", "dispatched"], ); assert!(error.contains("failed closed"), "{error}"); + // No later start of this run can reopen it: the controller offers Retry at once. + assert_eq!(classification, Some(PROVIDER_SESSION_CLOSED)); assert_eq!(harness.fixture.state()["lifecycle"], "closed"); let starts = harness.fixture.process_starts().len(); harness.sequence += 1; @@ -124,9 +135,9 @@ fn a_start_cut_off_after_the_prompt_left_stays_closed_and_never_resends() { "turn.start", json!({"turnId": "resent", "text": "Write the brief."}), )) - .unwrap_err() - .to_string(); - assert_eq!(refused, "ACPX session is not open"); + .unwrap_err(); + assert_eq!(refused.to_string(), "ACPX session is not open"); + assert_eq!(refused.classification(), Some(PROVIDER_SESSION_CLOSED)); assert_eq!(harness.fixture.process_starts().len(), starts); } diff --git a/packages/paperclip-runner/runner/crates/runner-core/tests/support/acpx_turn_end_restart.rs b/packages/paperclip-runner/runner/crates/runner-core/tests/support/acpx_turn_end_restart.rs index 6671c6b3106..d0aaa7df97f 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/tests/support/acpx_turn_end_restart.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/tests/support/acpx_turn_end_restart.rs @@ -437,9 +437,13 @@ fn a_runner_restart_in_the_same_run_keeps_the_failed_turn_end_restart_closed() { "turn.start", json!({"turnId": "second", "text": "Complete the work."}), )) - .unwrap_err() - .to_string(); - assert_eq!(failed, "ACPX session is not open"); + .unwrap_err(); + assert_eq!(failed.to_string(), "ACPX session is not open"); + // No same-run start can reopen it: the controller offers Retry at once. + assert_eq!( + failed.classification(), + Some(paperclip_runner_core::durable::PROVIDER_SESSION_CLOSED) + ); assert_eq!(harness.fixture.process_starts().len(), starts); // Neither session.open nor a same-run attach reopens it. let reopened = harness diff --git a/server/src/services/native-runtime/native-closed-session-retry.integration.test.ts b/server/src/services/native-runtime/native-closed-session-retry.integration.test.ts new file mode 100644 index 00000000000..07dc92bdde8 --- /dev/null +++ b/server/src/services/native-runtime/native-closed-session-retry.integration.test.ts @@ -0,0 +1,106 @@ +import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { agents, companies, companyMemberships, completionContracts, createDb, heartbeatRuns, issues, nativeRunFinalizations } from "@paperclipai/db"; +import type { NativeExecutionInputV1 } from "@paperclipai/paperclip-runner"; +import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; + +const provider = vi.hoisted(() => ({ execute: vi.fn() })); +vi.mock("../../vendor/paperclip-runner/index.js", async (importOriginal) => ({ + ...(await importOriginal()), + executeNativeSession: provider.execute, +})); + +import { executePaperclipNativeSession, NATIVE_PROVIDER_SESSION_CLOSED } from "./native-session-executor.js"; +import { buildNativeCompletionContract } from "./completion-contracts.js"; +import { prepareNativeHeartbeatRun } from "./prepare-native-run.js"; +import { heartbeatService } from "../heartbeat.js"; +import { requestTaskRetry } from "../task-retry.js"; +import { taskInterruptionPresentation } from "../task-interruption-presentation.js"; + +// Chaos w-20261111T011704-s9107/t05 (claude, TM2): a cut-off ACPX turn start +// left this run's session closed with the prompt possibly sent. Every same-run +// resume got "ACPX session is not open"; the board offered Retry only after +// three attempts (about 95 s). The Runner now classifies that refusal, and +// Retry starts a new run with a fresh provider session. +describe("native turn start refused on a closed provider session", () => { + let temporary: Awaited>; + let db: ReturnType; + const companyId = randomUUID(); + const agentId = randomUUID(); + + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("native-closed-session-"); + db = createDb(temporary.connectionString); + await db.insert(companies).values({ id: companyId, name: "Closed session", issuePrefix: "NCS" }); + await db.insert(agents).values({ id: agentId, companyId, name: "Claude agent", status: "active", adapterType: "paperclip_runner", + adapterConfig: { provider: "acpx", agent: "claude", model: "claude-test" } }); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "board-user", status: "active", membershipRole: "member" }); + }); + afterAll(async () => { await temporary?.cleanup(); }); + + const refusal = (result: Record) => { + const commandResult = { commandId: "command_lab_1", commandType: "turn.start", controllerSeq: 10, result, status: "failed" }; + return Object.defineProperty(new Error(`PRP command turn.start failed: ${JSON.stringify(commandResult)}`), + "runnerCommandResult", { value: commandResult, enumerable: false }); + }; + + async function refuseTurnStart(failure: Error) { + const issueId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Write the brief", status: "in_progress", workMode: "standard", + assigneeAgentId: agentId, createdByUserId: "board-user", responsibleUserId: "board-user" }); + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + const runId = randomUUID(); + const [run] = await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", runtimeMode: "native", + nativeIssueId: issueId, responsibleUserId: "board-user", invocationSource: "automation", triggerDetail: "system", + contextSnapshot: { issueId } }).returning(); + await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId)); + const native = await prepareNativeHeartbeatRun({ db, run, issue, environmentLeaseId: randomUUID() }); + const [contract] = await db.select().from(completionContracts).where(eq(completionContracts.issueId, issueId)); + await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "observed" }); + const execution: NativeExecutionInputV1 = { + schema: "paperclip.native-execution-input.v1", + binding: { companyId, runId, issueId, agentId, executionWorkspaceId: runId }, + provider: { kind: "opencode", model: "openrouter/test-model" }, + task: { identifier: issueId, title: issue.title, description: null, prompt: "Write the brief.", workMode: "standard" }, + workspace: { cwd: "/tmp", repoUrl: null, repoRef: null, branchName: null }, + session: { normalizedSessionId: native.normalizedSessionId, driverKind: "opencode_server", protocolVersion: 1, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } }, + completionContract: { id: contract.id, sha256: contract.canonicalSha256, schemaVersion: "paperclip.completion-contract.v1", + contract: buildNativeCompletionContract(issue, { revision: contract.revision }) }, + interactionResponses: [], credentialBindings: [], + }; + // An established provider session: same-run resume is the ordinary recovery. + await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: execution, + sessionCheckpoint: { backendKind: "mock", providerSessionId: "claude-session" } } }).where(eq(heartbeatRuns.id, runId)); + provider.execute.mockReset().mockRejectedValue(failure); + await executePaperclipNativeSession({ db, execution, runnerInstanceId: native.runnerInstanceId, backend: { + descriptor: async () => { throw new Error("Unexpected provider call"); }, + openSession: async () => { throw new Error("Unexpected provider call"); }, + } }).catch(() => undefined); + const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)); + return { issueId, runId, coordinator }; + } + + it("offers Retry on the first refusal, and Retry starts a new run", async () => { + const { issueId, runId, coordinator } = await refuseTurnStart(refusal({ code: "command_execution_failed", + message: "ACPX session is not open", classification: "provider_session_closed" })); + expect(coordinator).toMatchObject({ phase: "terminal_failure", failureCode: NATIVE_PROVIDER_SESSION_CLOSED, nextAttemptAt: null }); + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + await expect(taskInterruptionPresentation(db, issue)).resolves.toMatchObject({ state: "failed", canRetry: true }); + const receipt = await requestTaskRetry({ db, companyId, issueId, actorId: "board-user", actorSource: "session", + idempotencyKey: randomUUID(), observedRunId: runId }); + expect(receipt).toMatchObject({ accepted: true, stale: false }); + const heartbeat = heartbeatService(db); + await heartbeat.resumeTaskRetry(companyId, receipt.requestId!); + const retried = (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId))) + .filter(r => r.contextSnapshot?.issueId === issueId && r.contextSnapshot?.taskRetryRequestId === receipt.requestId); + expect(retried).toHaveLength(1); + await heartbeat.drainActiveRunExecutions(); + }, 120_000); + + it("keeps a same-run retry when the Runner proved the prompt never left", async () => { + const { coordinator } = await refuseTurnStart(refusal({ code: "command_execution_failed", + message: "ACPX turn start failed before its prompt reached the provider: ACPX sidecar request timed out at turn.start" })); + expect(coordinator).toMatchObject({ phase: "retryable_failure", failureCode: "native_session_interrupted" }); + }, 120_000); +}); diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index 29669b434ca..e37262c5b72 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -429,6 +429,7 @@ import { retainedNativeCleanupJournalMatches, nativeProviderUsageLimitFromEvent, nativeSessionFailureSourceCode, + NATIVE_PROVIDER_SESSION_CLOSED, nativeSessionRecoveryProjection, nativeGovernedWaitResult, nativeConversationReplyResult, @@ -13976,6 +13977,52 @@ describe("native session bounded recovery", () => { expect(nativeSessionFailureSourceCode(new Error(failure.message))).toBe("native_session_interrupted"); }); + // Chaos w-20261111T011704-s9107/t05: after a cut-off ACPX turn start the + // Runner saved the session closed; three same-run resumes each got the same + // refusal before the board offered Retry. + describe("a turn start the Runner refused because this run's session is closed", () => { + const turnStartFailure = (result: Record) => { + const commandResult = { commandId: "command_lab_1", commandType: "turn.start", controllerSeq: 10, result, status: "failed" }; + return Object.defineProperty(new Error(`PRP command turn.start failed: ${JSON.stringify(commandResult)}`), + "runnerCommandResult", { value: commandResult, enumerable: false }); + }; + const closed = (message: string) => turnStartFailure({ code: "command_execution_failed", message, + classification: "provider_session_closed" }); + + it.each(["ACPX session is not open", "ACPX turn start failed closed: ACPX sidecar request timed out at turn.start"])( + "stops on the first refusal and hands the run to the board: %s", (message) => { + const code = nativeSessionFailureSourceCode(closed(message)); + expect(code).toBe(NATIVE_PROVIDER_SESSION_CLOSED); + const disposition = nativeSessionFailureDisposition(1, new Date(), code); + expect(disposition).toEqual({ phase: "terminal_failure", failureCode: NATIVE_PROVIDER_SESSION_CLOSED, nextAttemptAt: null }); + expect(nativeSessionRecoveryProjection({ ...disposition, agentId: "agent" })).toMatchObject({ + issueStatus: "blocked", recoveryOwner: { kind: "board" }, + }); + // A rewrapped failure keeps the class through its authenticated text. + expect(nativeSessionFailureSourceCode(new Error(closed(message).message))).toBe(NATIVE_PROVIDER_SESSION_CLOSED); + expect(nativeSessionFailureSourceCode(Object.assign(new Error("native session failed"), { cause: closed(message) }))) + .toBe(NATIVE_PROVIDER_SESSION_CLOSED); + }); + + it("keeps retrying a start the Runner proved never reached the provider", () => { + const failure = turnStartFailure({ code: "command_execution_failed", + message: "ACPX turn start failed before its prompt reached the provider: ACPX sidecar request timed out at turn.start" }); + expect(nativeSessionFailureSourceCode(failure)).toBe("native_session_interrupted"); + expect(nativeSessionFailureDisposition(1, new Date(), "native_session_interrupted").phase).toBe("retryable_failure"); + }); + + it("keeps today's same-run retries for an unclassified refusal from an older Runner", () => { + // An older Runner sends the same text for a session that can reopen after + // a restart (provider exit not yet proven), so the text alone proves nothing. + const failure = turnStartFailure({ code: "command_execution_failed", message: "ACPX session is not open" }); + expect(nativeSessionFailureSourceCode(failure)).toBe("native_session_interrupted"); + // Another command's class is not a turn-start refusal. + const other = Object.defineProperty(new Error("PRP command session.open failed"), "runnerCommandResult", + { value: { commandType: "session.open", result: { classification: "provider_session_closed" } }, enumerable: false }); + expect(nativeSessionFailureSourceCode(other)).not.toBe(NATIVE_PROVIDER_SESSION_CLOSED); + }); + }); + it("stops same-run retries for an operator while a saved side-effecting call has no result", () => { const failure = new NativeProviderSideEffectPendingError( "Error: native_runner_source_semantic_reconciliation_required", diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index ac9a832446a..fff7e2b6e6f 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -8312,7 +8312,8 @@ export function nativeSessionFailureDisposition( sourceFailureCode === NATIVE_CURRENT_WAKE_COMMENTS_CHANGED_AFTER_READ || sourceFailureCode === "native_session_cleanup_quarantined" || sourceFailureCode === "native_adopted_runner_authentication_timeout" || - sourceFailureCode === "native_provider_usage_limit"; + sourceFailureCode === "native_provider_usage_limit" || + sourceFailureCode === NATIVE_PROVIDER_SESSION_CLOSED; const permissionDeclined = sourceFailureCode === "native_permission_declined"; const exhausted = permanentFailure || permissionDeclined || attempt >= 3; return { @@ -8353,6 +8354,33 @@ export function nativeSessionRecoveryProjection(input: { }; } +/** + * The Runner closed this run's provider session after a turn start whose prompt + * may have reached the provider. Every later same-run `turn.start` is refused + * the same way, and resending could duplicate the prompt, so the run stops and + * the board offers Retry (a new run with a fresh provider session). A start the + * Runner proved never dispatched is not classified and still retries. + */ +export const NATIVE_PROVIDER_SESSION_CLOSED = "native_provider_session_closed"; +export const NATIVE_PROVIDER_SESSION_CLOSED_ACTION = + "The provider session closed after a turn start that may have reached the provider, and this run cannot reopen it. Retry starts a new run with a fresh provider conversation and the saved task context."; +const RUNNER_PROVIDER_SESSION_CLOSED = "provider_session_closed"; + +/** Reads the Runner's closed class from an authenticated turn.start failure. */ +function runnerClosedTurnStartSession(error: unknown, depth = 0): boolean { + if (!error || typeof error !== "object" || depth > 5) return false; + const value = error as Record; + const result = record(value.runnerCommandResult); + if (result.commandType === "turn.start" && record(result.result).classification === RUNNER_PROVIDER_SESSION_CLOSED) { + return true; + } + // The structured result can be lost when the failure is rewrapped; the + // authenticated command failure text carries the same closed class. + const message = error instanceof Error ? error.message : ""; + if (/\bPRP command turn\.start failed: \{.*"classification":"provider_session_closed"/.test(message)) return true; + return runnerClosedTurnStartSession(value.cause, depth + 1); +} + export function nativeSessionFailureSourceCode( error: unknown, ): @@ -8363,6 +8391,7 @@ export function nativeSessionFailureSourceCode( | typeof NATIVE_PROVIDER_SIDE_EFFECT_PENDING | "native_provider_approval_required" | "native_provider_usage_limit" + | typeof NATIVE_PROVIDER_SESSION_CLOSED | "native_session_cleanup_quarantined" | "native_adopted_runner_authentication_timeout" | "runner_remote_provider_artifact_incompatible" @@ -8424,6 +8453,7 @@ export function nativeSessionFailureSourceCode( return error.failure.httpStatus === 401 || error.failure.httpStatus === 403 ? "runner_ingress_access_rejected" : "runner_ingress_acquisition_failed"; } + if (runnerClosedTurnStartSession(error)) return NATIVE_PROVIDER_SESSION_CLOSED; const message = error instanceof Error ? error.message : String(error); if (/classification=runtime_package_missing\)/.test(message)) return "native_provider_runtime_missing"; @@ -12261,6 +12291,8 @@ async function executePaperclipNativeSessionAttempt( ? "Provider permission was declined. Inspect the task and give explicit direction before starting further provider work. Automatic recovery is stopped." : sourceFailureCode === "native_provider_approval_required" ? "Approval required. Review the operation and update the agent's permission setting before retrying. This runner has no interactive approval handler." + : sourceFailureCode === NATIVE_PROVIDER_SESSION_CLOSED + ? NATIVE_PROVIDER_SESSION_CLOSED_ACTION : sourceFailureCode === "native_session_cleanup_quarantined" ? nativeCleanupRefusalAction(completedTurnCleanup) : sourceFailureCode === "runner_remote_provider_verification_unavailable" @@ -12530,6 +12562,8 @@ async function executePaperclipNativeSessionAttempt( ? "Provider permission was declined. Inspect the task and give explicit direction before starting further provider work. Automatic recovery is stopped." : sourceFailureCode === "native_provider_approval_required" ? "Approval required. Review the operation and update the agent's permission setting before retrying. This runner has no interactive approval handler." + : sourceFailureCode === NATIVE_PROVIDER_SESSION_CLOSED + ? NATIVE_PROVIDER_SESSION_CLOSED_ACTION : sourceFailureCode === "native_session_cleanup_quarantined" ? nativeCleanupRefusalAction(completedTurnCleanup) : sourceFailureCode === "runner_ingress_access_rejected" From 94c7c83ce8af7a03fd6cbda62846890e48480fda Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 11 Nov 2026 00:14:03 -0600 Subject: [PATCH 38/38] fix(runner): refuse a moved-root same-session checkpoint by name (#20723) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Native runs on a remote sandbox resume a task's provider session from a saved checkpoint > - #20712 made a checkpoint that names an abandoned remote workspace root decline recovery, so a replacement session opens in the new root > - A checkpoint that requires the same session (an unfinished goal, `same_session_only`) cannot be replaced. It then failed with the generic `native_session_recovery_failed`, which recovery treats as a retryable interruption > - A retry cannot move a saved session to another root, so the failure repeats. The upgrade-safe rule requires a permanent, named code for this case > - Also, the working-directory errors said "Codex" on Claude and other ACPX runs, because one app-server driver serves all of them > - This pull request reports the moved root as provider state that is incompatible, and makes the errors name the agent generically > - The benefit is a named, permanent refusal with a working board Retry, and error text that is correct for every agent ## Linked Issues or Issue Description Refs #20712 **What happened?** After #20712, a `same_session_only` checkpoint with a moved remote root ended with `native_session_recovery_failed: persisted session working directory is not the assigned remote workspace`. That is not a named permanent code, so recovery could retry a run that cannot succeed. On ACPX Claude runs, path errors read "Remote Codex working directory ...". **Expected behavior** The run ends with the permanent code `native_provider_state_incompatible`. Automatic retries stop. A board Retry continues the task in a fresh provider session in the same workspace. Errors do not name Codex on other agents. **Steps to reproduce** 1. Save a native checkpoint with `providerRecoveryPolicy: same_session_only` under one remote workspace root. 2. Assign the run a different sibling root (the epoch was abandoned). 3. Resume the run. ## What Changed - `codex-app-server-driver-impl.ts`: the moved-root decline from #20712 now carries `failureClass: provider_state_incompatible`. The runtime already maps that class: - checkpoint allows replacement (`allow_replacement_after_resume_failure`): a replacement session opens in the assigned root, as before; - checkpoint requires the same session: `NativeProviderStateIncompatibleError`, code `native_provider_state_incompatible`. - The server already treats `native_provider_state_incompatible` as a permanent failure (no automatic retry, board action text "Retry the task to continue in a fresh provider session with the same workspace"). `rebindNativeSessionCheckpoint` returns no checkpoint after that code, so a board Retry starts a fresh session in the same workspace. No server change is needed. - A moved-root checkpoint with an active turn or a pending runtime request now reports `provider_side_effect_pending`. The runtime never replaces it under any policy, and the run ends with the permanent code `native_provider_side_effect_pending` for an operator to reconcile. Before, it threw the working-directory refusal, which recovery recorded as the retryable `native_session_interrupted`. - `harness-driver.ts`: the `PROVIDER_STATE_INCOMPATIBLE` doc now names the moved-workspace case. - `codex-boundaries.ts`: working-directory errors say "Agent working directory", "Remote agent working directory" and "Provider thread response" instead of "Codex". Tests updated to the new text. - Tests: - `native-session-runtime.test.ts`: the real app-server backend with `remote_runner` authority and a moved root, for each recovery policy. Same-session policies end with `native_provider_state_incompatible`, the replacement policy opens a replacement in the assigned root, an in-flight turn ends with `native_provider_side_effect_pending` under every policy, and no transport starts. - `native-backend-factory.test.ts`: the decline carries the failure class, and an ACPX Claude refusal reads "Remote agent working directory does not match the assigned workspace". Previous-release story: no persisted shape changes. Saved checkpoints are classified at recovery time. A saved same-session checkpoint under an old root now ends with the named permanent code instead of a generic one. ## Verification - Red: without the failure classes, the same-session and in-flight runtime cases fail (generic `native_session_recovery_failed`). Before the rename, the ACPX Claude message test fails. - Green: `cd packages/paperclip-runner && npx vitest run src/backends src/drivers/codex src/live/runner-prepared-launch-workspace.test.ts src/native-session-runtime.test.ts` passes (784 tests). - `npx tsc --noEmit -p packages/paperclip-runner` passes. - Existing server coverage for the code: `native-session-resume.test.ts` (no rebind after `native_provider_state_incompatible`) and `native-session-executor.test.ts` (source-code mapping). ## Risks - Low. Error message text changes. A search found no code that matches on the old text outside the updated tests. - Same-session checkpoints with a moved root now stop for a board Retry instead of a generic interruption. That is the intended behavior: a retry cannot succeed. > 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, used through Claude Code with tool use (shell, file edit, test execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] 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 --- .../paperclip-runner/docs/durable-recovery.md | 10 +++ .../backends/native-backend-factory.test.ts | 43 ++++++++++--- .../src/contracts/harness-driver.ts | 4 +- .../codex/codex-app-server-driver-impl.ts | 35 ++++++++--- .../codex-app-server-driver.recovery.test.ts | 2 +- .../src/drivers/codex/codex-boundaries.ts | 34 +++++------ .../runner-prepared-launch-workspace.test.ts | 2 +- .../src/native-session-runtime.test.ts | 61 +++++++++++++++++++ .../native-runtime/native-session-executor.ts | 2 +- 9 files changed, 154 insertions(+), 39 deletions(-) diff --git a/packages/paperclip-runner/docs/durable-recovery.md b/packages/paperclip-runner/docs/durable-recovery.md index 4de69c15a29..5d021ed8172 100644 --- a/packages/paperclip-runner/docs/durable-recovery.md +++ b/packages/paperclip-runner/docs/durable-recovery.md @@ -227,6 +227,16 @@ protected launch argument fails with the closed classification controller never opens a replacement session after either class, whatever the checkpoint's recovery policy, and stops the run for an operator. +A remote session whose saved working directory is not the run's assigned +workspace root (its workspace epoch was abandoned, so the saved version was +restored into a new root) cannot resume there. The driver declines it before +any Runner or provider process starts. An idle session reports +`provider_state_incompatible`: a replacement opens in the assigned root when the +checkpoint allows it, and otherwise the run fails with +`native_provider_state_incompatible`. A session with an unfinished provider turn +or a pending runtime request reports `provider_side_effect_pending` and stops +for an operator, whatever its recovery policy. + A restart can kill the runner after it journaled a run's own cold `run.attach` and before the attachment finished. The restored runner settles that command as `execution_indeterminate` and never executes it again. When the journal shows no diff --git a/packages/paperclip-runner/src/backends/native-backend-factory.test.ts b/packages/paperclip-runner/src/backends/native-backend-factory.test.ts index afaadd9defa..134c048e310 100644 --- a/packages/paperclip-runner/src/backends/native-backend-factory.test.ts +++ b/packages/paperclip-runner/src/backends/native-backend-factory.test.ts @@ -32,6 +32,7 @@ import { WORKSPACE, } from "../drivers/codex/codex-app-server-driver.test-support.js"; import { createNativeSessionBackend } from "../index.js"; +import { PROVIDER_SIDE_EFFECT_PENDING, PROVIDER_STATE_INCOMPATIBLE } from "../contracts/harness-driver.js"; import { createCodexNativeSessionBackend, createRunnerdNativeSessionBackend } from "./codex-native-backend.js"; import { createOpenCodeNativeSessionBackend } from "./opencode-native-backend.js"; @@ -409,9 +410,11 @@ describe("native backend factory", () => { // An abandoned remote workspace epoch is restored into a new sibling root // under `.paperclip-workspaces`, while the follow-up inherits a checkpoint - // that names the old root. Resume there is impossible, but it is an ordinary - // resume failure: the runtime's replacement policy must decide, not a thrown - // admission error that ends the run as native_session_interrupted. + // that names the old root. Resume there is impossible, and retrying cannot + // move the saved session: the runner reports provider state incompatible. + // The runtime then replaces the session when the checkpoint allows it, and + // otherwise ends the run with the permanent named code + // native_provider_state_incompatible, never a generic retryable failure. it.each([ ["Codex", execution()], ["ACPX Claude", acpxExecution("claude")], @@ -421,6 +424,7 @@ describe("native backend factory", () => { expect(recovered).toEqual({ recovered: false, reason: "persisted session working directory is not the assigned remote workspace", + failureClass: PROVIDER_STATE_INCOMPATIBLE, }); // No Runner or provider process is started for a session that cannot resume here. expect(factory).not.toHaveBeenCalled(); @@ -430,15 +434,38 @@ describe("native backend factory", () => { it.each([ ["an active turn", { activeTurnId: "turn-in-flight" }], ["a pending runtime request", { pendingRuntimeRequests: [{ requestId: "request-1" }] }], - ])("keeps refusing a moved-root session that holds %s", async (_label, inFlight) => { + ])("stops a moved-root session that holds %s for reconciliation, never replacing it", async (_label, inFlight) => { const { factory, backend, snapshot } = movedRootRecovery(acpxExecution("claude")); await expect(backend.recoverSession!({ ...snapshot, ...inFlight } as never, { signal: new AbortController().signal })) - .rejects.toThrow("Remote Codex working directory does not match the assigned workspace"); + .resolves.toEqual({ + recovered: false, + reason: "persisted session working directory is not the assigned remote workspace, and a provider turn or runtime request was in flight", + failureClass: PROVIDER_SIDE_EFFECT_PENDING, + }); + expect(factory).not.toHaveBeenCalled(); + }); + + it("treats a moved-root active turn that already has a terminal record as finished", async () => { + const { factory, backend, snapshot } = movedRootRecovery(acpxExecution("claude")); + await expect(backend.recoverSession!({ ...snapshot, activeTurnId: "turn-1", + terminalTurns: [{ turnId: "turn-1", fingerprint: "{\"status\":\"completed\"}" }] } as never, { signal: new AbortController().signal })) + .resolves.toMatchObject({ recovered: false, failureClass: PROVIDER_STATE_INCOMPATIBLE }); + expect(factory).not.toHaveBeenCalled(); + }); + + it("names the agent generically when a remote Claude session opens outside its workspace", async () => { + const { factory, backend } = movedRootRecovery(acpxExecution("claude")); + const failure = await backend.openSession({ + identity: { runId: "run", sessionId: "session", companyId: "company", issueId: "issue", agentId: "agent" }, + workingDirectory: "/home/daytona/paperclip-workspace/.paperclip-workspaces/elsewhere", + }).catch((error: unknown) => error); + // A Claude run must not be told its working directory is a Codex one. + expect((failure as Error).message).toBe("Remote agent working directory does not match the assigned workspace"); expect(factory).not.toHaveBeenCalled(); }); it.each([ - ["a filesystem root", "/", "Codex working directory cannot be a filesystem root"], + ["a filesystem root", "/", "Agent working directory cannot be a filesystem root"], ["an unnormalized path", "/home/daytona/../root", "normalized absolute path"], ])("keeps refusing a saved session whose working directory is %s", async (_label, workingDirectory, message) => { const { factory, backend, snapshot } = movedRootRecovery(acpxExecution("claude")); @@ -533,7 +560,7 @@ describe("native backend factory", () => { it.each([ ["thread read", { read: "/projects/other", resume: "/home/agent", reason: "provider read a different working directory" }], - ["thread resume", { read: "/home/agent", resume: "/projects/other", reason: "Error: Codex thread response changed the assigned working directory" }], + ["thread resume", { read: "/home/agent", resume: "/projects/other", reason: "Error: Provider thread response changed the assigned working directory" }], ])("does not recover when the %s reports another cwd", async (_label, cwds) => { const transport = new PreparedLaunchTransport(cwds.resume); transport.readResponse = { thread: { id: transport.threadId, sessionId: transport.providerSessionId, cwd: cwds.read, turns: [] } }; @@ -552,7 +579,7 @@ describe("native backend factory", () => { codexTransportFactory: () => new PreparedLaunchTransport("/home/agent"), workingDirectoryAuthority: "remote_runner", environment: {}, }); await expect(backend.openSession({ identity, workingDirectory: "/home/agent" })) - .rejects.toThrow("Remote Codex working directory requires an assigned workspace"); + .rejects.toThrow("Remote agent working directory requires an assigned workspace"); }); it("does not allow prepared launch authority without runnerd", () => { diff --git a/packages/paperclip-runner/src/contracts/harness-driver.ts b/packages/paperclip-runner/src/contracts/harness-driver.ts index 7be7eccfc9a..406523d3b5f 100644 --- a/packages/paperclip-runner/src/contracts/harness-driver.ts +++ b/packages/paperclip-runner/src/contracts/harness-driver.ts @@ -498,7 +498,9 @@ export interface PersistedHarnessSession { } /** Runner proof that saved provider state cannot be restored by this runner - * build. Restoring the same state again fails the same way. */ + * build, or in the workspace assigned to this run (for example, a remote + * workspace root that moved after its epoch was abandoned). Restoring the same + * state again fails the same way. */ export const PROVIDER_STATE_INCOMPATIBLE = "provider_state_incompatible"; /** Runner refused to attach a new run to the saved session (for example, a * protected launch argument or the durable provider profile would change). diff --git a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts index 52641c405ed..a006348de21 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver-impl.ts @@ -20,7 +20,7 @@ import type { PersistedHarnessTurnTerminal, } from "../../contracts/harness-driver.js"; import { NativeSessionProtocolIntegrityError, nativeRestartInterruptedTurnId } from "../../contracts/native-session-backend.js"; -import { HarnessReconciliationError, runnerRecoveryFailureClass } from "../../contracts/harness-driver.js"; +import { HarnessReconciliationError, PROVIDER_SIDE_EFFECT_PENDING, PROVIDER_STATE_INCOMPATIBLE, runnerRecoveryFailureClass } from "../../contracts/harness-driver.js"; import { CODEX_CODEX_PROTOCOL_VERSION, CODEX_SKILLLESS_BASE_INSTRUCTIONS, @@ -400,20 +400,35 @@ export class CodexAppServerDriver implements HarnessDriver { // in the newly assigned root. When it holds no in-flight turn or runtime // request (a follow-up's inherited checkpoint, for example), decline // before any Runner or provider process starts, so the runtime's recovery - // policy decides: a replacement in the assigned workspace, or a named - // refusal. In-flight provider work keeps the stricter admission refusal, - // because nothing here can prove its side effects settled. + // policy decides: a replacement in the assigned workspace, or the + // permanent named refusal when the checkpoint requires the same session. + // Retrying cannot move the saved session, so this is incompatible state, + // not a transient failure. A session with an in-flight turn or runtime + // request may have an external effect nothing here can prove settled, so + // it is never replaced: it stops by name for an operator to reconcile. if ( snapshot.workingDirectory && - !snapshot.activeTurnId && - !(snapshot.pendingRuntimeRequests?.length) && this.#options.workingDirectoryAuthority === "remote_runner" && remoteRunnerWorkingDirectoryMoved(snapshot.workingDirectory, this.#options.environment) ) { - return { - recovered: false, - reason: "persisted session working directory is not the assigned remote workspace", - }; + // A crash can save a turn's terminal record before clearing its active + // marker; that turn finished and is not in flight. + const activeTurnIsTerminal = (snapshot.terminalTurns ?? []).some( + (terminal) => terminal.turnId === snapshot.activeTurnId, + ); + const inFlight = (Boolean(snapshot.activeTurnId) && !activeTurnIsTerminal) + || Boolean(snapshot.pendingRuntimeRequests?.length); + return inFlight + ? { + recovered: false, + reason: "persisted session working directory is not the assigned remote workspace, and a provider turn or runtime request was in flight", + failureClass: PROVIDER_SIDE_EFFECT_PENDING, + } + : { + recovered: false, + reason: "persisted session working directory is not the assigned remote workspace", + failureClass: PROVIDER_STATE_INCOMPATIBLE, + }; } const transport = this.#transport({ workingDirectory: snapshot.workingDirectory diff --git a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.recovery.test.ts b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.recovery.test.ts index 8904234549d..845eec9d141 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.recovery.test.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-app-server-driver.recovery.test.ts @@ -550,7 +550,7 @@ describe("Codex app-server Codex driver", () => { await expect(driver.recoverSession?.(snapshot)).resolves.toEqual({ recovered: false, reason: expect.stringContaining( - "Codex working directory is outside the assigned workspace", + "Agent working directory is outside the assigned workspace", ), }); }); diff --git a/packages/paperclip-runner/src/drivers/codex/codex-boundaries.ts b/packages/paperclip-runner/src/drivers/codex/codex-boundaries.ts index cd36389978f..67039c32797 100644 --- a/packages/paperclip-runner/src/drivers/codex/codex-boundaries.ts +++ b/packages/paperclip-runner/src/drivers/codex/codex-boundaries.ts @@ -53,7 +53,7 @@ export function validateCodexWorkingDirectory( authority: CodexWorkingDirectoryAuthority = "local_filesystem", ): string { if (workingDirectory.trim().length === 0) { - throw new Error("Codex working directory is required"); + throw new Error("Agent working directory is required"); } if (authority === "remote_runner") { return validateRemoteRunnerWorkingDirectory(workingDirectory, environment); @@ -66,24 +66,24 @@ export function validateCodexWorkingDirectory( try { resolved = realpathSync.native(requested); if (!statSync(resolved).isDirectory()) { - throw new Error("Codex working directory must be a directory"); + throw new Error("Agent working directory must be a directory"); } } catch (error) { const code = (error as NodeJS.ErrnoException).code; if (code === "ENOENT") { throw new Error( - "Codex working directory must exist before provider admission", + "Agent working directory must exist before provider admission", ); } throw error; } if (resolved === parse(resolved).root) { - throw new Error("Codex working directory cannot be a filesystem root"); + throw new Error("Agent working directory cannot be a filesystem root"); } const configuredRoot = environment.PAPERCLIP_WORKSPACE_CWD; const hostHome = canonicalConfiguredPath(environment.HOME); if (hostHome && pathContains(resolved, hostHome)) { - throw new Error("Codex working directory cannot contain the host HOME"); + throw new Error("Agent working directory cannot contain the host HOME"); } if ( hostHome && @@ -92,7 +92,7 @@ export function validateCodexWorkingDirectory( ) ) { throw new Error( - "Codex working directory cannot overlap sensitive host HOME state", + "Agent working directory cannot overlap sensitive host HOME state", ); } if ( @@ -101,7 +101,7 @@ export function validateCodexWorkingDirectory( (configuredRoot === undefined || configuredRoot.trim().length === 0) ) { throw new Error( - "Codex working directory inside the host HOME requires an assigned workspace", + "Agent working directory inside the host HOME requires an assigned workspace", ); } const codexHome = canonicalConfiguredPath(environment.CODEX_HOME); @@ -110,7 +110,7 @@ export function validateCodexWorkingDirectory( pathContains(resolved, codexHome) || pathContains(codexHome, resolved) ) { - throw new Error("Codex working directory cannot overlap host CODEX_HOME"); + throw new Error("Agent working directory cannot overlap host CODEX_HOME"); } } if (configuredRoot !== undefined && configuredRoot.trim().length > 0) { @@ -122,7 +122,7 @@ export function validateCodexWorkingDirectory( isAbsolute(pathFromRoot) ) { throw new Error( - "Codex working directory is outside the assigned workspace", + "Agent working directory is outside the assigned workspace", ); } } @@ -154,7 +154,7 @@ export function validatePreparedLaunchWorkingDirectory( ); } if (workingDirectory === posix.parse(workingDirectory).root) { - throw new Error("Codex working directory cannot be a filesystem root"); + throw new Error("Agent working directory cannot be a filesystem root"); } return workingDirectory; } @@ -170,10 +170,10 @@ export function codexThreadWorkingDirectory( authority: CodexWorkingDirectoryAuthority = "local_filesystem", ): string { if (authority !== "runner_prepared_launch") { - if (expected === null) throw new Error("Codex working directory is required"); + if (expected === null) throw new Error("Agent working directory is required"); const returned = typeof reported === "string" ? reported : expected; if (resolve(returned) !== expected) { - throw new Error("Codex thread response changed the assigned working directory"); + throw new Error("Provider thread response changed the assigned working directory"); } return expected; } @@ -182,7 +182,7 @@ export function codexThreadWorkingDirectory( } const returned = validatePreparedLaunchWorkingDirectory(reported); if (expected !== null && returned !== expected) { - throw new Error("Codex thread response changed the assigned working directory"); + throw new Error("Provider thread response changed the assigned working directory"); } return returned; } @@ -217,16 +217,16 @@ function validateRemoteRunnerWorkingDirectory( ): string { if (!isNormalizedRemotePath(workingDirectory)) { throw new Error( - "Remote Codex working directory must be a normalized absolute path", + "Remote agent working directory must be a normalized absolute path", ); } if (workingDirectory === posix.parse(workingDirectory).root) { - throw new Error("Codex working directory cannot be a filesystem root"); + throw new Error("Agent working directory cannot be a filesystem root"); } const configuredRoot = environment.PAPERCLIP_WORKSPACE_CWD?.trim(); if (!configuredRoot) { throw new Error( - "Remote Codex working directory requires an assigned workspace", + "Remote agent working directory requires an assigned workspace", ); } if ( @@ -242,7 +242,7 @@ function validateRemoteRunnerWorkingDirectory( // canonical identity inside the authoritative filesystem before launch. if (workingDirectory !== configuredRoot) { throw new Error( - "Remote Codex working directory does not match the assigned workspace", + "Remote agent working directory does not match the assigned workspace", ); } return workingDirectory; diff --git a/packages/paperclip-runner/src/live/runner-prepared-launch-workspace.test.ts b/packages/paperclip-runner/src/live/runner-prepared-launch-workspace.test.ts index 6112d7f87bb..cef217f8f7c 100644 --- a/packages/paperclip-runner/src/live/runner-prepared-launch-workspace.test.ts +++ b/packages/paperclip-runner/src/live/runner-prepared-launch-workspace.test.ts @@ -71,7 +71,7 @@ it("reproduces the controller-side remote cwd requirement for plugin-owned launc try { const { backend, prepareLaunch, launches } = await pluginBackend(root, root, "remote_runner"); await expect(backend.openSession({ identity: sessionIdentity, workingDirectory: "/controller/workspace" })) - .rejects.toThrow("Remote Codex working directory requires an assigned workspace"); + .rejects.toThrow("Remote agent working directory requires an assigned workspace"); expect(prepareLaunch).not.toHaveBeenCalled(); expect(launches).toEqual([]); } finally { await rm(root, { recursive: true, force: true }); } diff --git a/packages/paperclip-runner/src/native-session-runtime.test.ts b/packages/paperclip-runner/src/native-session-runtime.test.ts index 0dfda06c42f..0f30e117452 100644 --- a/packages/paperclip-runner/src/native-session-runtime.test.ts +++ b/packages/paperclip-runner/src/native-session-runtime.test.ts @@ -6664,6 +6664,67 @@ describe("executeNativeSession recovery", () => { } }); + // A remote workspace epoch was abandoned, so the run was assigned a new + // sibling root while its checkpoint still names the old one. A checkpoint + // that requires the same session (an unfinished goal) ends with the + // permanent named code, never a generic retryable failure; a checkpoint that + // allows replacement continues in a fresh session in the assigned root. + it.each([ + ["same_session_only", false, false], + ["allow_replacement_after_governed_wait", false, false], + ["allow_replacement_after_resume_failure", true, false], + // An in-flight turn may have an unsettled external effect: never replaced, under any policy. + ["same_session_only", false, true], + ["allow_replacement_after_resume_failure", false, true], + ] as const)("handles a %s checkpoint whose remote workspace root moved (replaces=%s, in flight=%s)", async (providerRecoveryPolicy, replaces, inFlight) => { + const parent = "/home/daytona/paperclip-workspace/.paperclip-workspaces"; + const savedRoot = `${parent}/a5a34403-04fe-4e7e-97cf-d8f371a802a4-1-80214561-2151-4112-a43a-7d65f3071b56`; + const assignedRoot = `${parent}/a5a34403-04fe-4e7e-97cf-d8f371a802a4-5-ef79592c-6784-438f-8a17-9800dd2fa2fc`; + const checkpoint: PersistedNativeSession = { + backendKind: "runner", sessionId: "thread-1", identity, providerSessionId: "provider-session-1", + workingDirectory: savedRoot, providerRecoveryPolicy, cursor: "0", activeTurnId: inFlight ? "turn-in-flight" : null, + terminalTurns: [], pendingRuntimeRequests: [], lineage: [], + }; + const transportFactory = vi.fn(() => new FakeCodexTransport()); + const backend = createCodexNativeSessionBackend({ ...input, workspace: { ...input.workspace, cwd: assignedRoot } }, { + runnerInstanceId: "runner-recovery", transportFactory, + workingDirectoryAuthority: "remote_runner", environment: { PAPERCLIP_WORKSPACE_CWD: assignedRoot }, + }); + const replacementAttempted = new Error("replacement attempted"); + const openReplacementSession = vi.fn(async (sessionInput: { workingDirectory?: string }) => { + expect(sessionInput.workingDirectory).toBe(assignedRoot); + throw replacementAttempted; + }); + const openRun = vi.fn(async () => undefined); + const failure = await executeNativeSession({ + input: { ...input, workspace: { ...input.workspace, cwd: assignedRoot } }, + backend: { descriptor: () => backend.descriptor(), openSession: sessionInput => backend.openSession(sessionInput), + openReplacementSession, recoverSession: (snapshot, options) => backend.recoverSession!(snapshot, options) }, + controlPlane: { + openRun, appendEvent: vi.fn(), completeRun: vi.fn(), + loadSessionCheckpoint: async () => structuredClone(checkpoint), + replayEvents: async () => ({ events: [], highestContiguousSourceSeq: 0 }), + }, + runnerInstanceId: "runner-recovery", controlPlaneInstanceId: "control-recovery", + }).catch((error: unknown) => error); + if (replaces) { + expect(failure).toBe(replacementAttempted); + expect(openReplacementSession).toHaveBeenCalledOnce(); + } else { + if (inFlight) { + expect(failure).toBeInstanceOf(NativeProviderSideEffectPendingError); + expect((failure as NativeProviderSideEffectPendingError).code).toBe("native_provider_side_effect_pending"); + } else { + expect(failure).toBeInstanceOf(NativeProviderStateIncompatibleError); + expect((failure as NativeProviderStateIncompatibleError).code).toBe("native_provider_state_incompatible"); + } + expect(openReplacementSession).not.toHaveBeenCalled(); + expect(openRun).not.toHaveBeenCalled(); + } + // No Runner or provider process starts for a session that cannot resume here. + expect(transportFactory).not.toHaveBeenCalled(); + }); + it("never replaces a session after a deterministic, non-destructive recovery refusal", async () => { const outcomes = [ { failureClass: PROVIDER_ATTACH_REFUSED, reason: "run.attach cannot change protected launch arguments", diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index fff7e2b6e6f..e138de3c335 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -8549,7 +8549,7 @@ export function nativeSessionFailureSourceCode( } const NATIVE_PROVIDER_SIDE_EFFECT_PENDING_ACTION = - "The saved provider session has a tool call whose result never reached the runner, so Paperclip did not replace the session or retry it. Reconcile the action: check whether it ran and record the outcome. The task then continues in a fresh provider session in the same workspace. The saved session and workspace are unchanged."; + "The saved provider session has an unfinished provider turn, or a tool call whose result never reached the runner, so Paperclip did not replace the session or retry it. Reconcile the action: check whether it ran and record the outcome. The task then continues in a fresh provider session in the same workspace. The saved session and workspace are unchanged."; const NATIVE_PROVIDER_STATE_INCOMPATIBLE_ACTION = "The current runner cannot restore this task's saved provider session, so retrying this run cannot succeed. Retry the task to continue in a fresh provider session with the same workspace. The earlier provider conversation is not carried over.";